Created
March 28, 2014 10:02
-
-
Save stlehmann/9829288 to your computer and use it in GitHub Desktop.
Decorator for singleton classes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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