Search code examples
pythondictionaryclass-attributes

Dictionary class attribute that refers to other class attributes in the definition


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?


Solution

  • 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.