Python singleton, demonstrated using Qt

class ESingleton( object ):
    @classmethod
    def Stub(cls):
        cls.inst = cls()
        return cls.inst
    
    inst = Stub
    
    def __call__(self):
        return self

class EMainWindow( QtGui.QDockWidget, ESingleton ):
    def __init__(self):
        QtGui.QDockWidget.__init__(self)
        main = QtGui.QWidget()
        self.setWidget( main )
        self.setFloating( True )
        self.show()

print EMainWindow.inst
print EMainWindow.inst()
print EMainWindow.inst

@classmethod
def refresh(cls):
    cls.Stub()

Although you can make it as complex as you want, for example when the inst already is an instance of cls we can take the geometry to the refreshed instance.

@classmethod
def refresh(cls):
    if isinstance(cls.inst, cls):
        g = cls.geometry()
    cls.Stub().setGeometry(g)
    return cls.inst

Note that I did implement this method as override in the main window to keep the singleton generic and not Qt specific!

Here’s the fun:

print EMainWindow.inst
EMainWindow.refresh()
print EMainWindow.inst
EMainWindow.inst()
print EMainWindow.inst
EMainWindow.refresh()
print EMainWindow.inst
<bound method ObjectType.Stub of <class '__main__.EMainWindow'>>
<__main__.EMainWindow object at 0x000000001143DAC8>
<__main__.EMainWindow object at 0x000000001143DAC8>
<__main__.EMainWindow object at 0x000000001143D908>

As you can see the inst() call sticks to the method and the window can in fact be initialized with refresh without ever calling inst first.

Leave a Reply

Your email address will not be published. Required fields are marked *