【问题标题】:What does __flags__ in python type used forpython类型中的__flags__用于什么
【发布时间】:2017-12-04 12:34:34
【问题描述】:

最近在看pickle源码。

copy_reg 中的以下代码让我很困惑:

_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对象中定义的:

type.__flags__ = 2148423147

我试图在官方文档中搜索它,但没有找到。

但有趣的是,当__class__ 是python 内部类型时,__class__.__flags__ &amp; _HEAPTYPE 总是0。当__class__ 是python 内部类型的子类时,结果将是1

谁能帮我解决这个难题?

【问题讨论】:

    标签: python python-2.7 pickle cpython


    【解决方案1】:

    __flags__ 是一个包装器to access CPython type object structure member tp_flags,用于组成这个标志defined in object.h 的常量,以下引自来源:

    类型标志 (tp_flags) 这些标志用于以向后兼容的方式扩展类型结构 时尚。扩展可以使用标志来指示(和测试)给定的 类型结构包含一个新特性。 Python 核心将在以下情况下使用这些 在主要版本之间引入新功能(以避免中间版本 PYTHON_API_VERSION 的变化)。

    python document on tp_flags上查看更多详情。

    但有趣的是 class.flags & _HEAPTYPE 在 class 是 python 内部类型时始终为 0。当class是python内部类型的子类时,结果为1。

    python 内置类型的子类,与其他用户定义类型一样,在堆上分配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
    

    【讨论】:

      【解决方案2】:

      __flags__ 将被视为二进制,如果您想查看标志。

      这些类型标志在 Python 的源代码中定义为 here

      【讨论】:

        猜你喜欢
        • 2020-02-06
        • 2012-11-15
        • 2021-01-30
        • 2014-04-28
        • 1970-01-01
        • 2021-07-06
        • 1970-01-01
        • 2019-09-07
        • 1970-01-01
        相关资源
        最近更新 更多