Avoid double checking `tp_as_number`, `tp_as_sequence` and `tp_as_mapping`
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 77.2k
- Forks
- 35.9k
- PR merge metrics
- PR metrics pending
Description
Feature or enhancement
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.
Linked PRs
- gh-149317
- gh-149476
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start at PyType_Ready and trace the handling of tp_as_number, tp_as_sequence, and tp_as_mapping, then inspect the access patterns described in the issue. Done means NULL slots are safely represented by shared all-NULL structs without the extra checks, with relevant CPython tests passing.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- backend
- Issue type
- Feature
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 30/100