Why does Python Lambda bind to local references at invocation time, not creation time?

DDD
Release: 2024-10-29 21:41:29
Original
381 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!