Destructor being called twice?

Longpoke longpoke at gmail.com
Mon Apr 12 15:05:01 EDT 2010


-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Hi,

Is it normal for the destructor to be called more than once? This code
caused it to happen:

import gtk

class A(gtk.Window):
    def __init__(self):
        gtk.Window.__init__(self)
        self.connect("delete-event", lambda w,e: gtk.main_quit())
    def __del__(self):
        print 'bye', self

if __name__ == '__main__':
    A().show()
    print 'enter main'
    gtk.main()
    print 'quitting'

$ python test.py 
bye <A object at 0x252bc80 (GtkWindow at 0x25bb240)>
enter main
bye <A object at 0x252bc80 (GtkWindow at 0x25bb240)>
quitting
$ python --version
Python 2.6.4

FYI, gtk.Window is a new-style class. There is another thread about
this claiming this is a bug, but the author only mentions it happening
with old-style classes:

http://mail.python.org/pipermail/python-dev/2006-August/068358.html

I don't suspect this is a bug in pygtk, as a grep for __del__ yields
nothing through pygtk's and pygobject's sources (pygobject is a heavy
dependency of pygtk).

Furthermore, pygtk has a test case to ensure __del__ is called after
GC (pygtk-2.16.0/tests/test_gdk.py), and pygobject has one that asserts
__del__ is only called once (pygobject-2.18.0/tests/test_subtype.py).

A snippet from pygobject-2.18.0/tests/test_subtype.py:
    def testSimpleDecref(self):
        class CallInDel:
            def __init__(self, callback):
                self.callback = callback

            def __del__(self):
                if callable(self.callback):
                    self.callback()
        disposed_calls = []
        def on_dispose():
            disposed_calls.append(None)
        gobj = gobject.GObject()
        gobj.set_data('tmp', CallInDel(on_dispose))
        del gobj
        assert len(disposed_calls) == 1 # <---- !!

So either this test case is wrong to assume the destructor can only be
called once, or there is a bug in Python?
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v2.0.14 (GNU/Linux)

iEYEARECAAYFAkvDbt0ACgkQ3PGpByoQpZEQBQCbB1pzcOBHWrB4RUqFLaEbKt1E
9a4AoKENPAwQ99g8Y/DJwJqDSQFPGZQ2
=/CUN
-----END PGP SIGNATURE-----


More information about the Python-list mailing list