[Python-Dev] AtExit Functions

Tim Peters tim.one@comcast.net
Mon, 15 Jul 2002 00:54:17 -0400


[Guido]
>> I think you may be making a wrong use of Py_AtExit().  The docs state
>> (since 1998):
>>
>>   Since Python's internal finallization will have completed before the
>>   cleanup function, no Python APIs should be called by *func*.

[Guido]
> Hmm, and that includes Py_DECREF() and PyObject_Del() ?

Certainly.  In particular, Py_DECREF() can end up calling any Python code at
all, via __del__ methods.

> In that case, I have a problem since I'm using those
> two to clean up caches and free lists in the mx tools.

We have two sets of exit-function gimmicks, one that runs at the very start
of Py_Finalize(), and the other at the very end.  If you need to clean up
Python objects, you have to get into the first group.  The interpreter has
been torn down beyond usefulness by the time we get to the second group
(that's only useful for low-level OS and external non-Python C library
cleanup).

>> You may want to use the atexit.py module instead to schedule your
>> module's cleanup action; these exit functions are called much earlier.

> That's difficult to get right since I have to register such a
> function from C.

? You know how to write Python-callable C functions.  I'm not sure why you
would need to call atexit.register from C, but if you must then that's easy
too (PyObject_Call).

> Also, atexit.py is not present in Python 1.5.2.

What's that <wink>?