Home > Backend Development > Python Tutorial > Why Does My Nested Function Only Access the Final Value of a Local Variable in Its Parent Function?

Why Does My Nested Function Only Access the Final Value of a Local Variable in Its Parent Function?

Barbara Streisand
Release: 2024-12-16 12:49:14
Original
465 people have browsed it

Why Does My Nested Function Only Access the Final Value of a Local Variable in Its Parent Function?

Local Variables in Nested Functions

Nested functions provide a convenient means of encapsulating specific functionality within a parent function. However, their closure behavior can introduce some complications in regard to the accessibility and value of local variables.

Problem:

Consider the following code snippet:

from functools import partial

class Cage(object):
    def __init__(self, animal):
        self.animal = animal

def gotimes(do_the_petting):
    do_the_petting()

def get_petters():
    for animal in ['cow', 'dog', 'cat']:
        cage = Cage(animal)

        def pet_function():
            print("Mary pets the " + cage.animal + ".")

        yield (animal, partial(gotimes, pet_function))

funs = list(get_petters())

for name, f in funs:
    print(name + ":", f())
Copy after login

The desired behavior is to print three different animals ('cow', 'dog', 'cat') for each iteration. However, the program only prints 'cat' for all iterations. This behavior contradicts the expectation that the local variable cage is associated with the nested function.

Answer:

The misunderstanding lies in the assumption that a nested function stores a reference to its parent scope's local variables when it is defined. In reality, the nested function looks up variables from the parent scope only when it is executed.

In this specific example, the closure created for the pet_function indexes the cage variable from the get_petters function. When the pet_function is called, it accesses the closure to retrieve the value of cage. However, at that point, the get_petters function has completed, and the cage variable has a final value of 'cat'. Therefore, all subsequent calls to any pet_function variation return the value 'cat'.

Workarounds:

To resolve this issue, one can use various techniques to ensure that the nested function accesses the correct value of cage:

  • Partial function: Utilize functools.partial to create a new function with a fixed value for cage.
  • Scoped function: Create a new function within the loop to ensure a unique scope for each instance of pet_function.
  • Default parameter value: Pass cage as a default parameter value to pet_function.

By employing one of these approaches, you can ensure that the nested function accesses the intended local variable for each iteration.

The above is the detailed content of Why Does My Nested Function Only Access the Final Value of a Local Variable in Its Parent Function?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template