list comprehensions put non-names into namespaces!
bencvt at gmail.com
Fri May 26 02:12:28 CEST 2006
skip at pobox.com wrote:
> Lonnie> List comprehensions appear to store their temporary result in a
> Lonnie> variable named "_" (or presumably "_", "_" etc for
> Lonnie> nested comprehensions)
> Known issue. Fixed in generator comprehensions. Dunno about plans to fix
> it in list comprehensions. I believe at some point in the future they may
> just go away or become syntactic sugar for a gen comp wrapped in a list()
The latter, starting in Python 3.0. It won't be fixed before Python
3.0 because it has the potential to break existing 2.x code. From PEP
"""List comprehensions also "leak" their loop variable into the
surrounding scope. This will also change in Python 3.0, so that the
semantic definition of a list comprehension in Python 3.0 will be
equivalent to list(<generator expression>). Python 2.4 and beyond
should issue a deprecation warning if a list comprehension's loop
variable has the same name as a variable used in the immediately
Also mentioned in PEP 3100.
Doesn't look like the deprecation warning was ever implemented for 2.4,
though. On my 2.4.3:
>>> def f():
[x for x in range(10)]
>>> # no warning yet..
2.5 is in alpha now, hopefully the warning will be added.
More information about the Python-list