Skip to content

Singleton

A metaclass to ensure we don't instantiate this class twice. One object will be created at the start of our application. After this, it will always use this specific instance.

Singleton

Bases: type

Credits go to https://www.linkedin.com/pulse/writing-thread-safe-singleton-class-python-saurabh-singh/

Source code in mac_notifications/singleton.py
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Singleton(type):
    """Credits go to https://www.linkedin.com/pulse/writing-thread-safe-singleton-class-python-saurabh-singh/"""

    _instances: Dict[Type, Any] = {}

    _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]