Home > Backend Development > Python Tutorial > 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
Release: 2024-10-19 17:25:30
Original
285 people have browsed it

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>
Copy after login

The expected output is:

do
re
mi
Copy after login
Copy after login

However, the actual output is:

mi
mi
mi
Copy after login

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>
Copy after login

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
Copy after login
Copy after login

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!

source:php
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template