When I get hold of a code object (via internals like .func_code
or __code__
in Python 3), is there any way of calling this piece of code? Simply calling it does not work:
def f(): pass
f.func_code()
results in
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'code' object is not callable
This can come in handy when you like to unit-test a nested function:
def f():
def g():
return 3
f.x = g
return g() + 1
f.func_code.co_consts[1]
results in
<code object g at 0x7f123991b930, file "<stdin>", line 2>
Of course, this piece of code still needs a context etc. but that's not my question here.