Skip to content

[mypyc] Clear only subtype refs in tp_dealloc of built-in subtypes - #21872

Merged
p-sawicki merged 1 commit into
python:masterfrom
p-sawicki:builtin-base-dealloc-clear-subtype-only
Aug 19, 2026
Merged

[mypyc] Clear only subtype refs in tp_dealloc of built-in subtypes#21872
p-sawicki merged 1 commit into
python:masterfrom
p-sawicki:builtin-base-dealloc-clear-subtype-only

Conversation

@p-sawicki

Copy link
Copy Markdown
Collaborator

Fixes #21859

Deallocating an instance of a class that inherits from a built-in type might fail an assertion because when we clear references during the deallocation, we call the generated tp_clear function that in turn calls tp_clear of the base class.

The functions put in the tp_clear slot of built-in types require that the instance is still alive (references > 0) which is not the case during deallocation.

To avoid this, split the tp_clear function for types with built-in bases into two: first (subtype_clear) clears only the references owned by the subtype, second (clear) does the same plus calls base type tp_clear.

clear is put into the tp_clear slot while subtype_clear can be called from tp_dealloc. tp_dealloc also calls base type tp_dealloc which clears the references owned by the base type, so the base type tp_clear call was not necessary.

For classes without a builtin base we continue to clear all their references in a single function.

@p-sawicki p-sawicki changed the title [mypyc] Clear only subtype refs in tp_dealloc of built-in base types [mypyc] Clear only subtype refs in tp_dealloc of built-in subtypes Aug 19, 2026
@p-sawicki
p-sawicki merged commit 7f88c95 into python:master Aug 19, 2026
18 checks passed
@p-sawicki
p-sawicki deleted the builtin-base-dealloc-clear-subtype-only branch August 19, 2026 16:07
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

CPython assertion error Py_REFCNT when running compiled mypy

2 participants