Scope of Lambda Functions and Their Parameters
Lambda functions are anonymous functions that can capture the scope of their enclosing function. This allows them to access variables and parameters from the parent scope. However, this behavior can sometimes lead to unexpected results when lambda functions use parameters that are modified within the enclosing function.
To illustrate the issue, consider the following code:
<code class="python">def callback(msg): print(msg) # Creating a list of function handles with an iterator funcList = [] for m in ('do', 're', 'mi'): funcList.append(lambda: callback(m)) # Calling the lambda functions for f in funcList: f()</code>
The expected output of this code is:
do re mi
However, the actual output is:
mi mi mi
This is because the lambda functions capture a reference to the variable m from the enclosing scope. When the iterator executes the loop, it assigns the value 'mi' to m in the final iteration. As a result, all the lambda functions have a reference to 'mi' when they are executed, even though different values were passed to them during creation.
To resolve this issue, you can capture the value of m at the time of lambda function creation by using it as the default value of an optional parameter:
<code class="python">for m in ('do', 're', 'mi'): funcList.append(lambda m=m: callback(m))</code>
This ensures that each lambda function has access to its own copy of m, capturing the value that was assigned during the loop iteration. The output of this code will be:
do re mi
The above is the detailed content of How to Avoid Unexpected Results from Parameter Modifications in Lambda Functions. For more information, please follow other related articles on the PHP Chinese website!