In Python, cell objects are used to store free closure variables .
Let's say you need a function that always returns a certain fraction of its argument. You can use closure to achieve this:
def multiplier(n, d): """Return a function that multiplies its argument by n/d.""" def multiply(x): """Multiply x by n/d.""" return x * n / d return multiply
And here is how you can use it:
>>> two_thirds = multiplier(2, 3) >>> two_thirds(7) 4.666666666666667
How do two_thirds remember the values โโof n and d ? They are not multiply function arguments that are defined by multiplier , they are not local variables defined inside multiply , they are not global, and since multiplier already complete, its local variables no longer exist, right?
What happens when multiplier compiled, the interpreter notices that multiply wants to use its local variables later, so it marks them:
>>> multiplier.__code__.co_cellvars ('d', 'n')
Then, when multiplier is called, the value of these external local variables is stored in the attribute of the returned __closure__ function as a tuple of cell objects:
>>> two_thirds.__closure__ (<cell at 0x7f7a81282678: int object at 0x88ef60>, <cell at 0x7f7a81282738: int object at 0x88ef40>)
... with their names in the __code__ object as co_freevars :
>>> two_thirds.__code__.co_freevars ('d', 'n')
You can get the contents of the cells using the cell_contents attribute:
>>> {v: c.cell_contents for v, c in zip( two_thirds.__code__.co_freevars, two_thirds.__closure__ )} {'d': 3, 'n': 2}
You can learn more about closures and their implementation in the Python Enhancement Proposal that introduced them: PEP 227 - Static Nested Areas .