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

前端 未结 3 929

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)
         


        
相关标签:
3条回答
  • 2020-12-03 03:15

    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.

    0 讨论(0)
  • 2020-12-03 03:20

    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).

    0 讨论(0)
  • 2020-12-03 03:24

    How about this:

    def test():
        exec (code, globals())
        f()
    
    0 讨论(0)
提交回复
热议问题