You can return the __enter__ method __enter__ different object than self if you do not want the user to be able to call methods in the context manager object itself.
class Foo(object): def __enter__(self): print("In __enter__") return Bar() def __exit__(self, typ, val, traceback): print("In __exit__") class Bar(object): def func1(self): print("In func1") def func2(self): print("In func2")
Of course, you can have the Foo and Bar classes more related to each other than in this example. For example, the Foo class may pass itself to the Bar constructor in __enter__ .
Calling Foo().func1() will not work for the obvious reason that Foo does not have such a method. If you want Bar not to be visible to the user, you can prefix his name with an underscore (hinting that it is internal) or even nest it in the Foo class (or even the __enter__ method if you really want to be extreme).
Blckknght
source share