Whatever is returned from __enter__ . From the documentation on the __enter__ method of __enter__ managers :
contextmanager.__enter__()
Enter the runtime context and return this object or another object associated with the runtime context. The value returned by this method is bound to the identifier in the as expression of the with statements using this context manager.
(Emphasize mine)
The result of the __enter__ call __enter__ well be a context manager, nothing in the specification prohibits this. Of course, this may be another object related to the context of the runtime, because the state of the documents.
Objects returned from __enter__ can be used again and again as context managers. file objects , for example:
with open('test_file') as f1: # file.__enter__ returns self with f1 as f2: # use it again, get __self__ back print("Super context managing") with f2 as f3, f1 as f4: # getting weird. print("This can go on since f1.__enter__ returns f1") print("f1.__exit__ has been called here, though :)") print("f1 closed: {}".format(f1.closed))
Not that the previous one made sense, but simply to make it clear.
Jim fasarakis hilliard
source share