In Python, is there a way to call a function after an object is finalized?
I thought the callback in a weakref would do it, but it appears a weakref's callback is called once the object is garbage collected, but before the objects __del__
method is called. This seems contrary to the notes on weakrefs and garbace collection in the Python trunk. Here's an example.
import sys
import weakref
class Spam(object) :
def __init__(self, name) :
self.name = name
def __del__(self) :
sys.stdout.write("Deleting Spam:%s\n" % self.name)
sys.stdout.flush()
def cleaner(reference) :
sys.stdout.write("In callback with reference %s\n" % reference)
sys.stdout.flush()
spam = Spam("first")
wk_spam = weakref.ref(spam, cleaner)
del spam
The output I get is
$ python weakref_test.py
In callback with reference <weakref at 0xc760a8; dead>
Deleting Spam:first
Is there some other conventional way to do what I want? Can I somehow force the finalization in my callback?