简体   繁体   English

Python的代码object是什么类型的?

[英]What is the type of Python's code object?

Is there a way I can compare to the type of a code object constructed by compile or __code__ to the actual code object type?有没有办法可以将compile__code__构造的代码 object 的类型与实际代码 object 类型进行比较?

This works fine:这工作正常:

>>> 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

But I can't do this:但我不能这样做:

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

but where do I import code from?但是我从哪里导入code

It doesn't seem to be from code.py .它似乎不是来自code.py It's defined in the CPython C file but I couldn't find the Python interface type for it.它在 CPython C文件中定义,但我找不到它的Python接口类型。

You're after CodeType which can be found in types .您正在寻找可以在types中找到的CodeType

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

Note that there's nothing special about it, it just uses type on a functions __code__ .请注意,它没有什么特别之处,它只是在函数__code__上使用type

Since it's in the standard lib, you can be sure it will work even if some change happens in the way code objects are exposed.由于它在标准库中,因此即使代码对象的公开方式发生一些变化,您也可以确定它会起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM