Python code objects have an attribute co_cellvars
. The documentation to PyPy's bytecode interpreter often uses the term Cell.
Among other langauges, Rust provides a Cell datatype. Googling suggests they relate to closures somehow.
What is a cell, in the context of a programming language implementation? What problem do cells solve?
In Python,
cell
objects are used to store the free variables of a closure.Let's say you want a function that always returns a particular fraction of its argument. You can use a closure to achieve this:
And here's how you can use it:
How does
two_thirds
remember the values ofn
andd
? They aren't arguments to themultiply
function thatmultiplier
defined, they aren't local variables defined insidemultiply
, they aren't globals, and sincemultiplier
has already terminated, its local variables no longer exist, right?What happens is that when
multiplier
is compiled, the interpreter notices thatmultiply
is going to want to use its local variables later, so it keeps a note of them:Then when
multiplier
is called, the value of those outer local variables is stored in the returned function's__closure__
attribute, as a tuple ofcell
objects:... with their names in the
__code__
object asco_freevars
:You can get at the contents of the cells using their
cell_contents
attribute:You can read more about closures and their implementation in the Python Enhancement Proposal which introduced them: PEP 227 — Statically Nested Scopes.