Why doesn't an import in an exec in a function work?

Alex Varga picture Alex Varga · Sep 20, 2012 · Viewed 14.4k times · Source

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.

Answer

Yevgen Yampolskiy picture Yevgen Yampolskiy · Sep 20, 2012

How about this:

def test():
    exec (code, globals())
    f()