singleton.py 1023 B

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