Python Lambda Closure Scoping
Understanding the behavior of lambda closures in Python can be tricky. In this article, we explore a case where a lambda function behaves unexpectedly, returning the same value for all cases.
The Issue:
Consider the following code:
<code class="python">names = ['a', 'b', 'c'] def test_fun(name, x): print(name, x) def gen_clousure(name): return lambda x: test_fun(name, x) funcs1 = [gen_clousure(n) for n in names] funcs2 = [lambda x: test_fun(n, x) for n in names]</code>
When calling the functions in funcs1, we get the expected output:
a 1 b 1 c 1
However, when calling the functions in funcs2, we get an unexpected result:
c 1 c 1 c 1
The expected output should be the same as in the first case, but instead, we see the value of the last name, 'c', for all cases.
The Explanation:
The key to understanding this behavior lies in the concept of closures. Closures in Python allow inner functions to access variables from their enclosing scopes. In the first case (funcs1), the lambda function is created inside a loop, but it captures the variable name from the enclosing scope and binds it to the name within the lambda function.
In the second case (funcs2), however, the lambda function directly references the variable n from the enclosing scope without binding it to the name within the lambda function. This means that when the lambda function is called, it evaluates n at that time, which always returns the last value from the loop, resulting in the unexpected output.
Avoiding the Issue:
To avoid this issue and achieve the desired behavior, we must ensure that the lambda function captures the variable from the enclosing scope and binds it to the name within the lambda function. One way to do this is to wrap the lambda function in another function:
<code class="python">def makeFunc(n): return lambda x: x+n</code>
The resulting lambda function in makeFunc captures the value of n from the enclosing scope and binds it to the name within the lambda function, achieving the desired behavior.
The above is the detailed content of What Causes Unexpected Lambda Closure Behavior in Python?. For more information, please follow other related articles on the PHP Chinese website!