Lambdas, called class instances and scope; why doesn't it work in Python 2.7?

Can someone explain to me why the following code throws an exception that it makes?

>>> 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 
+4
source share
2 answers

The class namespace (material defined directly in the class) is not accessible from the functions defined in this namespace. Lambda is just a function, so this applies to lambdas. Your CallableKlass is a red herring. In this simpler case, the behavior is the same:

 >>> class Foo(object): ... d = {'foo': 'bar'} ... (lambda stuff: d[stuff])('foo') Traceback (most recent call last): File "<pyshell#3>", line 1, in <module> class Foo(object): File "<pyshell#3>", line 3, in Foo (lambda stuff: d[stuff])('foo') File "<pyshell#3>", line 3, in <lambda> (lambda stuff: d[stuff])('foo') NameError: global name 'd' is not defined >>> class Foo(object): ... d = {'foo': 'bar'} ... def f(stuff): ... d[stuff] ... f('foo') Traceback (most recent call last): File "<pyshell#4>", line 1, in <module> class Foo(object): File "<pyshell#4>", line 5, in Foo f('foo') File "<pyshell#4>", line 4, in f d[stuff] NameError: global name 'd' is not defined 
+3
source

you should use Klass.d inside lambda, since variables declared inside a class become an attribute of that class. This is why your program raised this error, since it cannot find anything like d in global variables:

 class Klass(object): d = {'foo': 'bar'} m = CallableKlass(lambda x: Klass.d[x]) 
+2
source

Source: https://habr.com/ru/post/1443861/


All Articles