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

How about this:

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

What's going on here is that the module random is being imported as a local variable in test. Try this

def test():
    exec code
    print globals()
    print locals()
    f()

will print

{'code': '\nimport random\ndef f():\n    print random.randint(0,9)\n', '__builtins__': <module '__builtin__' (built-in)>, '__package__': None, 'test': <function test at 0x02958BF0>, '__name__': '__main__', '__doc__': None}
{'random': <module 'random' from 'C:\Python27\lib\random.pyc'>, 'f': <function f at 0x0295A070>}

The reason f can't see random is that f is not a nested function inside of test--if you did this:

def test():
    import random
    def f():
        print random.randint(0,9)
    f()

it would work. However, nested functions require that the outer function contains the definition of the inner function when the outer function is compiled--this is because you need to set up cell variables to hold variables that are shared between the two (outer and inner) functions.

To get random into the global namespace, you would just do something like this

exec code in globals(),globals()

The arguments to exec after the in keyword are the global and local namespaces in which the code is executed (and thus, where name's defined in the exec'd code are stored).


Specify that you want the global random module

code = """
import random
def f():
  global random
  print random.randint(0,9)
"""

The problem here is that you're importing the random module into your function scope, not the global scope.