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__andcell.cell_contents; a function with no free variables has__closure__ofNone. - 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.