Steve Frécinaux

GObject singleton with python

Just as a reminder, since I find myself often looking for this snippet. Singleton is usually a bad idea, but sometimes it’s required to avoid data corruption or to avoid wasting resources. So use it carefully.

import gobject

class GObjectSingletonMeta(gobject.GObjectMeta):
    """GObject Singleton Metaclass"""

    def __init__(klass, name, bases, dict):
        gobject.GObjectMeta.__init__(klass, name, bases, dict)
        klass.__instance = None

    def __call__(klass, *args, **kwargs):
        if klass.__instance is None:
            klass.__instance = gobject.GObjectMeta.__call__(klass, *args, **kwargs)
        return klass.__instance

class SingletonObject(gobject.GObject):
    __metaclass__ = GObjectSingletonMeta

    def __init__(self):
        gobject.GObject.__init__(self)

For a stock python singleton object, you can simply replace gobject.GObject with object, and gobject.GObjectMeta with type.