Search

Recent

Tags

Singleton pattern in Python

Filed under Python on jul 23, 2010

Just came up with a simple pattern for singletons in Python using a class decorator:

def singleton(cls):
    instances = {}
    def instance():
        if cls not in instances:
            instances[cls] = cls()
        return instances[cls]
    return instance

Little demo:

>>> @singleton
... class Foo(object):
...     pass
...
>>> f1 = Foo()
>>> print id(f1)
3077430124
>>> f2 = Foo()
>>> print id(f2)
3077430124

Add to

Post your feedback

You can use this form to leave your feedback. Your insights are always appreciated.

Tools

View document source in text/plain