Skip to content

Commit 3b26578

Browse files
bmerryjagerman
authored andcommitted
Document using atexit for module destructors on PyPy (#1169)
None of the three currently recommended approaches works on PyPy, due to it not garbage collecting things when you want it to. Added a note with example showing how to get interpreter shutdown callbacks using the Python atexit module.
1 parent 086d53e commit 3b26578

File tree

1 file changed

+15
-0
lines changed

1 file changed

+15
-0
lines changed

docs/advanced/misc.rst

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -216,6 +216,21 @@ avoids this issue involves weak reference with a cleanup callback:
216216
// Create a weak reference with a cleanup callback and initially leak it
217217
(void) py::weakref(m.attr("BaseClass"), cleanup_callback).release();
218218
219+
.. note::
220+
221+
PyPy (at least version 5.9) does not garbage collect objects when the
222+
interpreter exits. An alternative approach (which also works on CPython) is to use
223+
the :py:mod:`atexit` module [#f7]_, for example:
224+
225+
.. code-block:: cpp
226+
227+
auto atexit = py::module::import("atexit");
228+
atexit.attr("register")(py::cpp_function([]() {
229+
// perform cleanup here -- this function is called with the GIL held
230+
}));
231+
232+
.. [#f7] https://docs.python.org/3/library/atexit.html
233+
219234
220235
Generating documentation using Sphinx
221236
=====================================

0 commit comments

Comments
 (0)