Tag Archives: design patterns

Singleton in Python

Singleton pattern should be the most known design pattern out there(maybe the most overused design pattern as well). The idea is to restrict the object creation to only one instance. The typical way of achieving this is to declare the Singleton class’s constructor as private and then provide a static method to do the object initiation. This method would create an object on it’s first call and then onward return the already created object. Since Python doesn’t have private constructors we have to go down a complete different path to achieve the same objective. Remember we have to somehow get between the object creation mechanism and make sure only one object is created at most. The right place to do this is __new__ which is where objects are created in Python. You can find a good introduction to __new__ here[1].

Here is an example Singleton class. What it does is check whether an object instance is already created and return it. If an object is not created yet it would call the super class’s __new__ where the object would be created and returned.

 class Singleton(object):
     __instance = None
     def __new__(cls, *args, **kwargs):
         if not cls.__instance:
             cls.__instance = super(Singleton, cls).__new__(cls,
*args, **kwargs)
         return cls.__instance

The downside of the above design is there is no simple way to subclass a singleton class.

Another popular pattern to achieve the same effect as the singleton pattern is the Borg pattern. This allows multiple object creation but forces each object to share the same state.

Here is an example Borg pattern.

class Borg(object):
    __state = {}
    def __init__(self):
        self.__dict__ = self.__state

[1] http://agiliq.com/blog/2012/06/__new__-python/