What Causes Unexpected Lambda Closure Behavior in Python?

Mary-Kate Olsen
Release: 2024-10-21 13:10:30
Original
883 people have browsed it

What Causes Unexpected Lambda Closure Behavior in Python?

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

When calling the functions in funcs1, we get the expected output:

a 1
b 1
c 1
Copy after login

However, when calling the functions in funcs2, we get an unexpected result:

c 1
c 1
c 1
Copy after login

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

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!

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