generator expression works in shell, NameError in script

Mark Dickinson dickinsm at
Fri Jun 19 15:08:18 CEST 2009

On Jun 19, 1:45 pm, Bruno Desthuilliers <bruno.
42.desthuilli... at websiteburo.invalid> wrote:
> [...]
> 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
> Looks like a bug to me :-/

I think it's working as intended:  name resolution for
nested scopes skips intermediate class scopes.  The
'Discussion' section of PEP 227 (Statically Nested Scopes)
is illuminating;  here's a snippet:

"""Names in class scope are not accessible.  Names are resolved in
the innermost enclosing function scope.  If a class definition
occurs in a chain of nested scopes, the resolution process skips
class definitions.  This rule prevents odd interactions between
class attributes and local variable access."""


More information about the Python-list mailing list