Skip to the solution
MediumDSA10 min read

How do closures capture variables in Python?

94 views

The problem

Question presented to candidate: "What is a closure in Python, and what exactly does the inner function capture β€” the value of the outer variable, or something else? Show me how you would prove it."

What a strong answer should cover:

  • A closure is a function that keeps access to variables of the enclosing function after that function has returned.
  • Python captures the variable, not a snapshot of its value: the variable lives in a cell object shared by the outer function and every inner function that uses it.
  • The inspection points: outer.__code__.co_cellvars, inner.__code__.co_freevars, inner.__closure__ and cell.cell_contents; a function with no free variables has __closure__ of None.
  • Reading a captured variable needs nothing; rebinding it needs nonlocal. Each call of the outer function makes new cells.
  • Globals are not captured at all, and late binding means the value is read when the inner function runs β€” the source of the loop pitfall.
  • Real uses: function factories, decorators, callbacks and small private state; the closure keeps the captured objects alive.

Code / implementation expected: Yes β€” a factory or counter closure, ideally with __closure__ inspected to show the shared cell.

  • closures
  • cells

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

10 min read Β· 12 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

PythonLook inside a closure: cells, co_freevars and __closure__
PythonClosures at work: factories, a memoizing decorator, lifetime

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 111 of 139 in Python

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All Python questions
Up nextMedium

What is EAFP vs LBYL in Python?

Continue