"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > What is the difference between nested functions and closures in Python

What is the difference between nested functions and closures in Python

Posted on 2025-05-01
Browse:236

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

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

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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3