在解释器或编译器的上下文中是什么单元格? [英] What is a cell in the context of an interpreter or compiler?

查看:117
本文介绍了在解释器或编译器的上下文中是什么单元格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python代码对象有一个属性 co_cellvars 在这里记录)。 Pypy的字节码解释器的文档通常使用术语Cell。

Python code objects have an attribute co_cellvars (documented here). The documentation to Pypy's bytecode interpreter often uses the term Cell.

在其他语言中,Rust 提供单元格数据类型。 Googling建议他们以某种方式涉及闭包。

In other langauges, Rust provides a Cell datatype. Googling suggests they relate to closures somehow.

在编程语言实现的上下文中,什么是单元格?细胞解决什么问题?

What is a cell, in the context of programming language implementation? What problem do cells solve? Where can I read about them?

推荐答案

在Python中, cell 用于存储自由变量闭包

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:

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

下面是如何使用它:

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

two_thirds 记住 n d 的值?它们不是定义乘法乘法函数的参数,它们不是 multiply ,它们不是全局变量,因为 multiplier 已经终止,它的局部变量不再存在,对吗?

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

会发生什么是当编译 multiplier 时,解释器注意到 multiply 稍后将要使用其局部变量,因此它保留了它们的注释:

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

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

code>乘法器被调用,那些外部局部变量的值存储在返回的函数的 __ closure __ 属性中, code> cell objects:

Then when multiplier is called, the value of those outer local variables is stored in the returned function's __closure__ attribute, as a tuple of cell objects:

>>> two_thirds.__closure__
(<cell at 0x7f7a81282678: int object at 0x88ef60>,
 <cell at 0x7f7a81282738: int object at 0x88ef40>)

...在 __ code __ 对象中的名称为 co_freevars

... with their names in the __code__ object as co_freevars:

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

在细胞的内容使用它们的 cell_contents 属性:

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

>>> {v: c.cell_contents for v, c in zip(
        two_thirds.__code__.co_freevars,
        two_thirds.__closure__
)}
{'d': 3, 'n': 2}

您可以在Python增强提议中了解更多关于闭包及其实现, PEP 227 - 静态嵌套范围

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

这篇关于在解释器或编译器的上下文中是什么单元格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆