Singleton.py 1.3 KB

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