Skip to content

gh-89373: Document that error indicator may be set in tp_dealloc #28358

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
Jun 9, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions Doc/c-api/typeobj.rst
Original file line number Diff line number Diff line change
Expand Up @@ -686,6 +686,26 @@ and :c:data:`PyType_Type` effectively act as defaults.)
instance, and call the type's :c:member:`~PyTypeObject.tp_free` function to
free the object itself.

If you may call functions that may set the error indicator, you must use
:c:func:`PyErr_GetRaisedException` and :c:func:`PyErr_SetRaisedException`
to ensure you don't clobber a preexisting error indicator (the deallocation
could have occurred while processing a different error):

.. code-block:: c

static void
foo_dealloc(foo_object *self)
{
PyObject *et, *ev, *etb;
PyObject *exc = PyErr_GetRaisedException();
...
PyErr_SetRaisedException(exc);
}

The dealloc handler itself must not raise an exception; if it hits an error
case it should call :c:func:`PyErr_FormatUnraisable` to log (and clear) an
unraisable exception.

No guarantees are made about when an object is destroyed, except:

* Python will destroy an object immediately or some time after the final
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Document that error indicator may be set in tp_dealloc, and how to avoid
clobbering it.
Loading