这个问题在Python3 bug list篇文章中有所讨论.最终,要获得这种行为,你需要做:
def foo():
ldict = {}
exec("a=3",globals(),ldict)
a = ldict['a']
print(a)
如果你 Select the Python3 documentation on exec
,你会看到下面的注释:
默认局部变量的作用如下面函数
locals()
:modifications to the default locals dictionary should not be attempted所述.如果需要在函数exec()返回后查看代码对局部变量的影响,请传递一个显式局部变量字典.
这意味着一个参数exec
不能安全地执行任何绑定局部变量的操作,包括变量赋值、导入、函数定义、类定义等.如果它使用global
声明,它可以赋值给全局变量,但不能赋值给局部变量.
回到a specific message on the bug report岁,格奥尔格·布兰德尔说:
动态修改函数的局部变量是不正确的
重点是我的.
因此,其要点是Python3可以更好地优化局部变量的使用,默认情况下允许这种行为.
为了完整性起见,正如上面的 comments 所提到的,这does条代码在Python2中可以正常工作.X:
Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41)
[GCC 4.3.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> def f():
... a = 1
... exec "a=3"
... print a
...
>>> f()
3