generator expression works in shell, NameError in script

greg greg at
Fri Jun 19 06:28:10 CEST 2009

nn wrote:

> This is certainly an odd one. This code works fine under 2.6 but fails
> in Python 3.1.
>>>>class x:
> ...     lst=[2]
> ...     gen=[lst.index(e) for e in lst]

In 3.x it was decided that the loop variables in a list
comprehension should be local, and not leak into the
surrounding scope. This was implemented by making the
list comprehension into a nested function.

Unfortunately this leads to the same unintuitive
behaviour as a genexp when used in a class scope.


More information about the Python-list mailing list