为什么python VM拥有co_names而不是仅仅使用co_consts? [英] Why does python VM have co_names instead of just using co_consts?

查看:170
本文介绍了为什么python VM拥有co_names而不是仅仅使用co_consts?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由Python编译器生成的代码对象包含一个在指令中使用的常量元组(名为co_consts),还包含一个包含名称的元组(名为co_names).

A code object generated by Python compiler contains a tuple of constants used in the instructions (named co_consts) and also a tuple containing names (named co_names).

为什么有两个不同的列表?仅仅使用co_consts来命名也不会更简单吗?

Why having two distinct lists? Wouldn't be simpler to just use co_consts for names too?

推荐答案

请考虑以下功能.

def f(x):
    x += n
    return x * 4

此处x是本地名称,其值可以更改. 4是一个常数.它的价值永远不会改变.但是,它仍然是一个对象,最好缓存它们,而不是每次需要时都创建一个新对象.最后,n是全局引用.字符串"n"由函数存储,因此可以用作从函数的全局上下文中检索n的键.

Here x is a local name, its value can change. 4 is a constant. Its value will never change. However, it's still an object and it's better to cache them rather than create a new object each time it's needed. Finally, n is a global reference. The string "n" is stored by the function so that it can be used as a key to retrieve n from the function's global context.

>>> f.__code__.co_nlocals # just 1 (for x)
1
>>> f.__code__.co_consts
(None, 4)
>>> f.__code__.co_names
('n',)
>>> "n" in f.__globals__ and globals() is f.__globals__
True

将名称和const分开的原因是为了自省.合并元组的唯一真正原因是内存效率,尽管这只会为您每个函数获得一个对象和一个指针.考虑以下功能.

The reason for keeping names and consts separate is for the purposes of introspection. The only real reason to merge the tuples would be memory efficiency, though this would only gain you one object and one pointer per function. Consider the following function.

def g():
    return "s" * n

如果包含const的元组与包含名称的元组合并,则您(不是VM)将无法分辨出哪些值用于访问全局变量,哪些是该函数的常量.

If the tuple containing consts was merged with the tuple containing names then you (not the VM) wouldn't be able to tell which values were for accessing globals and which were constants of the function.

这篇关于为什么python VM拥有co_names而不是仅仅使用co_consts?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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