stieß ich auf bizarres eval Verhalten in Python 3 - lokale Variablen nicht abgeholt werden, wenn eval in einer Liste Verständnis genannt wird.Eval Umfang in Python 2 vs. 3
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())
Es Fehler in 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
Und es funktioniert gut in Python 2:
▶ python --version
Python 2.7.8
▶ python eval.py
[0.5, 0.25, 0.75]
bewegen sie außerhalb der Liste Verständnis beseitigt das Problem.
def apply_op():
x, y, z = [0.5, 0.25, 0.75]
return [eval("x"), eval("y"), eval("z")]
Ist das beabsichtigte Verhalten, oder ist es ein Fehler?
[hier] (http://stackoverflow.com/questions/4198906/python-list-comprehension-rebind-names-even- after-scope-of-comprehension-is-thi) gibt einige weitere Informationen über Bereiche und Listen-Comprehensions in p2 und p3. – Marcin
Der Spaßfaktor ist, wenn man ihn aus dem Funktionsumfang verschiebt, wird das Problem ebenfalls gestoppt. im Zusammenhang: http://bugs.python.org/msg81898 – wim
@Marcin dies ist nicht mit dem Umfang der Schleife Variable außerhalb von List Comprehensions Leaking. es geht um den Umfang der Schleifenvariablen innerhalb des Verständnisses selbst. – wim