python - 什么是 co_names?

标签 python documentation cpython

description检查模块中的 co_names 读取:

tuple of names of local variables

但在实践中,co_names 似乎是一个全局变量名称的元组,而 co_varnames 是一个局部变量名称(和参数名称)的元组。例如:

a = 1

def f(b):
    c = a + b

print(f.__code__.co_varnames)  # prints ('b', 'c')
print(f.__code__.co_names)     # prints ('a',)

此外,在 dis 模块的文档中,许多指令描述暗示 co_names 包含全局变量的名称。例如 LOAD_GLOBAL description阅读:

Loads the global named co_names[namei] onto the stack.

我在这里误解了什么吗? co_names 真的包含“局部变量的名称”吗?

编辑 07/17/2017

如评论/答案中所述,这似乎是文档错误。提交的错误问题 here .

编辑 07/22/2017

Pull request修复此文档错误已批准并等待合并。

编辑 06/06/2022

Pull request于 2021 年 9 月 24 日合并。

最佳答案

正如其他人已经说过的,这似乎是文档错误documentation for code objects显然与 documentation for inspect 相矛盾:

co_varnames is a tuple containing the names of the local variables (starting with the argument names); [...] co_names is a tuple containing the names used by the bytecode;

此外,访问代码对象的属性 co_namesco_varnamesinspect 中所述的内容冲突:

>>> def f():
...     a = 1
...     b = 2
... 
>>> f.__code__.co_names
()
>>> f.__code__.co_varnames
('a', 'b')

此外,CPython's compiler 的源代码中的注释明确提到 co_varnames 用于局部变量:

PyObject *u_names;     /* all names */
PyObject *u_varnames; /* local variables */

您看不到 co_varnames 的原因是因为上面的代码正在初始化 Python 用来编译代码的 编译器对象 的属性。 u_names and u_varnames are both later passed into PyCode_New - CPython 代码对象的构造函数:

names = dict_keys_inorder(c->u->u_names, 0);
varnames = dict_keys_inorder(c->u->u_varnames, 0);

...

co = PyCode_New(..., names, varnames, ... );

还有 PyCode_New assigns names and varnames to the co_names and co_varnames attributes respectively :

Py_INCREF(names);
co->co_names = names;
Py_INCREF(varnames);
co->co_varnames = varnames;

如果您还没有,我建议您在 bugs.python.org 填写错误报告让 Python 开发团队了解文档中的这种不一致。

关于python - 什么是 co_names?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45147260/

相关文章:

python - 以Pythonic方式比较列表项

c++ - C++ 的手册页在哪里?

python - 在 Aiohttp/Python 中记录 websocket 消息的最佳方法是什么?

python - 使用调试 Python 安装在 Windows 上构建 Python-C-Extension

python - python语法中 `~`是什么意思

python - pandas 获取带有列表的列的虚拟值

python - 在 python 3 中展平多维数组

Python:将新字典附加到json文件

xcode - Swift Markdown 中的相关链接

python - 切片端点被无形地截断