Skip to content

always implement tp_traverse to traverse type object - #6269

Open
davidhewitt wants to merge 9 commits into
PyO3:mainfrom
davidhewitt:heap-type-traverse
Open

always implement tp_traverse to traverse type object#6269
davidhewitt wants to merge 9 commits into
PyO3:mainfrom
davidhewitt:heap-type-traverse

Conversation

@davidhewitt

Copy link
Copy Markdown
Member

This is a followup to #6206 which I noticed while reviewing (also very similar to #6224).

Reading the CPython docs for tp_traverse:

Heap types (Py_TPFLAGS_HEAPTYPE) must visit their type with:

Py_VISIT(Py_TYPE(self));

All #[pyclass] types are heap types, but we were not doing that. The test added demonstrates a memory leak present on main which this branch fixes.

Summary of changes:

  • We now make every PyO3 type a GC type, and install a tp_traverse which traverses the heap type
  • Because every type is now a GC type, I could simplify create_type_object to
    • We no longer need separate tp_dealloc / tp_dealloc_with_gc implementations
    • I moved the assertion that __clear__ requires a __traverse__ implementation to compile-time in macro code (with a UI test)
  • I tidied up the PyVisit type implementation slightly at the same time

@davidhewitt
davidhewitt marked this pull request as draft July 31, 2026 10:02
@davidhewitt
davidhewitt marked this pull request as ready for review July 31, 2026 10:51
Comment thread src/impl_/pyclass/traverse.rs
Comment thread src/impl_/pymethods.rs Outdated
);
}

pub const fn assert_type_implements_traverse(implements_traverse: bool) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If we apply a #[track_caller] to this, it might clean up the error backtrace a bit.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good idea, pushed that and will merge, thanks!

@davidhewitt
davidhewitt enabled auto-merge July 31, 2026 20:20
@davidhewitt
davidhewitt added this pull request to the merge queue Jul 31, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Jul 31, 2026
@davidhewitt
davidhewitt enabled auto-merge August 1, 2026 06:36
@davidhewitt
davidhewitt added this pull request to the merge queue Aug 1, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Aug 1, 2026
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.

2 participants