|
|
|
|
|
by Jtsummers
1378 days ago
|
|
Creating a new one. It isn't a closure, so: x = 3
def f(x): # note the name here
x = 20
f(x)
x # => 3
Similarly, using a different parameter name: def g(y):
x = y
g(20)
x # => 3
You have to explicitly mark the `x` in the function to be the global one to reference it: def h(y):
global x
x = y
h(10)
x # => 10
With a lambda it would be a closure: i = lambda y : x # throwing away y for fun
i(3) # => 10
x = 20
i("hi") # => 20
|
|
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:
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: