bpo-40217: Ensure Py_VISIT(Py_TYPE(self)) is always called for PyType_FromSpec types by pablogsal · Pull Request #19414 · python/cpython

https://bugs.python.org/issue40217

Types created by PyType_FromSpec own a strong reference to their type, but this was added in Python 3.8. The tp_traverse function needs to call Py_VISIT on the type but all existing traverse functions cannot be updated (especially the ones from existing user functions) so we need to provide a tp_traverse that manually calls Py_VISIT(Py_TYPE(self)) and then call the provided tp_traverse. In this way, user functions do not need to be updated, preserve backwards compatibility.

To do this, we store the user-provided traverse function at the end of the type (we need to allocate space for it) so we can call it from our PyType_FromSpec_tp_traverse wrapper.