gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 20:46:28 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)局部变量的操作,包括变量赋值、导入、函数定义、类定义等。它可以分配给全局变量,如果它使用全局声明,但不使用本地声明。

返回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/56554437/

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