Singleton.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. class Singleton:
  2. """
  3. (From Stackoverflow : http://stackoverflow.com/questions/31875/is-there-a-simple-elegant-way-to-define-singletons-in-python)
  4. A non-thread-safe helper class to ease implementing singletons.
  5. This should be used as a decorator -- not a metaclass -- to the
  6. class that should be a singleton.
  7. The decorated class can define one `__init__` function that
  8. takes only the `self` argument. Other than that, there are
  9. no restrictions that apply to the decorated class.
  10. To get the singleton instance, use the `Instance` method. Trying
  11. to use `__call__` will result in a `TypeError` being raised.
  12. Limitations: The decorated class cannot be inherited from.
  13. """
  14. def __init__(self, decorated):
  15. self._decorated = decorated
  16. def Instance(self):
  17. """
  18. Returns the singleton instance. Upon its first call, it creates a
  19. new instance of the decorated class and calls its `__init__` method.
  20. On all subsequent calls, the already created instance is returned.
  21. """
  22. try:
  23. return self._instance
  24. except AttributeError:
  25. self._instance = self._decorated()
  26. return self._instance
  27. def __call__(self):
  28. raise TypeError('Singletons must be accessed through `Instance()`.')
  29. def __instancecheck__(self, inst):
  30. return isinstance(inst, self._decorated)