3 ms·
No, I mean this: def f(x): g = lambda : x x = 2 return g() f(42) What is does f(42) return? Holy fuck, I simply cannot just cut and paste th
by kazinator 4y ago
No, I mean this:
def f(x):
g = lambda : x
x = 2
return g()
f(42)
What is does f(42) return?
Holy fuck, I simply cannot just cut and paste the above into Python as-is, because of the "unexpected indent" which I added so that HN shows that as quote. It's complaining about an unexpected indent.
Kill. Me. Now.
Anywway:
>>> def f(x):
... g = lambda : x
... x = 2
... return g()
...
>>> f(42)
2
So what it looks like is that there is only one x in the function, established by the parameter. This x is captured by the lambda, and is then reassigned the value 2. The lambda retrieves the 2.
For completeness we show that if x is not assignmed, g accesses f's argument value:
>>> def f(x):
... g = lambda : x
... return g()
...
>>> f(42)
42
- deleted 4y ago[deleted]