Skip to content

gh-160749: Correct documentation of tp_alloc and tp_free inheritance for heap types - #160821

Open
Yuvansh-thx wants to merge 2 commits into
python:mainfrom
Yuvansh-thx:main
Open

Yuvansh-thx wants to merge 2 commits into
python:mainfrom
Yuvansh-thx:main

Conversation

@Yuvansh-thx

Copy link
Copy Markdown

Fixes gh-160749

Summary of Changes

Clarify the inheritance and default documentation for the tp_alloc and tp_free slots in Doc/c-api/typeobj.rst.

The documentation previously stated that heap subtypes do not inherit tp_alloc or tp_free, and that for heap subtypes, tp_alloc is always set to PyType_GenericAlloc() and tp_free defaults to a generic deallocator.

However, heap types also include types created through C API functions such as PyType_FromSpec and PyType_FromMetaclass. For these types, if Py_tp_alloc or Py_tp_free is omitted from the specification slots, the corresponding slot is inherited from the base type through inherit_slots in Objects/typeobject.c. If the base type defines a custom allocator or deallocator, the C API heap subtype can inherit that custom implementation.

The exception applies to subtypes created using Python’s class statement or the type() constructor, which are handled by type_new_alloc. In these cases, tp_alloc and tp_free are explicitly initialized to PyType_GenericAlloc and PyObject_GC_Del, respectively.

Changes Made

  • PyTypeObject.tp_alloc: Clarified that subtypes inherit this slot from the base type, defaulting to PyType_GenericAlloc when inherited from object. Documented the exception for subtypes created using the class statement or type().
  • PyTypeObject.tp_free: Clarified that subtypes inherit this slot from the base type, subject to garbage collection compatibility rules. Documented the exception for subtypes created using the class statement or type().
  • Default sections: Updated the documentation for both slots to distinguish between types created through Python’s class statement or type() constructor and other subtypes, including static types and C API heap types created through PyType_FromSpec.

Testing

Documentation-only change. No code changes or additional tests are included.

@python-cla-bot

python-cla-bot Bot commented Oct 28, 2026 •

Copy link
Copy Markdown

All commit authors signed the Contributor License Agreement.

CLA signed

@read-the-docs-community

Copy link
Copy Markdown

Documentation build overview

📚 cpython-previews | 🛠️ Build #35471513 | 📁 Comparing 1e2cd0f against main (c71bf4d)

  🔍 Preview build  

1 file changed
± c-api/typeobj.html

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

awaiting review docs Documentation in the Doc dir skip news

Projects

Status: Todo

Development

Successfully merging this pull request may close these issues.

documentation of tp_alloc and tp_free inheritance for heap types is incorrect

1 participant