exec doesn't pick up variables from closure

前端 未结 1 886
感动是毒
感动是毒 2021-01-18 10:10

I\'m a little curious why the following code raises a NameError.

>>> s = \"\"\"
... foo = [1,2,3]
... def bar():
...    return foo[1]
.         


        
相关标签:
1条回答
  • 2021-01-18 10:47

    It turns out that the answer was there all along in the docs:

    If two separate objects are given as globals and locals, the code will be executed as if it were embedded in a class definition.

    Since I'm passing in both globals and locals, it executes as if it were in a class.

    class Foo(object):
        foo = [1,2,3]
        @staticmethod
        def bar():
           return foo[1]
    

    not surprisingly doesn't work either :).

    For anyone interested in a workaround, you can inject namespace back into namespace['bar'].func_globals1 (inspired by this):

    >>> namespace['bar'].func_globals.update(namespace)
    >>> namespace['bar']()
    2
    

    Nice.

    1It would be namespace['bar'].__globals__.update on python3.x

    0 讨论(0)
提交回复
热议问题