Home > Backend Development > Python Tutorial > Python Closures vs. Nested Functions: What\'s the Difference?

Python Closures vs. Nested Functions: What\'s the Difference?

Patricia Arquette
Release: 2024-12-09 00:47:09
Original
942 people have browsed it

Python Closures vs. Nested Functions: What's the Difference?

Closure vs. Nested Functions in Python: A Clarification

Python features a concept known as "nested functions," often mistaken for closures. To address this confusion, let's delve into the true nature of closures within Python.

A closure is defined as a function that maintains access to local variables from an enclosing scope, even after that scope has concluded. In Python, a closure arises when a nested function references local variables from the enclosing function. These variables remain accessible outside the enclosing scope due to the nested function's access to them.

Consider the following example:

def make_printer(msg):
    def printer():
        print(msg)
    return printer

printer = make_printer('Foo!')
printer()
Copy after login

In this scenario, the function printer is a closure because it references the local variable msg from the enclosing function make_printer. Even after make_printer concludes, msg remains accessible to printer.

However, not all nested functions are closures. For a nested function to qualify as a closure, it must meet these criteria:

  • Access local variables of the enclosing scope
  • Reference these variables when executed outside the scope

If a nested function does not meet these requirements, it is not considered a closure but rather an ordinary nested function.

For example, consider the following code:

def make_printer(msg):
    def printer(msg=msg):
        print(msg)
    return printer

printer = make_printer("Foo!")
printer()  # Output: Foo!
Copy after login

Here, the nested function printer is not a closure because it doesn't reference the msg from the enclosing function. Instead, it assigns the default parameter a value, eliminating the need for external access to msg.

Therefore, to distinguish between closures and nested functions in Python, it's crucial to consider whether or not the nested function maintains access to local variables from the enclosing scope even after the latter has completed execution.

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