There are essentially three ways to use the with statement:
Use an existing context manager:
with manager:
pass
Create a context manager and bind its result to a variable:
with Manager() as result:
pass
Create an context manager and discard its return value:
with Manager():
pass
If we have place a function get_manager()
inside the three with blocks above, is there any implementation that can return the enclosing context manager, or at least their __exit__
function?
It's obviously easy in the first case, but I can't think of a way to make it work in the other two. I doubt it's possible to get the entire context manager, since the value stack is popped immediately after the SETUP_WITH
opcode. However, since the __exit__
function is stored on the block stack by SETUP_WITH
, is there some way to access it?