Closure in Python

A closure in Python is a powerful feature that allows a function to capture and remember the environment in which it was created. This means that a closure can access variables from its enclosing scope even after that scope has finished execution. Closures are often used in functional programming and are a key component of decorators and higher-order functions.

Definition and Basic Concept

Closures are created when an inner function is defined within an outer function and the inner function captures variables from the outer function's scope. This is known as nonlocal variable binding. The inner function, or closure, can then be returned and used outside the outer function, maintaining access to the captured variables.

For example, consider the following code:

def outer(x):
    def inner():
        return x + 5
    return inner

closure = outer(100)
print(closure())  # Output: 105

In this example, inner is a closure that captures the variable x from the outer function's scope.

How Closures Work

When you create a closure, you are essentially creating a function that retains access to its lexical scope. This allows the closure to "remember" the environment in which it was created. You can inspect a closure to see what variables it has captured:

>>> closure.__closure__[0].cell_contents
100

This inspection reveals the value of the nonlocal variable x that the closure is using.

Higher-Order Functions and Closures

Closures are often used with higher-order functions, which are functions that take other functions as arguments or return them as results. A common use case is when a higher-order function returns a closure as its output.

A higher-order function that returns a function as output A higher-order function that returns a function as output

Closures and Decorators

Decorators in Python are a practical application of closures. A decorator is a higher-order function that takes a function to be decorated as an argument and returns a new function, which is the closure. This process is depicted in the following figure:

Applying a decorator is the process of creating a closure from the decorator function. Figure 7.2 Applying a decorator is the process of creating a closure from the decorator function.

Example of Closure in Practice

Consider the following example from the book "Tiny Python Projects":

def main():
    args = get_args()
    vowel = args.vowel

    def new_char(c):
        return vowel if c in 'aeiou' else vowel.upper() if c in 'AEIOU' else c

    text = ''.join([new_char(c) for c in args.text])
    print(text)

In this example, new_char() is a closure that captures the vowel variable from the main() function's scope. This allows new_char() to use vowel even though it is not passed as an argument.

Visual Representation

The concept of closure is visually represented in the following figure:

The new_char() function can only be seen within the main() function. Figure 8.6 The new_char() function can only be seen within the main() function. It creates a closure because it references the vowel variable.

In summary, closures are a powerful feature in Python that allow functions to capture and remember the environment in which they were created. They are widely used in functional programming and are a key component of decorators.

| Book Title | Usage of closure | Technical Depth | Connections to Other Concepts | Examples Used | Practical Application |
|------------|------------------|-----------------|-------------------------------|---------------|-----------------------|
| [Python How-To](https://www.manning.com/books/python-how-to) | Discusses closures as a way for inner functions to remember the environment in which they were created. | Explains nonlocal variable binding and how closures work with higher-order functions. | Connects closures to decorators and higher-order functions. | Provides code examples demonstrating closure creation and inspection. | Highlights the use of closures in decorators. [more](https://livebook.manning.com/book/python-how-to/chapter-7/140) |
| [Tiny Python Projects: Learn coding and testing with puzzles and games](https://www.manning.com/books/tiny-python-projects) | Describes closures as functions capturing lexical scope, allowing access to variables from enclosing scopes. | Focuses on practical implementation within a function using captured variables. | Shows how closures can be used with `map()` for functional programming. | Includes a practical example with `new_char()` function demonstrating closure. | Demonstrates closure usage in text processing with `map()`. [more](https://livebook.manning.com/book/tiny-python-projects/chapter-8/84) |