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