2

While there are numerous ways around this, because of a personality fault I can't let it go until I understand the nature of the failure.

Attempting:

class OurFavAnimals(object):
    FAVE = 'THATS ONE OF OUR FAVORITES'
    NOTFAVE = 'NAH WE DONT CARE FOR THAT ONE'
    UNKNOWN = 'WHAT?'
    FAVES = defaultdict(lambda: UNKNOWN, {x:FAVE for x in ['dog', 'cat']})
    FAVES['Crab'] = NOTFAVE 

Fails with:

      3     NOTFAVE = 'NAH WE DONT CARE FOR THAT ONE'
      4     UNKNOWN = 'WHAT?'
----> 5     FAVES = defaultdict(lambda: UNKNOWN, {x:FAVE for x in ['dog', 'cat']})
      6     FAVES['Crab'] = NOTFAVE

NameError: global name 'FAVE' is not defined

Why? Why can it find UNKNOWN but not FAVE? Is it because it's in a dictionary comprehension?

eriophora
  • 999
  • 1
  • 8
  • 20

1 Answers1

4

Yes, it's because it's in a dictionary comprehension. Note that it's not "finding" UNKNOWN either; it's just not looking for it yet, because UNKNOWN is only referenced in a lambda. If you replace your dict comprehension with something else to allow the class definition to succeed, you'll get an error later if you try to access a nonexistent key (because then it will try to call that lambda). So if you change it to

FAVES = defaultdict(lambda: UNKNOWN, {'a': 1})

You'll get:

>>> OurFavAnimals.FAVES['x']
Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    OurFavAnimals.FAVES['x']
  File "<pyshell#2>", line 5, in <lambda>
    FAVES = defaultdict(lambda: UNKNOWN, {'a': 1})
NameError: global name 'UNKNOWN' is not defined

In both cases, the reason is that variables defined in the class scope are not available in nested scopes. In other words, it's the same reason this fails:

class Foo(object):
    something = "Hello"
    def meth(self):
        print(something)

Both the lambda and the dictionary comprehension create function scopes that are nested in the class scope, so they don't have access to the class variables directly. See also this related question.

Community
  • 1
  • 1
BrenBarn
  • 242,874
  • 37
  • 412
  • 384
  • In which I would add, the most preferable way around this would be defining (some or all of) these variables in the `__init__()` method of the class with `self.FAVE = [...]`. – Sam Aug 27 '15 at 19:25
  • Thanks! But that's still so odd; why is this case? I thought it was always the case that nested scopes had access to the parent scope in Python. At least, that's always been the case before in my experience. – eriophora Aug 27 '15 at 19:34
  • @eriophora: Class scopes are different. See the question I linked to for some discussion of that. – BrenBarn Aug 27 '15 at 19:35
  • W.R.T. Sam's response, while it's not the case here and it's difficult to think of a scenario in which it was the case, let's say you had to initialize hundreds of thousands of instances of this class all with the same parameters. I had an elaborate backstory to justify it ("let's say you wanted to model a large group of psychics who can communicate instantly with each other and who travel the world learning the names of new animals and arbitrarily assigning them to their communal 'favorite' or 'not favorite' lists of animals...") – eriophora Aug 27 '15 at 19:36
  • @BrenBarn that answer you linked is fabulous; I'm embarrassed I didn't find it sooner. Perhaps people should get points on stack overflow for tagging resolved questions with alternate phrasings of the question. Or perhaps I should've just included "list comprehensions" in my search terms... – eriophora Aug 27 '15 at 19:39
  • @eriophora: As discussed in that question, this behavior actually shows up for list comprehensions only in Python 3. It shows up for generator and dictionary comprehensions in both Python 2 and 3 though. – BrenBarn Aug 27 '15 at 19:47