Namespace puzzle, list comprehension fails within class definition

John Ladasky john_ladasky at sbcglobal.net
Mon Jan 12 21:25:40 CET 2015


I've never come across this before.  Here's a minimal example (in Python 3.4):


Code:
---------------------------------------------------------------------

d = {0:"a", 1:"b", 2:"c", 3:"d"}
e = [d[x] for x in (0,2)]

class Foo:
    f = {0:"a", 1:"b", 2:"c", 3:"d"}
    print(f)
    g = [f[x] for x in (0,2)]

foo = Foo()


Output:
---------------------------------------------------------------------

{0: 'a', 1: 'b', 2: 'c', 3: 'd'}

Traceback (most recent call last):
  File "minimal example.py", line 6, in <module>
    class Foo:
  File "minimal example.py", line 9, in Foo
    g = [f[x] for x in (0,2)]
  File "minimal example.py", line 9, in <listcomp>
    g = [f[x] for x in (0,2)]
NameError: name 'f' is not defined

---------------------------------------------------------------------

When I am working in the top-level namespace, I get no errors when referencing the dictionary, d, inside the list comprehension which generates e.

When I am working inside the class namespace, the print function call on line 8 recognizes the name f and prints the dictionary bound to that name.

However, the LIST COMPREHENSION defined inside the class namespace generates a NameError.

In all my years of Python programming, I guess that I have never tried to define a class attribute using a list comprehension.  Why doesn't it work?  Any advice, and suggestions for Pythonic workarounds, are appreciated.



More information about the Python-list mailing list