Rémi Baudoux
Rémi Baudoux

Reputation: 559

Is there a pythonic way to wrap a 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 is meant to prevent"

Upvotes: 0

Views: 89

Answers (2)

Rémi Baudoux
Rémi Baudoux

Reputation: 559

The issue can actually be solved by using a sub-class instead of a wrapper (Thanks @tripleee) I overlooked this option because the parent class had to be instantiated differently depending on the child class parameters. But this can be done as follow:

import B

class A(B):
    def __init__(self, parameter):
        if parameter == 1:
            super().__init__(x=1)
        elif parameter == 2:
            super().__init__(y=2, z=3)
        else:
            raise ValueError

Upvotes: 0

jurez
jurez

Reputation: 4667

The sentence "methods B.__enter__() and B.__exit__() should not be used outside B" is meant to teach newbie programmers how to properly use with statement.

However, you are implementing it. What you are doing is perfectly acceptable and correct. In fact I do not know of any better way either.

Upvotes: 3

Related Questions