Home > Backend Development > Python Tutorial > What\'s the Difference Between Nested Functions and Closures in Python?

What\'s the Difference Between Nested Functions and Closures in Python?

DDD
Release: 2024-11-23 02:32:10
Original
1014 people have browsed it

What's the Difference Between Nested Functions and Closures in Python?

Nested Functions vs. Closures in Python

While nested functions in Python superficially resemble closures, they are fundamentally distinct due to a key difference:

Nested Functions as Non-Closures

Nested functions in Python are not considered closures because they do not meet the following requirement:

  • They do not access variables that are local to enclosing scopes when executed outside the enclosing scope.

Consider the following example:

def make_printer(msg):
    def printer():
        print(msg)
    return printer
Copy after login

Here, the printer function is a nested function within make_printer. It is a closure because it references the local variable msg after make_printer has returned.

Closure Definition

A closure is a function that maintains a reference to an enclosing scope, allowing it to access variables that are not defined within its own scope. This reference is maintained even after the enclosing scope has been exited.

Non-Closure Nested Function

On the other hand, the following nested function, which uses a default parameter value, is not a closure:

def make_printer(msg):
    def printer(msg=msg):
        print(msg)
    return printer
Copy after login

In this case, the variable msg is bound to the default value when printer is created, and it does not reference any variables outside its own scope. Therefore, it is not a closure.

Conclusion

Nested functions in Python that do not meet the closure definition are commonly referred to as "nested functions" to distinguish them from genuine closures. Closures can be useful for retaining the state of enclosing scopes, while non-closure nested functions simply encapsulate functionality within a lexical scope.

The above is the detailed content of What's the Difference Between Nested Functions and Closures in Python?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template