Is this a bug, or is it me?

Peter Otten __peter__ at web.de
Thu Jan 17 10:55:56 EST 2008


cptnwillard wrote:

> Hello all,
> For some reason, the following does not work :
> 
> 
> class C:
>     TYPES = [None]
>     DICT = {}
>     for Type in TYPES:
>         DICT.update((E,Type) for E in [1])
> 
>>>> NameError: global name 'Type' is not defined
> 
> 
> What do you think? Is this a bug?

Here is a simpler example:

>>> class A:
...     a = 42
...     list(a for _ in "a")
... 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in A
  File "<stdin>", line 3, in <genexpr>
NameError: global name 'a' is not defined

The equivalent code using a list comprehension instead of the generator
expression works without complaint:

>>> class A:
...     a = 42
...     [a for _ in "a"]
... 
>>> 

So it seems that Python gets puzzled by the extra scope introduced by the
genexp, i. e. you are seeing an obscure variant of the following
(expected) behaviour:

>>> class B:
...     a = 42
...     def f(): a
...     f()
... 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in B
  File "<stdin>", line 3, in f
NameError: global name 'a' is not defined

I think you should file a bug report, though making the genexp recognizing
the class scope probably isn't worth the effort.

Peter



More information about the Python-list mailing list