I came across bizarre eval behavior in Python 3 - local variables aren't picked up when eval is called in a list comprehension.
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())
It errors 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
And it works fine in Python 2:
▶ python --version
Python 2.7.8
▶ python eval.py
[0.5, 0.25, 0.75]
Moving it outside of the list comprehension removes the problem.
def apply_op():
x, y, z = [0.5, 0.25, 0.75]
return [eval("x"), eval("y"), eval("z")]
Is this intended behavior, or is it a bug?