Python lambda behavior

I am trying to raise my head around lambda expressions, closures and clouds in Python. Why doesn't the program crash to the first line here?

>>> foo = lambda x: x + a >>> foo(2) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 1, in <lambda> NameError: global name 'a' is not defined >>> a = 5 >>> foo(2) 7 >>> 
+4
source share
5 answers

Because it's just not how Python functions work; this is not especially for lambda:

 >>> def foo(x): ... return x + a >>> foo <function foo at 0xb7dde454> >>> foo(2) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 2, in foo NameError: global name 'a' is not defined 

Variables are processed when used, not when defining a function. They are even viewed every time a function is called that you will certainly find unexpected if you use background C (for example), but that is not a problem in Python.

+6
source

Your lambda expression is not evaluated until you name it.

It parses, so a syntax error causes a trace.

 >>> foo = lambda x : x + a >>> bar = lambda y : print y SyntaxError: invalid syntax 
+2
source

Variables in Python can be used before they are set. This will create a runtime error, not a syntax error. Here is an example of using local variables:

 >>> def f(): ... return a ... a = 3 ... >>> f() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 2, in f UnboundLocalError: local variable 'a' referenced before assignment 

This is in contrast to languages ​​that consider dereferencing an unassigned or undefined variable of syntax error. Python does not “capture” the current state of the lexical region; it simply uses references to mutable lexical regions. Here is a demo:

 >>> def f(): return a ... >>> f() Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 1, in f NameError: global name 'a' is not defined >>> a = 3 >>> f() 3 
+2
source

The bodies of lambdas (and functions defined with def) in Python are not evaluated before they are called. Names are always viewed at runtime.

0
source

in the first line, you create an expression that is different from its evaluation. When you try to evaluate it, then it cannot find the character a.

0
source

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


All Articles