Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is "lambda binding" in Python?

I understand what are lambda functions in Python, but I can't find what is the meaning of "lambda binding" by searching the Python docs. A link to read about it would be great. A trivial explained example would be even better. Thank you.

like image 686
Anonymous Avatar asked Oct 02 '08 04:10

Anonymous


1 Answers

First, a general definition:

When a program or function statement is executed, the current values of formal parameters are saved (on the stack) and within the scope of the statement, they are bound to the values of the actual arguments made in the call. When the statement is exited, the original values of those formal arguments are restored. This protocol is fully recursive. If within the body of a statement, something is done that causes the formal parameters to be bound again, to new values, the lambda-binding scheme guarantees that this will all happen in an orderly manner.

Now, there is an excellent python example in a discussion here:

"...there is only one binding for x: doing x = 7 just changes the value in the pre-existing binding. That's why

def foo(x): 
   a = lambda: x 
   x = 7 
   b = lambda: x 
   return a,b

returns two functions that both return 7; if there was a new binding after the x = 7, the functions would return different values [assuming you don't call foo(7), of course. Also assuming nested_scopes]...."

like image 141
Swati Avatar answered Nov 30 '22 23:11

Swati