Search code examples
pythonpython-3.xsys

How is types.SimpleNamespace implemented?


I noticed the types.SimpleNamespace class seems to be recursively implemented. In the types module, the class is defined as type(sys.implementation). However, type(sys.implementation) simply returns types.SimpleNamespace, which wouldn't be possible, since both names rely on each other to be available. How is types.SimpleNamespace actually implemented?


Solution

  • Of course type(sys.implementation) is types.SimpleNamespace, but that doesn’t mean that the latter is the source of the type (and types. doesn’t appear as the output of anything). Like most types exposed in types, SimpleNamespace is defined in the implementation (in C for CPython), and types just gives names to whatever circumlocutions are “convenient” for accessing the type. (TracebackType is obtained from actually throwing and catching a dummy exception!) The sys module actually uses the built-in type, along with other shenanigans like creating version_info even though the type can’t be instantiated (afterwards).