Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is `x = 42; x = lambda: x` parsed?

I was surprised that this assertion fails:

x = 42 x = lambda: x assert x() == 42 

It seems that x ends up recursively referring to itself, so that x(), x()(), etc. are all functions.

What is the rule used to parse this, and where is this documented?

By the way (not unexpectedly given the above), the original value of x has no references left after the lambda definition:

class X:   def __del__(self): print('deleting')  x = X() x = lambda: x  # 'deleting' is printed here 
like image 778
max Avatar asked Dec 04 '20 08:12

max


People also ask

What does lambda X X mean?

The following is an anonymous function: lambda x: x!= "X" The first x is its parameter, and in this example, the intention is for that parameter to represent a string argument.

Is Python lambda a closure?

The Python lambda function on line 4 is a closure that captures n , a free variable bound at runtime. At runtime, while invoking the function f on line 7, the value of n is three . A Python lambda function behaves like a normal function in regard to arguments.


1 Answers

The variable x is created by the first assignment, and rebound with the second assignment.

Since the x in the lambda isn't evaluated until the lambda is called, calling it will evaluate to the most recently assigned value.

Note that this is not dynamic scoping - if it were dynamic, the following would print "99", but it prints "<function ...":

x = 42 x = lambda: x  def test(f):   x = 99   print(f())  test(x) 
like image 170
molbdnilo Avatar answered Sep 27 '22 20:09

molbdnilo