I have an auto-generated Python code snippet which I'd like to exec()
from within a class instance.
A simplified snippet looks like this:
prog = """
def func1():
func2()
def func2():
pass
func1()
"""
class test():
def run(self):
exec(prog)
test().run() # results in NameError: name 'func2' is not defined
exec(prog) # works
While func1()
can be called in both cases, func2
isn't found when exec()
'ing from within the class. If I run the exec(prog)
first, then even the test().run()
succeeds. It seems that the previous exec call left func2
at some place in the namespace where it can later be found when called from within the class.
Is there a simple and clean way to call such a code snippet containing several functions from within a class?