exec doesn't pick up variables from closure
问题 I'm a little curious why the following code raises a NameError . >>> s = """ ... foo = [1,2,3] ... def bar(): ... return foo[1] ... """ >>> namespace = {} >>> exec(s, {'__builtins__': None}, namespace) >>> print namespace {'foo': [1, 2, 3], 'bar': <function bar at 0x7f79871bd0c8>} >>> namespace['bar']() At the normal interpreter level, we can find foo in bar.func_globals or bar.func_closure if in a function. I guess I'm wondering why namespace['bar'] doesn't put foo in func_closure ... 回答1: