bpo-45210: Document that error indicator may be set in tp_dealloc (#28358)

Signed-off-by: Edward Z. Yang <ezyang@fb.com>
Signed-off-by: Edward Z. Yang <ezyang@meta.com>
Co-authored-by: Victor Stinner <vstinner@python.org>
This commit is contained in:
Edward Z. Yang 2025-06-09 04:56:32 -04:00 committed by GitHub
parent 3cb109796d
commit 8441b263af
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 22 additions and 0 deletions

View file

@ -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

View file

@ -0,0 +1,2 @@
Document that error indicator may be set in tp_dealloc, and how to avoid
clobbering it.