Python - How to check function code generated with exec
I have a function that was created using exec()
inside another function and passed as an argument to the main program. How can I get the code of the specified function? I tried inspec.getsourcelines()
and inspec.getsource()
but I get the following error
IOError: could not get source code
Is there a way to get around this?
MWE main file:
#!/usr/bin/python
from ext import makeF
import inspect
f=makeF()
f()
inspect.getsource(f)
then the external file:
def makeF():
script="def sayA():\n\tprint('Aah')"
exec(script)
return sayA
source to share
In python 3, the solution is an attribute __globals__
for functions.
In your example:
>>> f.__globals__['txt']
"def sayA():\n\tprint('Aah')"
Unfortunately I couldn't find anything similar to Python 2.
The reason the other methods fail to work is because they use the module file name and you don't have a file here.
source to share
It's impossible. I dug around and came to the same conclusion as in this answer .
I don't know your code, but I think that in your particular case, you could return a custom object containing the source code of the function (which you have, you pass it to exec) along with the actual compiled function. You could use Python's magic technique __call__
to better emulate the original behavior. Here's a sample:
class FunctionWithCode:
def __init__(self, source, func_name):
exec(source)
self.source = source
self.func = locals()[func_name]
def __call__(self, *args, **kwargs):
self.func(*args, **kwargs)
f = FunctionWithCode("def sayA():\n\tprint('Aah')", 'sayA')
f()
which prints Aah as expected. You need to know the name of the function when creating the object, but this is the same for your sample code.
source to share