generator expression works in shell, NameError in script

ryles rylesny at gmail.com
Thu Jun 18 23:09:25 EDT 2009


On Jun 18, 9:56 am, nn <prueba... at latinmail.com> wrote:
> On Jun 18, 8:38 am, guthrie <grguth... at gmail.com> wrote:
>
>
>
> > On Jun 17, 6:38 pm, Steven Samuel Cole <steven.samuel.c... at gmail.com>
> > wrote:
>
> > > Still don't really understand why my initial code didn't work, though...
>
> > Your code certainly looks reasonable, and looks to me like it "should"
> > work. The comment of partial namespace is interesting, but
> > unconvincing (to me) - but I am not a Python expert! It would
> > certainly seem that within that code block it is in the local
> > namespace, not removed from that scope to be in another.
>
> > Seems that it should either be a bug, or else is a design error in the
> > language!
>
> > Just as in the above noted "WTF" - non-intuitive language constructs
> > that surprise users are poor design.
>
> 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]
> ...
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
>   File "<stdin>", line 3, in x
>   File "<stdin>", line 3, in <listcomp>
> NameError: global name 'lst' is not defined
>
>
>
>

I believe it works in 2.x because unlike generator expressions, list
comprehensions do not create a new scope. However, in 3.0 list
comprehensions are actually treated as list(<generator>).

http://docs.python.org/reference/expressions.html
http://www.python.org/dev/peps/pep-0289



More information about the Python-list mailing list