Singleton Pattern for Python

In software engineering, the singleton pattern is a design pattern that is used to restrict instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system. Sometimes it is generalized to systems that operate more efficiently when only one or a few objects exist.

class Singleton(object):
    instance = None  lock_obj = threading.RLock()
    def __new__(self, *args, **kwargs):
         return self.get_instance( *args, **kwargs )

    @classmethod
    def get_instance(clazz, *args, **kwargs):
        with clazz.lock_obj:
            if clazz.instance is None:
                clazz.instance = object.__new__(clazz, *args, **kwargs)
                clazz.instance.init(*args, **kwargs)      return clazz.instance

    def __init__(self, *args, **kwargs):
         super( Singleton, self ).__init__(*args, **kwargs)

    def init(self, *args, **kwargs):      pass

class Test(Singleton):
    def init(self, *args, **kwargs):
        #do initializations here, not in __init__
        pass

print Test()
print Test()

The output of printing the value of the result of the “creating” the 2 Test objects will show that actually only one Test object was created.

This pattern is needed very often in Python, although when it is needed it addresses the problem very handily.

Note: this is code based off some searching earlier this year. I no longer remember exactly where I found the original that I based this work off of.

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • NewsVine
  • Reddit
  • StumbleUpon
  • YahooMyWeb
  • Google Bookmarks
  • Yahoo! Buzz
  • TwitThis
  • Live
  • LinkedIn
  • Pownce
  • MySpace

Leave a Reply

Security Code: