datarekha
Python Medium Asked at GoogleAsked at MetaAsked at StripeAsked at Airbnb

What is a closure in Python, and what problem does it solve?

The short answer

A closure is a function that retains access to variables from its enclosing scope even after that scope has finished executing. It is the mechanism behind decorators, factory functions, and stateful callbacks without needing a class.

How to think about it

A closure is Python’s way of packaging a function together with the state it needs. The enclosing function finishes and its stack frame is gone — but the inner function keeps a live reference to the variables it captured. That captured state is what makes closures so useful for factory functions and decorators.

What’s really being tested

Interviewers use closures to probe whether you understand Python’s scoping rules (LEGB: Local, Enclosing, Global, Built-in) and how functions are first-class objects. The follow-up is almost always the late-binding trap in loops.

Step 1 — The basic pattern

The key ingredients: an outer function, an inner function that references a variable from the outer scope, and the outer function returning the inner function. At that point, the outer scope is “closed over.”

Step 2 — Each call creates an independent closure

Every call to the factory produces a separate closure with its own copy of the captured variable. That’s what lets double and triple coexist without interfering.

Step 3 — Inspect the captured cells

Python stores the captured variables in __closure__ as cell objects. You can peek inside with .cell_contents.

The key insight — why it works

Python stores the free variable in a cell object shared between the outer and inner scope. As long as the inner function exists, the cell keeps the value alive — the garbage collector won’t reclaim it. Each call to the factory allocates a new cell, which is why double and triple are independent.

Learn it properly Functions

Keep practising

All Python questions

Explore further

Skip to content