Lambda Function Closures: Intriguing Properties and Capture Strategies
In Python, lambda functions exhibit intriguing behavior regarding closures, and understanding their mechanics is crucial for effective coding. This article explores the questions surrounding closure capture and provides a practical approach to achieving desired outcomes.
1. What do Lambda Function Closures Capture?
Consider a common scenario where lambda closures are crafted within a loop. Each closure is designed to capture the current loop variable's value. However, counterintuitive outcomes can arise when examining closure behaviors.
2. Capturing the Current Value
The essence of capturing the current value is not by pointer reference like one might assume. Instead, closures capture a "snapshot" of the referenced variable at the time of creation. Consequently, any subsequent modifications to that variable have no impact on the captured value.
3. An Elegant Solution
To ensure that lambda functions capture the intended current value, consider utilizing a parameter with a default value. This technique essentially "forces" the capture of the desired value. Here's an illustration:
for i in [0, 1, 2, 3]: adders[i] = lambda a, i=i: i + a
By specifying the i parameter with a default value of i (the loop variable), the closure captures the current value of i at the time of creation. As a result, changes to i outside the lambda function do not affect the captured value, leading to the expected outcome.
The above is the detailed content of How Do Lambda Function Closures in Python Capture Variables?. For more information, please follow other related articles on the PHP Chinese website!