Home  >  Article  >  Backend Development  >  Why do Python Lambdas Bind to Local Variables\' Values, Not References?

Why do Python Lambdas Bind to Local Variables\' Values, Not References?

Linda Hamilton
Linda HamiltonOriginal
2024-10-28 06:37:02975browse

 Why do Python Lambdas Bind to Local Variables' Values, Not References?

Python Lambda Functions and Local Variable Binding

When working with Python lambda functions, it's important to understand their behavior regarding references to local variables within the scope they're defined. The following code illustrates this issue:

<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>

In this scenario, we would expect to see 0 and 1 printed to the console. However, the actual output prints 1 twice. This behavior stems from the way Python lambdas bind to local variables.

The Gotcha: Early Binding

Python lambdas don't bind to the reference of local variables when they're created. Instead, they bind to the value of the variable at that specific point in time. As a result, when the lambda is invoked, it accesses the current value of the variable, not the value that was available at the time of creation.

A Solution: Late Binding with Default Arguments

To bind a local variable to a lambda function and preserve its correct reference, we can use late binding. This is achieved by passing a default argument to the lambda function, as seen below:

<code class="python">x.append(lambda v=v: pv(v))</code>

With this change, the lambda will bind to the value of v when the lambda is created, not when it's invoked. Therefore, when we iterate through the list x and call each lambda function, we'll obtain the expected output of 0 and 1.

Understanding Early Binding

To further clarify this concept, consider the following example:

<code class="python">x = "before foo defined"
def foo():
    print(x)
x = "after foo was defined"
foo()</code>

This code snippets prints "after foo was defined" to the console, demonstrating that variables are bound at the time of function call, not creation.

The above is the detailed content of Why do Python Lambdas Bind to Local Variables\' Values, Not References?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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
Previous article:cs week ythonNext article:cs week ython