Is there a pythonic way to wrap an class using with statement?

I did the following, it works, but I have doubts on its robustness.

import B

class A():
    def __init__(self):
        self._b = B()

    def __enter__(self):
        return self._b .__enter__()

    def __exit__(self, exc_type, exc_val, exc_tb):
        return self._b .__exit__(exc_type, exc_val, exc_tb)

I know the methods B.__enter__() and B.__exit__() should not be used outside B, but I did not find another way to do this. is it acceptable to wrap a class this this way? is there another way?

I am aware that the answer might be: "No, this is exactly what the with statement it meant to prevent"

Read more here:

Content Attribution

This content was originally published by Rémi Baudoux at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: