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

What is the type of Python's code object?

有什么方法可以将 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

它似乎不是来自 code.py. It's defined in the CPython C file 但我找不到它的 Python 接口类型。

您正在寻找 CodeType,可在 types 中找到。

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

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

因为它在标准库中,所以即使代码对象的公开方式发生一些变化,您也可以确定它会正常工作。