generator expression works in shell, NameError in script

Miles Kaufmann milesck at umich.edu
Sun Jun 21 15:47:32 EDT 2009


On Jun 19, 2009, at 8:45 AM, Bruno Desthuilliers wrote:
> >>> class Foo(object):
> ...     bar = ['a', 'b', 'c']
> ...     baaz = list((b, b) for b in bar)
>
> but it indeed looks like using bar.index *in a generator expression*  
> fails (at least in 2.5.2) :
>
> >>> class Foo(object):
> ...     bar = ['a', 'b', 'c']
> ...     baaz = list((bar.index(b), b) for b in bar)
> ...
> Traceback (most recent call last):
>  File "<stdin>", line 1, in <module>
>  File "<stdin>", line 3, in Foo
>  File "<stdin>", line 3, in <genexpr>
> NameError: global name 'bar' is not defined

The reason that the first one works but the second fails is clearer if  
you translate each generator expression to the approximately  
equivalent generator function:

class Foo(object):
     bar = ['a', 'b', 'c']
     def _gen(_0):
         for b in _0:
             yield (b, b)
     baaz = list(_gen(iter(bar))

# PEP 227: "the name bindings that occur in the class block
# are not visible to enclosed functions"
class Foo(object):
     bar = ['a', 'b', 'c']
     def _gen(_0):
         for b in _0:
             yield (bar.index(b), b)
     baaz = list(_gen(iter(bar))

-Miles




More information about the Python-list mailing list