Issue
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.
Solution
You define foo
in module.py
scope. Do not forget import module.py
.
Call foo()
, as module.foo()
.
import module
module.def_function('foo')
module.foo()
May help you https://realpython.com/python-scope-legb-rule/
Additional
Add this after exec(function)
. Also import sys
.
setattr(sys.modules['__main__'], name, globals()[name])
Setattr it's function assigns the value to the attribute of object or create new attribute. https://docs.python.org/3/library/functions.html#setattr
module.py
import sys
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)
setattr(sys.modules['__main__'], name, globals()[name])
main.py
from module import def_function
def_function('foo')
foo()
Answered By - fabelx Answer Checked By - Mildred Charles (PHPFixing Admin)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.