Home  >  Article  >  Backend Development  >  How to Avoid Unexpected Behavior in Lambda Functions Due to Shared Scope Variables?

How to Avoid Unexpected Behavior in Lambda Functions Due to Shared Scope Variables?

Barbara Streisand
Barbara StreisandOriginal
2024-10-19 17:25:30170browse

How to Avoid Unexpected Behavior in Lambda Functions Due to Shared Scope Variables?

Scope Behavior of Lambda Functions and Their Parameters

When a lambda function is created, it inherits the scope of its enclosing function. However, a common misconception arises when using iterator loops to generate a series of lambda functions. In such cases, the lambda functions share the same scope variable, leading to unexpected results.

Consider the following simplified 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))

# Executing the functions
for f in funcList:
    f()</code>

The expected output is:

do
re
mi

However, the actual output is:

mi
mi
mi

This happens because the lambda function, when created, retains a reference to the shared variable m in the enclosing scope. By the time the lambda functions are executed, m has been reassigned to 'mi', resulting in the unexpected output.

To resolve this issue, one can use an optional parameter with a default value. This allows each lambda function to capture its own value of the variable:

<code class="python">for m in ('do', 're', 'mi'):
    funcList.append(lambda m=m: callback(m))</code>

With this modification, each lambda function maintains a distinct copy of the value of m at the time of its creation, yielding the desired output:

do
re
mi

The above is the detailed content of How to Avoid Unexpected Behavior in Lambda Functions Due to Shared Scope Variables?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn