Home  >  Article  >  Backend Development  >  How do you capture local variables in lambda closures within loops?

How do you capture local variables in lambda closures within loops?

DDD
DDDOriginal
2024-11-10 12:52:03259browse

How do you capture local variables in lambda closures within loops?

Lambda Closures and Variable Scopes in Loops

When defining lambdas within loops, it's important to understand how variable scopes work. In the code snippet provided, each lambda created inside the loop references the same variable obj, which is modified with each iteration.

Default Scope Resolution

By default, a lambda will capture the variables from the enclosing scope. In the given code, the enclosing scope is the loop block. So, each lambda effectively captures the last value of obj. This behavior can lead to incorrect results when calling the lambdas from a different scope, as they may not have the expected value.

Capture Local Variables

To resolve this issue, you need to force the lambda to capture the current value of obj. This can be achieved by introducing a new local variable in the lambda that is bound to obj at the time of creation. The following code snippet demonstrates this approach:

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

By explicitly passing obj as an argument to the lambda, we create a new local variable for each lambda. This ensures that each lambda captures the local value of obj from the loop iteration. As a result, when you call the lambdas from another scope, they will access the correct value.

The above is the detailed content of How do you capture local variables in lambda closures within 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