I can put an import statement in a string, exec it, and it works (prints a random digit):
code = """
import random
def f():
print random.randint(0,9)
"""
def f():
pass
exec code
f()
Now, if I put exec code
and f()
in their own function and call it, it doesn't work.
def test():
exec code
f()
test()
It says NameError: global name 'random' is not defined
.
How about this:
def test():
exec (code, globals())
f()