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:
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()
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:
for m in ('do', 're', 'mi'):
funcList.append(lambda m=m: callback(m))
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
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3