While static types (PyTypeObject values) don't themselves ever change (once PyType_Ready() has run), they do hold mutable data. This means they cannot be safely shared between multiple interpreters without a common GIL (and without state leaking between).
Mutable data:
- the object header (e.g. refcount), as with all objects
- otherwise immutable objects:
- ob_type (
__class__)
- tp_base (
__base__) - set by PyType_Ready() if not set
- tp_bases (
__bases__) - always set by PyType_Ready()
- tp_mro (
__mro__) - always set by PyType_Ready()
- tp_dict (
__dict__) - set by PyType_Ready() if not set
- mutable containers:
- tp_subclasses (
__subclasses__)
- tp_weaklist
(See https://docs.python.org/3/c-api/typeobj.html#tp-slots.)
(Note that tp_cache is no longer used.)
For the object header, if PEP 683 (immortal objects) is accepted then we can make static types immortal.
For the otherwise immutable objects, we can make sure each is immortal and then we're good. Even tp_dict is fine since it gets hidden behind types.MappingProxyType. We'd also need to either make sure each contained item is immortal.
For tp_subclasses we will need a per-interpreter copy, and do the proper lookup in the __subclasses__ getter. The cache could be stored on PyInterpreterState or even as a dict in tp_subclasses.
For tp_weaklist it's a similar story as for tp_subclasses. Note that tp_weaklist isn't very important for static types since they are never deallocated.
(The above is also discussed in PEP 684.)
CC @kumaraditya303
Linked PRs
While static types (
PyTypeObjectvalues) don't themselves ever change (oncePyType_Ready()has run), they do hold mutable data. This means they cannot be safely shared between multiple interpreters without a common GIL (and without state leaking between).Mutable data:
__class__)__base__) - set byPyType_Ready()if not set__bases__) - always set byPyType_Ready()__mro__) - always set byPyType_Ready()__dict__) - set byPyType_Ready()if not set__subclasses__)(See https://docs.python.org/3/c-api/typeobj.html#tp-slots.)
(Note that
tp_cacheis no longer used.)For the object header, if PEP 683 (immortal objects) is accepted then we can make static types immortal.
For the otherwise immutable objects, we can make sure each is immortal and then we're good. Even
tp_dictis fine since it gets hidden behindtypes.MappingProxyType. We'd also need to either make sure each contained item is immortal.For
tp_subclasseswe will need a per-interpreter copy, and do the proper lookup in the__subclasses__getter. The cache could be stored onPyInterpreterStateor even as a dict intp_subclasses.For
tp_weaklistit's a similar story as fortp_subclasses. Note thattp_weaklistisn't very important for static types since they are never deallocated.(The above is also discussed in PEP 684.)
CC @kumaraditya303
Linked PRs