为什么 Python sys.version_info 缺少转换为字典的 _asdict() 方法?

Why is Python sys.version_info missing _asdict() method to cast to a dict?

sys.version_info 是否有什么独特之处,这意味着它没有 return 适当的 namedtuple 并且没有 _asdict 函数?

sss = sys.version_info._asdict
AttributeError: 'sys.version_info' object has no attribute '_asdict'
[Finished in 0.7s with exit code 1]

很有趣,所以我实际上更深入地挖掘了。正如评论中提到的,sys.version_info 是一个定制的元组子类,不要被 docstring 混淆,有趣的是它实际上是一个命名元组,尽管它们可能指的是 print 字符串格式。

print(sys.version_info.__doc__)
sys.version_info

Version information as a named tuple.

你也会意识到,如果你 运行 dir(sys.version_info) 其中 returns 它的方法, _asdictdict 不是它的一部分,因此返回您的错误没有 _asdict 作为属性。

根据文档本身;

A tuple containing the five components of the version number: major, minor, micro, releaselevel, and serial. All values except releaselevel are integers; the release level is 'alpha', 'beta', 'candidate', or 'final'. The version_info value corresponding to the Python version 2.0 is (2, 0, 0, 'final', 0). The components can also be accessed by name, so sys.version_info[0] is equivalent to sys.version_info.major and so on.

鉴于组件是静态的,并且如文档中所述,始终可以通过名称或其固定索引访问组件。

如果你真的想要一本字典:

comp = 'major minor micro releaselevel serial'.split()
svi_dic ={k:v for (k,v) in zip(comp,sys.version_info)}
svi_dic

{'major': 3, 'minor': 6, 'micro': 6, 'releaselevel': 'final', 'serial': 0}

这似乎是多余的,因为您也可以轻松地执行 sys.version_info.major 等等。希望这有助于让您有所了解。

version_info 不完全是 namedtuple(尽管有文档字符串)。

(以下假定 cpython 实现细节,它可能适用于也可能不适用于替代实现,例如 pypy / jython

它是用C实现的,一个StructSequence。来自 3.7.1 sources:

    version_info = PyStructSequence_New(&VersionInfoType);
    if (version_info == NULL) {
        return NULL;
    }

文档中的 StructSequence 是:

the C equivalent of namedtuple() objects, i.e. a sequence whose items can also be accessed through attributes. To create a struct sequence, you first have to create a specific struct sequence type.

也就是说,它一个namedtuple,但不一样。值得注意的是,它似乎缺少 _replace_asdict_fields_fields_defaults api。