You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Avoid double checking tp_as_number, tp_as_sequence and tp_as_mapping #149180
The PyTypeObject fields tp_as_number, tp_as_sequence and tp_as_mapping can be set to NULL
which means that any code that wants to access a field in those structs needs to first check for NULL.
e.g. checking if an object is a sequence: if (Py_TYPE(s)->tp_as_mapping && Py_TYPE(s)->tp_as_mapping->mp_length) {
this is ugly, a bit error prone and slower than necessary.
Instead, during PyType_Ready, any of these fields that are NULL should be made to pointer to a struct full of NULLs.
This would remove the need for the extra check: if (Py_TYPE(s)->tp_as_mapping->mp_length) {
since we would be guaranteed that Py_TYPE(s)->tp_as_mapping is never NULL.
Immutable types can all share common constant structs, so this should use very little extra memory.
If done properly, using structs of nulls will be faster than using null pointers, as the hot path will less branchy, even though the cold paths of constructing and modifying classes may be slower.
But it needs to be done with care, making sure that the correct test is being performed in all cases.
Many tests of the form tp->tp_as_mapping == NULL can be removed, but some will need to be converted to tp->tp_as_mapping == &MAPPING_NULL_STRUCT and a few will need to be left as tp->tp_as_mapping == NULL .
Also, take care to include implicit null checks of the form !tp->tp_as_mapping and those tests inverses.
Activity
Add NEWS blurb for pythongh-149180
Merge branch 'main' into pythongh-149180-empty-tp-as-structs
Merge branch 'python:main' into pythongh-149180-empty-tp-as-structs
pythongh-149180: Avoid double checking tp_as_number, tp_as_sequence, …
Add NEWS.d entry for pythongh-149180
Merge branch 'main' into pythongh-149180-empty-tp-as-structs
markshannon commentedon May 6, 2026
If done properly, using structs of nulls will be faster than using null pointers, as the hot path will less branchy, even though the cold paths of constructing and modifying classes may be slower.
But it needs to be done with care, making sure that the correct test is being performed in all cases.
Many tests of the form
tp->tp_as_mapping == NULLcan be removed, but some will need to be converted totp->tp_as_mapping == &MAPPING_NULL_STRUCTand a few will need to be left astp->tp_as_mapping == NULL.Also, take care to include implicit null checks of the form
!tp->tp_as_mappingand those tests inverses.sergey-miryanov commentedon May 6, 2026
I'll take this on in a week or two, if no one minds.
NekoAsakura commentedon May 6, 2026
Hi @sergey-miryanov, would you mind if I take this one? I was nearly done when #149317 was opened. :)
sergey-miryanov commentedon May 6, 2026
Yeah, go ahead!