akkudoktoreos.core.coreabc.SingletonMixin

class akkudoktoreos.core.coreabc.SingletonMixin(*args: Any, **kwargs: Any)

Bases: object

A thread-safe singleton mixin class.

Ensures that only one instance of the derived class is created, even when accessed from multiple threads. This mixin is intended to be combined with other classes, such as Pydantic models, to make them singletons.

_instances

A dictionary holding instances of each singleton class.

Type:

Dict[Type, Any]

_lock

A lock to synchronize access to singleton instance creation.

Type:

threading.Lock

Usage:
  • Inherit from SingletonMixin alongside other classes to make them singletons.

  • Avoid using __init__ to reinitialize the singleton instance after it has been created.

Example

class MySingletonModel(SingletonMixin, PydanticBaseModel):

name: str

# implement __init__ to avoid re-initialization of parent classes: def __init__(self, *args: Any, **kwargs: Any) -> None:

if hasattr(self, “_initialized”):

return

# Your initialisation here … super().__init__(*args, **kwargs)

instance1 = MySingletonModel(name=”Instance 1”) instance2 = MySingletonModel(name=”Instance 2”)

assert instance1 is instance2 # True print(instance1.name) # Output: “Instance 1”

__init__(*args: Any, **kwargs: Any) None

Initializes the singleton instance if it has not been initialized previously.

Further calls to __init__ are ignored for the singleton instance.

Parameters:
  • *args – Positional arguments for initialization.

  • **kwargs – Keyword arguments for initialization.

Methods

__init__(*args, **kwargs)

Initializes the singleton instance if it has not been initialized previously.

reset_instance()

Resets the singleton instance, forcing it to be recreated on next access.

static __new__(cls: Type[SingletonMixin], *args: Any, **kwargs: Any) SingletonMixin

Creates or returns the singleton instance of the class.

Ensures thread-safe instance creation by locking during the first instantiation.

Parameters:
  • *args – Positional arguments for instance creation (ignored if instance exists).

  • **kwargs – Keyword arguments for instance creation (ignored if instance exists).

Returns:

The singleton instance of the derived class.

Return type:

SingletonMixin

classmethod reset_instance() None

Resets the singleton instance, forcing it to be recreated on next access.

__init__(*args: Any, **kwargs: Any) None

Initializes the singleton instance if it has not been initialized previously.

Further calls to __init__ are ignored for the singleton instance.

Parameters:
  • *args – Positional arguments for initialization.

  • **kwargs – Keyword arguments for initialization.