Coverage for Users/vladimirpavlov/PycharmProjects/parameterizable/src/mixinforge/singleton_mixin.py: 62%

1"""Mixin for implementing the singleton pattern.

2

3 This module provides SingletonMixin, which ensures each subclass maintains

4 exactly one instance that is returned on every instantiation attempt. This is

5 useful for classes that should have only a single instance throughout the

6 application lifetime, such as configuration managers or resource coordinators.

7"""

8 from __future__ import annotations

9

10 from .parameterizable_mixin import ParameterizableMixin

11

12

13 class SingletonMixin(ParameterizableMixin):

14 """Mixin for creating singleton classes.

15

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.

19

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] = {}

25

26 def __new__(cls):

27 """Create or return the singleton instance for this class.

28

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]

35