Reading preferences
Concept

Closures and Decorators

Follow a function that remembers a value and wraps another function.

python, closures, decorators, functions

Remember a surrounding value

A nested function can keep access to a name from its enclosing scope after the outer call ends. Such a function is a closure. A decorator takes a function and returns a replacement, often a wrapper that adds behaviour.

Python illustration

from functools import wraps

def add_prefix(prefix):
    def decorate(function):
        @wraps(function)
        def wrapped(name):
            return prefix + function(name)
        return wrapped
    return decorate

@add_prefix("Hello, ")
def greet(name):
    return name

print(greet("Ada"))
print(greet.__name__)

Prepared output — not live execution:

Hello, Ada
greet

At definition time add_prefix("Hello, ") returns a decorator; that decorator receives the original greet and returns wrapped. The name greet then refers to the wrapper. When called, the wrapper reads the enclosing prefix and calls the original function.

See the reasoning

Follow the decorator's bindings

See how the wrapper keeps access to its prefix and original function. This is a prepared demonstration, not live code execution.

Create a decorator

Bindings and call path
  1. Factoryprefix = Hello, Current focus
  2. Decoratordecorate awaits a function
  3. Functiongreet is defined

The factory binds prefix to Hello, and returns decorate.

Binding is not a frozen copy

Closures retain access to bindings, so a loop creating functions can surprise you when all functions later read the same final loop variable. If a separate value is intended, bind it deliberately, for example using a default argument or a factory call. nonlocal permits rebinding an existing enclosing function's variable; it does not create a new enclosing variable.

Use functools.wraps when wrapping functions to preserve useful metadata. Decorators run when the function definition is executed, not once for every call. Avoid hiding side effects or changing a function's contract unexpectedly.

Reflect on the concept

Four fixed questions to reinforce the reasoning. Answers are not saved or scored.

1. What can a closure retain after its enclosing function returns?
2. What does decorating a function normally do?
3. Why use functools.wraps on a wrapper?
4. Does a closure always freeze a copy of each enclosing value?

References and further reading