class SingletonMixin: """ Threading safe singleton mixin class. Will run __init__ on subclasses for every invocation, so check self._initialized from __init__ to get around this if not desired. Use: class MyClass(SingletonMixin): def __init__(self): if not self._initialized: # initialize here self.foo = 'bar' # when done, set initialized to True self._initialized = True """ _instances: dict[type, Any] = {} _lock = threading.Lock() _initialized: bool def __new__(cls): with SingletonMixin._lock: if cls not in SingletonMixin._instances: # Create instance instance = super().__new__(cls) SingletonMixin._instances[cls] = instance instance._initialized = False # Return existing instance return SingletonMixin._instances[cls]