Why does this NameError happen?
(Blank lines before prompts inserted for readability.)
$ python3
Python 3.4.10 (default, Oct 4 2019, 19:39:58)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-23)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import pdb
>>> def blah():
... foo = "ab"
... pdb.set_trace()
...
>>> blah()
--Return--
> <stdin>(3)blah()->None
(Pdb) [bar for bar in "ac" if bar in foo]
*** NameError: name 'foo' is not defined
All of the following work okay:
(Pdb) foo
'ab'
(Pdb) [bar for bar in foo]
['a', 'b']
(Pdb) [bar for bar in "ac" if bar in "ab"]
['a']
So it is specifically an issue for variables which are referenced in the if clause, other than the loop variable itself.
Same behaviour as above also seen in python 3.6.9 (default, Apr 18 2020, 01:56:04).
But in python 2 (2.6.6 or 2.7.17), using the same commands as above, I get:
(Pdb) [bar for bar in "ac" if bar in foo]
['a']