python类型中的__flags__用于什么 [英] What does __flags__ in python type used for
问题描述
最近我已经阅读了pickle的源代码.
I have been read pickle source code recently.
copy_reg
中的以下代码使我感到困惑:
The following code in copy_reg
make me confused:
_HEAPTYPE = 1<<9
def _reduce_ex(self, proto):
assert proto < 2
for base in self.__class__.__mro__:
if hasattr(base, '__flags__') and not base.__flags__ & _HEAPTYPE:
break
else:
base = object # not really reachable
if base is object:
state = None
__flags__
的用途是什么?
我发现它是在type
对象中定义的:
I found it is defined in type
object:
type.__flags__ = 2148423147
我曾尝试在官方文档中进行搜索,但未找到任何内容.
I was tried to search it in the official doc, but nothing was found.
但是有趣的是,当__class__
是python内部类型时,__class__.__flags__ & _HEAPTYPE
始终是0
.当__class__
是python内部类型的子类时,结果将是1
.
But interesting thing is that __class__.__flags__ & _HEAPTYPE
is always 0
when the __class__
is python internal type. And the result will be 1
when __class__
is a subclass of python internal type.
有人可以帮我解决这个难题吗?
Can anyone help me to solve this puzzle?
推荐答案
__flags__
是一个包装器,在object.h 中定义,以下引自来源:
__flags__
is a wrapper, to access CPython type object structure member tp_flags
, constants used to compose this flag defined in object.h, following is quoted from the source:
类型标志(tp_flags) 这些标志用于向后兼容扩展类型结构 时尚.扩展可以使用标志来指示(和测试)给定时间 类型结构包含一个新功能. Python核心将在以下情况下使用这些 在主要版本之间引入新功能(以避免中间版本) PYTHON_API_VERSION中的更改).
Type flags (tp_flags) These flags are used to extend the type structure in a backwards-compatible fashion. Extensions can use the flags to indicate (and test) when a given type structure contains a new feature. The Python core will use these when introducing new functionality between major revisions (to avoid mid-version changes in the PYTHON_API_VERSION).
有关
但是有趣的是 class .标志&当 class 是python内部类型时,_HEAPTYPE始终为0.当 class 是python内部类型的子类时,结果将为1.
But interesting thing is that class.flags & _HEAPTYPE is always 0 when the class is a python internal type. And the result will be 1 when class is a subclass of python internal type.
与其他用户定义类型一样,python内置类型的子类使用PyType_GenericAlloc()
分配在堆上.
Subclass of python built-in type, like other user defined type, allocated on heap with PyType_GenericAlloc()
.
分解type.__flags__
:
import re
def flags_to_name(type_obj):
tp_flag_consts = {}
with open('/path/to/Include/object.h') as f:
for l in f:
m = re.search(r'^#define (Py_TPFLAGS_\w+)\s+\(.+?<< (\d+)\)', l.strip())
if m:
tp_flag_consts[int(m.group(2))] = m.group(1)
bin_str = bin(type_obj.__flags__)[2:][::-1]
return ', '.join(tp_flag_consts[n] for n, c in enumerate(bin_str) if c == '1')
print(flags_to_name(type))
产量:
Py_TPFLAGS_BASETYPE, Py_TPFLAGS_READY, Py_TPFLAGS_HAVE_GC, Py_TPFLAGS_HAVE_VERSION_TAG, Py_TPFLAGS_VALID_VERSION_TAG, Py_TPFLAGS_TYPE_SUBCLASS
这篇关于python类型中的__flags__用于什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!