如何在CPython中实现变量分配? [英] How is variable assignment implemented in CPython?

查看:180
本文介绍了如何在CPython中实现变量分配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道Python中的变量实际上只是对某些基础对象的引用/指针。而且由于它们是指针,所以我想它们会以某种方式存储或与它们所引用的对象的地址相关联。

I know that variables in Python are really just references/pointers to some underlying object(s). And since they're pointers, I guess they somehow "store" or are otherwise associated with the address of the objects they refer to.

这种地址存储可能发生在CPython实现的底层。但是
我对C的了解不足以从源代码推断出这一点,也不知道在源代码中应该从哪里开始寻找。

Such an "address storage" probably happens at a low level in the CPython implementation. But my knowledge of C isn't good enough to infer this from the source code, nor do I know where in the source to begin looking.

所以,我的问题是:

在CPython的实现中,对象地址如何存储在指向它们的变量中或与之相关联?

In the implementation of CPython, how are object addresses stored in, or otherwise associated with, the variables which point to them?

推荐答案

在模块范围或类范围中,变量作为Python dict中的条目实现。指向对象的指针存储在字典中。在较早的CPython版本中,指针直接存储在dict的基础哈希表中,但是自CPython 3.6起,哈希表现在将索引存储到dict条目的密集数组中,并且指针位于该数组中。 (还有一些拆分键字典,它们的工作方式略有不同。它们用于优化对象属性,您可能会或可能不会认为它们是变量。)

In module scope or class scope, variables are implemented as entries in a Python dict. The pointer to the object is stored in the dict. In older CPython versions, the pointer was stored directly in the dict's underlying hash table, but since CPython 3.6, the hash table now stores an index into a dense array of dict entries, and the pointer is in that array. (There are also split-key dicts that work a bit differently. They're used for optimizing object attributes, which you might or might not consider to be variables.)

在函数范围内,Python创建一个堆栈框架对象来存储给定函数执行的数据,并且该堆栈框架对象包括一个指向变量值的指针数组。变量被实现为该数组中的条目,并且指向值的指针存储在数组中,每个变量的索引固定。 (字节码编译器负责确定这些索引。)

In function scope, Python creates a stack frame object to store data for a given execution of a function, and the stack frame object includes an array of pointers to variable values. Variables are implemented as entries in this array, and the pointer to the value is stored in the array, at a fixed index for each variable. (The bytecode compiler is responsible for determining these indices.)

这篇关于如何在CPython中实现变量分配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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