What do Python Lambda Function Closures Capture?
When working with Python lambda function closures, it's important to understand their capture behavior. A closure captures the values of variables from its enclosing scope that are used within the closure. However, the manner in which this capture occurs can be surprising.
To illustrate this, consider the following code:
adders = [None, None, None, None] for i in [0, 1, 2, 3]: adders[i] = lambda a: i + a print(adders[1](3))
In this code, we create a list of lambda functions that take a single input and add a constant value to it. The constant value is initially set to the value of i during function creation. However, when we inspect the list of closures, we surprisingly find that they all reference the final value of i, resulting in an unexpected output of 6.
This behavior results from the fact that closures capture the value of the variable rather than its reference. As a result, when the value of i changes after closure creation, the closure continues to refer to the last captured value.
Capturing the Current Value
To capture the current value of i, we can use a trick known as the "dummy parameter" technique. By declaring a parameter with the same name as the variable we want to capture and providing it with a default value of that variable, we force the closure to capture the current value.
for i in [0, 1, 2, 3]: adders[i] = lambda a, i=i: i + a # <-- Note the dummy parameter with a default value print(adders[1](3)) # Output: 4
With this technique, the closure will capture the value of i at the time of its creation, ensuring that changes to i afterward will not affect the closure's behavior.
The above is the detailed content of What Variables Do Python Lambda Function Closures Actually Capture?. For more information, please follow other related articles on the PHP Chinese website!