python - Python的代码对象是什么类型?

标签 python compilation cpython python-internals

有没有办法可以将 compile__code__ 构造的代码对象的类型与实际代码对象类型进行比较?

这工作正常:

>>> code_obj = compile("print('foo')", '<string>', 'exec')
>>> code_obj
<code object <module> at 0x7fb038c1ab70, file "<string>", line 1>
>>> print(type(code_obj))
code
>>> def foo(): return None
>>> type(foo.__code__) == type(code_obj)
True

但我不能这样做:

>>> type(foo.__code__) == code
NameError: name 'code' is not defined

但是从哪里导入代码

这似乎不是来自 code.py 。它在 CPython C file 中定义但我找不到它的 Python 接口(interface)类型。

最佳答案

您正在寻找CodeType可以在类型中找到。

>>> from types import CodeType
>>> def foo(): pass
... 
>>> type(foo.__code__) == CodeType
True

请注意there's nothing special关于它,它只是在函数 __code__ 上使用 type

由于它位于标准库中,因此即使代码对象的公开方式发生一些变化,您也可以确保它能够正常工作。

关于python - Python的代码对象是什么类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62340735/

相关文章:

python - 使用装饰器在类内部进行函数包装

c++ - 错误/usr/include/string.h :652:42: error: ‘memcpy’ was not declared in this scope while building caffe

python - 为什么基于 C 的 Python 扩展总是返回相同的值?

Python:有关 Python 函数实现的信息

java - 如何编写 java 库的 python 包装器

python - 重新训练和更新现有 Rasa NLU 模型

python - 如何在 Python 3(0x80 及更高版本)中编写 ANSI 兼容字节?

python - matplotlib set_label_position 在 3d 中没有效果?

使用外部库创建独立项目

performance - 第一次调用 Julia 很慢