2

I am encountering a weird situation. I want to check if my variables x, y, z exist.

To do that, I tried:

>>> [var in locals() for var in ["x", "y", "z"]]
[False, False, False]

Then, I assign x, y, z to some values:

>>> x, y, z = 1, 2, 3

Nevertheless, I still have:

>>> [var in locals() for var in ["x", "y", "z"]]
[False, False, False]

But x, y, z exist one by one:

>>> for var in ["x", "y", "z"]: 
...     print(var in locals())
... 
True
True
True

Does someone have an explanation?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
thomask
  • 743
  • 7
  • 10

1 Answers1

6

See:https://portingguide.readthedocs.io/en/latest/comprehensions.html

In Python 3, list expressions have their own scope: they are functions, just defined with a special syntax, and automatically called. Thus, the iteration variable(s) don’t “leak” out:

Reference locals() outside of the comprehension

>>> my_locals = locals()
>>> [var in my_locals for var in ["x", "y", "z"]]
[True,True,True]

tomgalpin
  • 1,943
  • 1
  • 4
  • 12