types.SimpleNamespace 是如何实现的?

问题描述

我注意到 types.SimpleNamespace 类似乎是递归实现的。在 types 模块中,类被定义为 type(sys.implementation)。但是,type(sys.implementation) 只返回 types.SimpleNamespace,这是不可能的,因为两个名称相互依赖才能使用。 types.SimpleNamespace 是如何实际实施的?

解决方法

当然type(sys.implementation) is types.SimpleNamespace,但这并不意味着后者是该类型的来源(并且types.不会作为输出出现 任何东西)。与 types 中公开的大多数类型一样,SimpleNamespace 是在实现中定义的(在 CPython 中使用 C),而 types 只是为任何“方便”的绕行提供了名称 ”用于访问类型。 (TracebackType 是从实际抛出和捕获虚拟异常中获得的!)sys 模块实际上使用内置类型,以及其他恶作剧,例如创建 version_info,即使类型可以' t 被实例化(之后)。