Function and Lambda Creation Anomalies in Loops
When attempting to generate functions within a loop, as seen in the code snippet below, a peculiar issue arises:
functions = [] for i in range(3): def f(): return i functions.append(f)
Similarly, when using lambdas:
functions = [] for i in range(3): functions.append(lambda: i)
One would expect these functions to output distinct values (0, 1, and 2), but all functions end up yielding the same value (2).
Explanation and Solution
This phenomenon is caused by late variable binding. In Python functions, variables are resolved when called, which means that when the functions are invoked after the loop, the value of i is already set to 2. To rectify this, we employ early binding by introducing the f(i=i) syntax. Here, the default value for the i argument is established at the time of definition, resulting in early binding:
def f(i=i): return i
Alternatively, a more complex approach using a closure and a "function factory" ensures early binding as well:
def make_f(i): def f(): return i return f
Within the loop, we can then utilize f = make_f(i) rather than the def statement.
The above is the detailed content of Why Do Functions Created in a Python Loop All Return the Same Value?. For more information, please follow other related articles on the PHP Chinese website!