Coverage for Users / vladimirpavlov / PycharmProjects / parameterizable / src / mixinforge / singleton_mixin.py: 62%
8 statements
« prev ^ index » next coverage.py v7.13.1, created at 2026-01-01 16:37 -0600
« prev ^ index » next coverage.py v7.13.1, created at 2026-01-01 16:37 -0600
1"""Mixin for implementing the singleton pattern.
3This module provides SingletonMixin, which ensures each subclass maintains
4exactly one instance that is returned on every instantiation attempt. This is
5useful for classes that should have only a single instance throughout the
6application lifetime, such as configuration managers or resource coordinators.
7"""
8from __future__ import annotations
10from .parameterizable_mixin import ParameterizableMixin
13class SingletonMixin(ParameterizableMixin):
14 """Mixin for creating singleton classes.
16 Ensures each subclass maintains exactly one instance that is returned
17 on every instantiation. The singleton instance is stored per class type,
18 so each subclass has its own singleton instance.
20 Note:
21 This implementation is not thread-safe. For multi-threaded applications,
22 additional synchronization mechanisms should be added.
23 """
24 _instances: dict[type, SingletonMixin] = {}
26 def __new__(cls):
27 """Create or return the singleton instance for this class.
29 Returns:
30 The singleton instance for this class.
31 """
32 if cls not in SingletonMixin._instances:
33 SingletonMixin._instances[cls] = super().__new__(cls)
34 return SingletonMixin._instances[cls]