Home >Backend Development >Python Tutorial >Why Does My Nested Function Only Access the Final Value of a Local Variable in Its Parent Function?
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())
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:
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!