WeakRefs, callbacks and GC when program quits

Duncan Booth duncan at NOSPAMrcp.co.uk
Wed Aug 7 12:24:34 EDT 2002

daniel_shane_eicon_junk at hotmail.com (Daniel Shane) wrote in 
news:2a6452dc.0208070803.cf6434 at posting.google.com:

> I'm having some problems with weakrefs and callbacks in regards to
> program termination in 2.2.1. It seems that whenever a python script
> ends, all variables are "deleted" and if any weakrefs are still there
> with callbacks registered, they will be called in the process.
> Unfortunately, this can lead to some errors because I believe that the
> memory content at that time is uncertain. Therefore, I surely think
> that we should have a way to tell weakref not to call the callbacks at
> program termination (or maybe this should be the defacto behavior). In
> my case, I got this error message when weakref attempted to execute a
> callback when the script ended (because the GC started to reap all
> local/global variables):
> Exception exceptions.SystemError: 'codec module not properly
> initialized' when attempting to access a method in the class that
> defined the callback.
> I propose to add a method in weakref called clear_all_callbacks that
> could be called to ensure that no callbacks will be called upon
> termination.
But just because you don't want your callbacks triggered doesn't mean to 
say there aren't other objects in the system that do want them called.

The memory content isn't 'uncertain' at all. All that has happened is that 
some modules have been uloaded before your callback is triggered. Try and 
write the callback to handle such situations.

One way you might do this would be to make the callback call a global 
function, but wrap the call inside a try: ... except NameError: pass
Your global function will probably be destroyed early on (or you can 
destroy it yourself when you don't want your callbacks to work anymore) and 
you can silently ignore the error. If the callbacks are class methods, 
simply use a class variable for the same effect.

Duncan Booth                                             duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?

More information about the Python-list mailing list