I wrote a function def_function, that dynamically defines another function at runtime.
main.py
#!/usr/bin/python3
def def_function(name):
lines = list()
lines.append('global {}\n'.format(name))
lines.append('def {}():\n'.format(name))
lines.append(' print(\'{}() has been called!\')\n'.format(name))
code = ''.join(lines)
function = compile(code, '', 'exec')
exec(function)
def_function('foo')
foo()
Running main.py gives the expected output:
foo() has been called!
Now I'd like to move the definition of def_function to module.py and import it from main.py.
module.py
def def_function(name):
lines = list()
lines.append('global {}\n'.format(name))
lines.append('def {}():\n'.format(name))
lines.append(' print(\'{}() has been called!\')\n'.format(name))
code = ''.join(lines)
function = compile(code, '', 'exec')
exec(function)
main.py
#!/usr/bin/python3
from module import def_function
def_function('foo')
foo()
This results in the following error:
Traceback (most recent call last):
File "./main.py", line 6, in <module>
foo()
NameError: name 'foo' is not defined
I've already googled my problem and read various questions at SO, but I couldn't find a solution. Please help me.
def_function.def ...)