Andy's insights

Opinions, thoughts, archivements

Wed, 12 Apr 2006

Singleton and Borg Design Pattern

The Singleton Design Pattern is quite popular.

As usual Python provides an easy and even better solution for most situations the Singleton seems appropriate. But first look at our options:

The classic Singleton pattern implemented in Python looks like this:

class Singleton(object):
    def __new__(cls, *p, **k):
        if not '_the_instance' in cls.__dict__:
            cls._the_instance = object.__new__(cls)
        return cls._the_instance

The Borg Design Pattern Borg Design Pattern shares just one state. I’ve found it at ASPN (Alex Martelli).

The main idea is to just share the state by replacing the default instance dictionary with a shared one:

class Borg(object):
    _state = {}
    def __new__(cls, *p, **k):
        self = object.__new__(cls, *p, **k)
        self.__dict__ = cls._state
        return self

The best solution I found is to just use the Python mechanics: A Module is a singleton, why not just use it?

class _SingleInstance(object):
    def __init__(self):
        self.foo = 23
SingleInstance = _SingleInstance
del _SingleInstance

A good discussion about those pattern (and some others) can be found here: http://www.aleax.it/Python/5ep.html

The Borg design pattern can be found at ASPN: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66531

posted at: 13:05 | path: /python | permanent link to this entry