Last Updated: February 25, 2016
·
1.177K
· socek

Singleton in python

If you wish to have a singleton class, you can achive it by implementing a decorator:

def singleton(*args, **kwargs):
    def initalizer(cls):
        instances = {}
        def getinstance():
            if cls not in instances:
                instances[cls] = cls(*args, **kwargs)
            return instances[cls]
        return getinstance()
    return initalizer

Now you can use it like this:

@singleton(10)
class MyClass:

    def __init__(self, something):
        self.inner = something

    def me(self):
        print self.inner

All the arguments provided in the sigleton decorator will be used to initalize a class. And you can use it like this

MyClass.me()