-
Notifications
You must be signed in to change notification settings - Fork 60
/
Copy pathsingleton.py
36 lines (26 loc) · 866 Bytes
/
singleton.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
from threading import Lock
class SingletonMeta(type):
"""
This is a thread-safe implementation of Singleton.
"""
_instances = {}
_lock: Lock = Lock()
def __call__(cls, *args, **kwargs):
with cls._lock:
if cls not in cls._instances:
instance = super().__call__(*args, **kwargs)
cls._instances[cls] = instance
return cls._instances[cls]
class SingletonMetaNoArgs(type):
"""
Singleton metaclass for classes without parameters on constructor,
for compatibility with FastApi Depends() function.
"""
_instances = {}
_lock: Lock = Lock()
def __call__(cls):
with cls._lock:
if cls not in cls._instances:
instance = super().__call__()
cls._instances[cls] = instance
return cls._instances[cls]