singleton.py 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. from __future__ import absolute_import
  2. # Copyright (c) 2010-2019 openpyxl
  3. import weakref
  4. class Singleton(type):
  5. """
  6. Singleton metaclass
  7. Based on Python Cookbook 3rd Edition Recipe 9.13
  8. Only one instance of a class can exist. Does not work with __slots__
  9. """
  10. def __init__(self, *args, **kw):
  11. super(Singleton, self).__init__(*args, **kw)
  12. self.__instance = None
  13. def __call__(self, *args, **kw):
  14. if self.__instance is None:
  15. self.__instance = super(Singleton, self).__call__(*args, **kw)
  16. return self.__instance
  17. class Cached(type):
  18. """
  19. Caching metaclass
  20. Child classes will only create new instances of themselves if
  21. one doesn't already exist. Does not work with __slots__
  22. """
  23. def __init__(self, *args, **kw):
  24. super(Singleton, self).__init__(*args, **kw)
  25. self.__cache = weakref.WeakValueDictionary()
  26. def __call__(self, *args):
  27. if args in self.__cache:
  28. return self.__cache[args]
  29. obj = super(Singleton, self).__call__(*args)
  30. self.__cache[args] = obj
  31. return obj