[ACCEPTED]-What is a cell in the context of an interpreter or compiler?-rust

Accepted answer
Score: 20

In Python, cell objects are used to store the 21 free variables of a closure.

Let's say you want a function that 20 always returns a particular fraction of 19 its argument. You can use a closure to achieve 18 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's how you can use it:

>>> two_thirds = multiplier(2, 3)
>>> two_thirds(7)

How does 17 two_thirds remember the values of n and d? They aren't 16 arguments to the multiply function that multiplier defined, they 15 aren't local variables defined inside multiply, they 14 aren't globals, and since multiplier has already terminated, its 13 local variables no longer exist, right?

What 12 happens is that when multiplier is compiled, the interpreter 11 notices that multiply is going to want to use its 10 local variables later, so it keeps a note 9 of them:

>>> multiplier.__code__.co_cellvars
('d', 'n')

Then when multiplier is called, the value 8 of those outer local variables is stored 7 in the returned function's __closure__ attribute, as 6 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 5 in the __code__ object as co_freevars:

>>> two_thirds.__code__.co_freevars
('d', 'n')

You can get at the contents 4 of the cells using their cell_contents attribute:

>>> {v: c.cell_contents for v, c in zip(
{'d': 3, 'n': 2}

You 3 can read more about closures and their implementation 2 in the Python Enhancement Proposal which 1 introduced them: PEP 227 — Statically Nested Scopes.

More Related questions