-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsingleton.py
More file actions
62 lines (51 loc) · 1.44 KB
/
singleton.py
File metadata and controls
62 lines (51 loc) · 1.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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
# -*- coding: utf-8 -*-
#
# This module is part of the Frequent project, Copyright (C) 2019,
# Douglas Daly. The Frequent package is free software, licensed under
# the MIT License.
#
# Source Code:
# https://github.com/douglasdaly/frequent-py
# Documentation:
# https://frequent-py.readthedocs.io/en/latest
# License:
# https://frequent-py.readthedocs.io/en/latest/license.html
#
"""
Singleton utility metaclass.
Simply add it to any class you want to behave like a singleton via the
`metaclass`:
.. code-block:: python
class MyClass(SomeBaseClass, metaclass=Singleton):
def __init__(self, x: int) -> None:
self.x = x
return
Examples
--------
>>> my_instance = MyClass(42)
>>> my_instance.x
42
>>> another_instance = MyClass(43)
>>> another_instance.x
42
Note that values set in subsequent calls to `__init__` will have no
effect on the attribute. To change the attribute do so on any of
the instances:
>>> another_instance.x = 43
>>> my_instance.x
43
>>> my_instance.x = 42
>>> another_instance.x
42
"""
from weakref import WeakValueDictionary
class Singleton(type):
"""
Metaclass for singleton objects.
"""
__instances = WeakValueDictionary()
def __call__(cls: type, *args, **kwargs) -> None:
if cls not in cls.__instances:
instance = super().__call__(*args, **kwargs)
cls.__instances[cls] = instance
return cls.__instances[cls]