Skip to content

Instantly share code, notes, and snippets.

@stlehmann
Created March 28, 2014 10:02
Show Gist options
  • Save stlehmann/9829288 to your computer and use it in GitHub Desktop.
Save stlehmann/9829288 to your computer and use it in GitHub Desktop.
Decorator for singleton classes
def singleton(cls):
"""
Provide a decorator for the Singleton pattern
"""
instances = {}
def getinstance():
if cls not in instances:
instances[cls] = cls()
return instances[cls]
#Ensure that docstrings are passed on
getinstance.__doc__ = cls.__doc__
getinstance.__repr__ = cls.__repr__
return getinstance
@singleton
class MyClass():
"""
This is my Singleton class.
Usage:
>>> a = MyClass()
>>> b = MyClass()
>>> print (a == b)
True
"""
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment