closure

In Python, a closure is a function object that has access to variables in its enclosing (containing) lexical scope, even when the function is called outside that scope. In simpler terms, a closure “closes over” the free variables from its enclosing scope, preserving access to them.

Python Closure Example

A closure occurs when a nested function references variables from its enclosing function. The nested function “closes over” the data, maintaining a reference to it. This data is stored in what’s called the function’s cell, and remains accessible even after the outer function has finished executing.

Python
def outer_function(x):
    """Enclose the value of x in the closure scope."""
    def inner_function(y):
        # x is a free variable captured from the enclosing scope
        return x + y  
    return inner_function

# Create a closure and store it as add_five
add_five = outer_function(5)

# Call the closure function
result = add_five(3)  

# The closure returns 5 + 3 = 8

Tutorial

Python Closures: Common Use Cases and Examples

In this tutorial, you'll learn about Python closures. A closure is a function-like object with an extended scope. You can use closures to create decorators, factory functions, stateful functions, and more.

intermediate python

For additional information on related topics, take a look at the following resources:


By Dan Bader • Updated Jan. 24, 2025