list comprehensions put non-names into namespaces!

Ben Cartwright 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 "_[1]" (or presumably "_[2]", "_[3]" 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()
> call.

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
289:

"""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
surrounding scope."""

Source: http://www.python.org/dev/peps/pep-0289/

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)]
      print x
  >>> f()
  9
  >>> # no warning yet..

2.5 is in alpha now, hopefully the warning will be added.

--Ben




More information about the Python-list mailing list