Nested Functions in Python: Why Not Closures?
Nested functions in Python are a feature that allows functions to be defined within other functions. These functions inherit the variables from their enclosing scope, providing access to variables that would otherwise be out of reach.
Despite sharing similarities with closures, nested functions in Python are not referred to as closures. This distinction stems from their behavior. A closure is a function that has access to variables from an enclosing scope even after that scope has been exited.
When a nested function is defined in Python, it does not inherently retain access to the variables of its enclosing scope. Instead, the nested function creates a new scope and has access to variables in that scope only.
For a nested function to behave as a closure, it must meet two key criteria:
If a nested function satisfies both these conditions, it behaves as a closure. Otherwise, it is simply a nested function.
Consider the following example:
def make_printer(msg): def printer(): print(msg) return printer printer = make_printer('Foo!') printer() # Output: Foo!
In this example, the printer function accesses the msg variable from its enclosing scope (make_printer). Because it is executed outside of its enclosing scope (when it is assigned to printer and then called), it behaves as a closure.
In contrast, a nested function that does not reference variables from its enclosing scope is not a closure. For instance:
def make_printer(msg): def printer(msg=msg): print(msg) return printer printer = make_printer('Foo!') printer() # Output: Foo!
Here, the msg variable is bound to the default value of the parameter instead of the variable in the enclosing scope. Therefore, this nested function is not a closure.
In summary, nested functions in Python are not called closures because they do not inherently exhibit the behavior of closures, which is accessing variables from an enclosing scope after it has exited. To qualify as a closure, a nested function must both reference variables from its enclosing scope and be executed outside of it.
The above is the detailed content of When Are Nested Python Functions Actually Closures?. For more information, please follow other related articles on the PHP Chinese website!