Home >Backend Development >Python Tutorial >Why does Python Lambda bind to local references at invocation time, not creation time?
Python Lambda's Binding to Local References
The following code prints '1' twice instead of '0' and '1':
<code class="python">def pv(v): print v x = [] for v in range(2): x.append(lambda: pv(v)) for xx in x: xx()</code>
To understand this behavior, it's crucial to grasp how Python lambdas interact with local variables. Contrary to expectations, lambdas do not inherently bind to the references of local variables at the time of their creation. Instead, they bind to the values of the variables retrieved at the moment of their invocation.
To rectify this issue and correctly bind local variables to lambda functions, it's necessary to use a default argument for the lambda. By setting the default value of the variable within the lambda definition (e.g., lambda v=v: pv(v)), the lambda will refer to the value of the variable when it was created.
This behavior is not exclusive to lambdas. Consider the following example:
<code class="python">x = "before foo defined" def foo(): print x x = "after foo was defined" foo()</code>
The output of this code will be "after foo was defined," as Python looks up the value of x at the time the function is called, rather than when it was created.
The above is the detailed content of Why does Python Lambda bind to local references at invocation time, not creation time?. For more information, please follow other related articles on the PHP Chinese website!