The with
block doesn't exist as a separate code object, so no. See this similar question. In that case, the questioner was trying to do the reverse (access the context manager from inside the code block), but as this answer explains, the with
block is not a separate scope, so it doesn't really have any separate status.
You can see this with an example:
import contextlib
import dis
@contextlib.contextmanager
def silly():
yield
def foo():
print "Hello"
with silly():
print "Inside"
print "Goodbye"
and then
>>> dis.dis(foo.__code__)
2 0 LOAD_CONST 1 (u'Hello')
3 PRINT_ITEM
4 PRINT_NEWLINE
3 5 LOAD_GLOBAL 0 (silly)
8 CALL_FUNCTION 0
11 SETUP_WITH 10 (to 24)
14 POP_TOP
4 15 LOAD_CONST 2 (u'Inside')
18 PRINT_ITEM
19 PRINT_NEWLINE
20 POP_BLOCK
21 LOAD_CONST 0 (None)
>> 24 WITH_CLEANUP
25 END_FINALLY
5 26 LOAD_CONST 3 (u'Goodbye')
29 PRINT_ITEM
30 PRINT_NEWLINE
31 LOAD_CONST 0 (None)
34 RETURN_VALUE
You can see that the with
block's code is just inside the function's code object along with everything else. It doesn't exist as a separate code object and isn't distinguished from the rest of the function's code. You can't get it out in any sane way (by which I mean, without hacking the bytecode).