Python — Closures

1 min read

A closure is a function that captures variables from its enclosing scope. Those variables stay alive even after the outer function has returned because the inner function holds a reference to them.

def make_counter():
    count = 0
    def increment():
        nonlocal count
        count += 1
        return count
    return increment

counter = make_counter()
print(counter())  # 1
print(counter())  # 2

Here, increment is a closure: it remembers count from make_counter’s scope. Closures are useful for stateful functions, factories, decorators, and any case where you want a function to carry private data without resorting to global variables.

X