Can someone explain to me why the following code produces the exception it does?
>>> class CallableKlass(object):
def __init__(self, callible):
self.callible = callible
def __call__(self, arg):
return self.callible(arg)
>>> class Klass(object):
d = {'foo': 'bar'}
m = CallableKlass(lambda x: d[x])
>>> Klass.m('foo')
Traceback (most recent call last):
File "<pyshell#10>", line 1, in <module>
Klass.m('foo')
File "<pyshell#5>", line 5, in __call__
return self.callible(arg)
File "<pyshell#9>", line 3, in <lambda>
m = CallableKlass(lambda x: d[x])
NameError: global name 'd' is not defined
The class namespace (stuff defined directly in the class body) is not accessible from within functions defined in that namespace. A lambda is just a function, so this applies to lambdas as well. Your
CallableKlassis a red herring. The behavior is the same in this simpler case: