2

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?

fluffyyboii
  • 635
  • 6
  • 15

1 Answers1

2

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).

Davis Herring
  • 36,443
  • 4
  • 48
  • 76
  • About what you said about `types` giving names to built-in types -- that's true, but `type(lambda: 0)` doesn't come out as `types.FunctionType`, it's just `function`. It's still a good answer, though. – fluffyyboii Dec 30 '20 at 17:03
  • @fluffyyboii: Here, “gives names to” means “allows access by name”, not “stores a name into”. See the [cat-on-the-porch story](https://stackoverflow.com/a/13827710/8586227), although unlike most objects types *do* know their own name that might be (say) `function` instead of whatever you used to get them. – Davis Herring Dec 30 '20 at 17:14