[Python-Dev] AtExit Functions

M.-A. Lemburg mal@lemburg.com
Mon, 15 Jul 2002 09:52:55 +0200


Tim Peters wrote:
> [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*.
>>
> 
> [Marc]
> 
>>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.

PyObject_Del() as well ?

>>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).

I suppose the first one is what the atexit module exposes
in Python 2.0+, right ?

The problem with that approach is that there may still be some
references to objects left in lists and dicts which are cleaned
up after having called the atexit functions. This is not so
much a problem in my cases, but something to watch out in other
applications which use C level Python objects as globals.

>>>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).

Well, yeah :-)

>>Also, atexit.py is not present in Python 1.5.2.
> 
> 
> What's that <wink>?

That's the Python version which was brand new just 3 years
ago. I know... in US terms that's for history books ;-)

-- 
Marc-Andre Lemburg
CEO eGenix.com Software GmbH
_______________________________________________________________________
eGenix.com -- Makers of the Python mx Extensions: mxDateTime,mxODBC,...
Python Consulting:                               http://www.egenix.com/
Python Software:                    http://www.egenix.com/files/python/