Using GtkBuilder and connect_signals

I have been hunting spontaneous crashes with errors from the C GTK libs. The errors looked somewhat like these:

Warning: g_object_ref: assertion `G_IS_OBJECT (object)' failed  
  gtk.main()  
Warning: instance of invalid non-instantiatable type `AtkSelection'  
  gtk.main()  
Warning: g_signal_emit_valist: assertion `G_TYPE_CHECK_INSTANCE (instance)' failed  
  gtk.main()  
(...)  
Warning: instance of invalid non-instantiatable type `'  
  gtk.main()

In most versions of GTK window decorators, this caused a crash - in a few lucky cases, it didn't! My (wrong) assumption was that calling connect_signals was only of interest, if I actually had signal handlers to connect. This is also the case when looking at the docs. For instance:

The function connect_signals and variants thereof ~~can~~ MUST be used to connect handlers to the named signals in the description.

(...)

For each of handlers that cannot be found, a RuntimeWarning is issued.

However, when the warning was issued, GTK would crash anyways. This behavior was most like caused by dereferencing and deleting GTK widgets, which caused GTK to look for an on_delete_event handler as some sort of default behavior. Since I have a program that adds and removes GTK widgets during runtime, my program needed to handle these signals, even if the event handler would simply be empty. To make a long story short, you should ALWAYS make sure to call connect_signals no matter what, as it will connect core event handlers that you may not be aware of. This is how it should look:

class YourObject():  
    def __init__(self):  
        glade = add_from_file("x.glade")  
        win = glade.get_object("window")  
        win.show_all()  
        # ALWAYS DO THIS:  
        glade.connect_signals(self)





    def on_delete_event(self, *args):  
        pass

And even if the above may not fail, here is something that will potentially fail if you don't connect the signals. Please beware, that using the same on_delete_event handler for two different objects is a bad strategy.

Always take care that widgets are removed and deleted, and that delete events may be invoked at very separate places in your application. You should also be aware that the python garbage collector could be the one initiating these events, causing those strange c library reference errors.