Home >Backend Development >Python Tutorial >How to Avoid Variable Closure When Creating Lambdas Inside Loops?

How to Avoid Variable Closure When Creating Lambdas Inside Loops?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-16 14:31:03676browse

How to Avoid Variable Closure When Creating Lambdas Inside Loops?

Creating Lambdas Inside a Loop without Variable Closure

When creating lambdas inside a loop that iterate over a list of objects, it is important to prevent variable closure. Variable closure occurs when a function retains access to a variable outside of its immediate scope. This can lead to unexpected behavior, such as all lambdas referencing the same final value of a variable.

The Problem:

The following code demonstrates the problem:

lambdas_list = []
for obj in obj_list:
    lambdas_list.append(lambda: obj.some_var)

for f in lambdas_list:
    print(f())

When invoking the lambdas in this code, all lambdas will produce the same result: the value of obj.some_var from the last object in obj_list. This is because the lambdas all refer to the same obj variable, which changes with each iteration of the loop.

The Solution:

To prevent variable closure, we can use the syntax lambda x=x: where x is the variable we want to capture. This captures a copy of obj and makes it local to each lambda:

lambdas_list = []
for obj in obj_list:
    lambdas_list.append(lambda obj=obj: obj.some_var)

for f in lambdas_list:
    print(f())

Now, each lambda will reference the correct obj and produce the expected value for obj.some_var.

The above is the detailed content of How to Avoid Variable Closure When Creating Lambdas Inside Loops?. 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