gpt4 book ai didi

python - 使用 `exec` 调用时如何更新局部变量?

转载 作者:IT老高 更新时间:2023-10-28 20:32:05 24 4
gpt4 key购买 nike

我以为这会打印 3,但它会打印 1:

# Python3

def f():
a = 1
exec("a = 3")
print(a)

f()
# 1 Expected 3

最佳答案

此问题在 Python3 bug list 中有所讨论。 .最终,要获得这种行为,您需要这样做:

def foo():
ldict = {}
exec("a=3",globals(),ldict)
a = ldict['a']
print(a)

如果您检查 the Python3 documentation on exec ,您将看到以下注释:

The default locals act as described for function locals() below: modifications to the default locals dictionary should not be attempted. Pass an explicit locals dictionary if you need to see effects of the code on locals after function exec() returns.

这意味着单参数 exec 不能安全地执行任何会绑定(bind)局部变量的操作,包括变量赋值、导入、函数定义、类定义等。它可以分配给全局变量,如果它使用 global 声明,而不是本地声明。

引用 a specific message on the bug report ,格奥尔格·布兰德尔说:

To modify the locals of a function on the fly is notpossible without several consequences: normally, function locals are notstored in a dictionary, but an array, whose indices are determined atcompile time from the known locales. This collides at least with newlocals added by exec. The old exec statement circumvented this, becausethe compiler knew that if an exec without globals/locals args occurredin a function, that namespace would be "unoptimized", i.e. not using thelocals array. Since exec() is now a normal function, the compiler doesnot know what "exec" may be bound to, and therefore can not treat isspecially.

重点是我的。

所以它的要点是Python3可以更好地优化局部变量的使用,默认允许这种行为。

为了完整起见,正如上面评论中提到的,这确实在 Python 2.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

关于python - 使用 `exec` 调用时如何更新局部变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1463306/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com