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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…