Home >Backend Development >Python Tutorial >How Do Nested Functions Handle Local Variables and Closures in Python?
Local Variables in Nested Functions
This intricate example involves nested functions and closures, which can lead to confusing behavior. Let's unravel the mystery.
Nested Function Execution
Nested functions, when executed, access variables from the parent scope. In this case, the pet_function is a nested function within the get_petters generator. When executed, it searches for variables in the scope of get_petters.
Closure Cells and Local Variables
The pet_function has one free variable (cage). During compilation, this free variable is represented by a closure cell. When pet_function is executed, this closure cell checks the value of cage in the surrounding scope of get_petters.
Dynamic Lookups and Closures
The problematic behavior arises when the funs list is created. At that point, cage in get_petters has the value 'cat'. When each function in funs is called, the closure cell in pet_function looks up the value of cage at the time of that function call, not when it was defined.
Accessing Different Animals
To resolve this issue, pet_function needs to access a specific instance of the cage object for each animal. This can be achieved through partial functions, new function scopes, or keyword parameters.
Partial Function
A partial function creates a new function with fixed parameters. Here's an example using functools.partial():
def pet_function(cage=None): print("Mary pets the " + cage.animal + ".") yield (animal, partial(gotimes, partial(pet_function, cage=cage)))
New Function Scope
Creating a new function scope ensures that the cage variable is bound within the newly defined function.
def scoped_cage(cage=None): def pet_function(): print("Mary pets the " + cage.animal + ".") return pet_function yield (animal, partial(gotimes, scoped_cage(cage)))
Keyword Parameter
Binding the cage variable as a default value for a keyword parameter:
def pet_function(cage=cage): print("Mary pets the " + cage.animal + ".") yield (animal, partial(gotimes, pet_function))
The above is the detailed content of How Do Nested Functions Handle Local Variables and Closures in Python?. For more information, please follow other related articles on the PHP Chinese website!