python - Defining a function with exec from inside a function in global environment -
i have function that, when called, should define function use of exec
, make new function available main program. mwe following.
main program:
#!/usr/bin/python ext import makef makef() saya()
external module:
def makef(): script="def saya():\n\tprint 'aah'" exec(script) saya() return
what want able call inner function saya()
main program, in example output should
aah aah
but instead returns
aah traceback (most recent call last): file "mwe.py", line 5, in <module> saya() nameerror: name 'saya' not defined
which kind of expected, replace exec(script)
line exec(script,globals)
, according docs, instead get
traceback (most recent call last): file "mwe.py", line 4, in <module> makef() file "/home/tomas/tests/ext.py", line 3, in makef exec(script,globals,locals) typeerror: exec: arg 2 must dictionary or none
i have feeling i'm missing pretty obvious here can't figure out. appreciated.
thank you.
you have created function inside makef
not visible in scope of external module outside function.
if want call main, return saya
:
def makef(): script="def saya():\n\tprint('aah')" exec(script) return saya
then in main:
f = makef() f()
to same behaviour in python3 exec no longer statement function,you can use lambda dict:
def makef(): d = {} "saya = lambda: print('aah')" exec("saya = lambda: print('aah')",d) return d["saya"] ext import makef f = makef() f()