What is a cell in the context of an interpreter or compiler?

Python code objects have the co_cellvars attribute. The documentation for the PyPy bytecode interpreter often uses the term Cell.

Among other langauges, Rust provides a cell data type . Googling suggests that they are somehow related to closure.

What is a cell in the context of a programming language implementation? What problem do the cells solve?

+6
source share
1 answer

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 .

+10
source

Source: https://habr.com/ru/post/969570/


All Articles