gpt4 book ai didi

python - Python 2 与 3 中的评估范围

转载 作者:IT老高 更新时间:2023-10-28 22:18:59 26 4
gpt4 key购买 nike

我在 Python 3 中遇到了奇怪的 eval 行为 - 在列表推导中调用 eval 时,不会拾取局部变量。

def apply_op():
x, y, z = [0.5, 0.25, 0.75]
op = "x,y,z"
return [eval(o) for o in op.split(",")]
print(apply_op())

Python 3 中的错误:

▶ python --version
Python 3.4.3
▶ python eval.py
Traceback (most recent call last):
File "eval.py", line 7, in <module>
print(apply_op())
File "eval.py", line 5, in apply_op
return [eval(o) % 1 for o in op.split(",")]
File "eval.py", line 5, in <listcomp>
return [eval(o) % 1 for o in op.split(",")]
File "<string>", line 1, in <module>
NameError: name 'x' is not defined

它在 Python 2 中运行良好:

▶ python --version
Python 2.7.8
▶ python eval.py
[0.5, 0.25, 0.75]

将它移到列表推导之外可以解决问题。

def apply_op():
x, y, z = [0.5, 0.25, 0.75]
return [eval("x"), eval("y"), eval("z")]

这是预期的行为,还是错误?

最佳答案

在错误跟踪器中有一个 已关闭 问题:Issue 5242 .

此错误的解决方案是无法修复

问题中的一些评论如下:

This is expected, and won't easily fix. The reason is that list comprehensions in 3.x use a function namespace "under the hood" (in 2.x, they were implemented like a simple for loop). Because inner functions need to know what names to get from what enclosing namespace, the names referenced in eval() can't come from enclosing functions. They must either be locals or globals.

eval() is probably already an hack, there's no need to add another hack to make it work. It's better to just get rid of eval() and find a better way to do what you want to do.

关于python - Python 2 与 3 中的评估范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29336616/

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