Search code examples
pythonwxpythonpublish-subscribe

Defining a wx.Panel destructor in wxpython


How do you define a destructor for a wx.Panel in wxpython?

META: After inheriting a code base which uses wxpython and PyPubSub I've discovered a huge number of pubsub subscriptions in the __init__ functions of wx.Panel's that are never unsubscribed and cause errors later on in the program.


Solution

  • You should be able to bind to EVT_WINDOW_DESTROY and do the unsub in the handler.

    For example:

    class MyPanel(wx.Panel):
    
    def __init__(self, parent):
        wx.Panel.__init__(self, parent, wx.NewId())
    
        pub.subscribe(self.__handler, 'event')
    
        def __destroy(_):
            pub.unsubscribe(self.__handler, 'event')
    
        self.Bind(wx.EVT_WINDOW_DESTROY, __destroy)
    

    If above is not working you can protect against the PyDeadObjectError exception, by adding the following in the code where you try to access ExtendedWxPanel:

    if instanceOfExctendedWxPanel: then access it or methods of it.