Metaclasses¶
The helpers/metaclasses subpackage provides Python metaclass implementations for structural patterns such as the
singleton, giving classes framework-level behavioral guarantees.
Singleton¶
A thread-safe metaclass implementation of the singleton pattern that ensures a class has exactly one instance.
Singleton metaclass helpers.
archipy.helpers.metaclasses.singleton.SingletonInstance
module-attribute
¶
archipy.helpers.metaclasses.singleton.Singleton ¶
Bases: type
A thread-safe Singleton metaclass that ensures only one instance of a class is created.
This metaclass can be used to create Singleton classes. It supports an optional thread_safe
parameter to control whether thread-safety mechanisms (e.g., locks) should be used.
Attributes:
| Name | Type | Description |
|---|---|---|
_instances |
dict
|
A dictionary to store instances of Singleton classes. |
_lock |
RLock
|
A reentrant lock to ensure thread-safe instance creation; a singleton whose constructor creates another singleton does not deadlock. |
Example
To create a Singleton class, use the Singleton metaclass and optionally specify
whether thread-safety should be enabled:
class MySingletonClass(metaclass=Singleton, thread_safe=True):
def __init__(self, value):
self.value = value
# Create instances of MySingletonClass
instance1 = MySingletonClass(10)
instance2 = MySingletonClass(20)
# Verify that both instances are the same
print(instance1.value) # Output: 10
print(instance2.value) # Output: 10
print(instance1 is instance2) # Output: True
Source code in archipy/helpers/metaclasses/singleton.py
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 | |
options: show_root_toc_entry: false heading_level: 3