eval fails to detect an iterating variable when evaluating a generator

Viewed 159

Consider the following code:

print([a for a in [0] if eval("a in [0]")])
b = 0
print([b if eval("True in (x == b for x in [0])") else ''])
print([a for a in [0] if eval("True in (x == a for x in [0])")])

The output of this is:

[0]
[0]
Traceback (most recent call last):
  File "…", line 4, in <module>
    print([a for a in [0] if eval("False in (x == a for x in [0])")])
  File "…", line 4, in <listcomp>
    print([a for a in [0] if eval("False in (x == a for x in [0])")])
  File "<string>", line 1, in <module>
  File "<string>", line 1, in <genexpr>
NameError: name 'a' is not defined

The first eval uses the iterator a in a plain eval, and it works.

The second eval uses a static variable b when evaluating a generator, and it works.

The third eval combines the two ideas - it uses an iterator variable when evaluating a generator, and it fails to detect the variable and raises an error. Why does this happen?

1 Answers
Related