Deprecated: list comp leak use

Terry Reedy tjreedy at udel.edu
Tue Oct 21 00:18:28 EDT 2003


Announcement/Warning

In the current implementation of list comprehensions, for-part control
variables leak to the surrounding context.  Example:
>>> [i for i in [1,2]]
[1, 2]
>>> print i
2
The name i was bound within the list comprehension.  The Reference
Manual currently says nothing about this behavior.

On py-dev today (now yesterday), after GvR described how the leak
could be plugged, and other developers urged that it be so plugged,
GvR declared use of such leaked bindings as deprecated, and the
leakage subject to cessation in a future version .

Since people have posted at least one clever hack exploiting the
leakage (for simulating assignment expressions), I though this
followup might be useful.

This decision and any future patches will *NOT* affect for-loop
variables.  The following search idiom, for instance, will continue to
work:

for item in seq:
    if pred(item): break
else:
    item = default #usually sentinal value such as None
# item is now first item meeting pred criterion or default

Terry J. Reedy






More information about the Python-list mailing list