Passed
Push — dev ( 1b3874...6a1e3c )
by Konstantinos
03:33
created

ObjectRegistry.__new__()   A

Complexity

Conditions 2

Size

Total Lines 5
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 5
dl 0
loc 5
rs 10
c 0
b 0
f 0
cc 2
nop 3
1
from abc import ABC
2
3
__all__ = ['Singleton']
4
5
6
class Singleton(ABC):
7
    _instance = None
8
    def __new__(cls, *args, **kwargs):
9
        if not cls._instance:
10
            cls._instance = super(Singleton, cls).__new__(cls)
11
        return cls._instance
12
13
14
if __name__ == '__main__':
15
    class ObjectRegistry(Singleton):
16
        def __new__(cls, *args, **kwargs):
17
            x = super().__new__(cls)
18
            if not getattr(x, 'objects', None):
19
                x.objects = {}
20
            return x
21
22
    reg1 = ObjectRegistry()
23
    reg1.objects['a'] = 1
24
    reg2 = ObjectRegistry()
25
    assert reg2.objects == {'a': 1}
26
    reg2.objects['b'] = 2
27
    reg3 = ObjectRegistry()
28
29
    rs = [reg1, reg2, reg3]
30
31
    assert id(reg1) == id(reg2) == id(reg3)
32
    for i in rs:
33
        print(i.objects)
34
        assert i.objects == {'a': 1, 'b': 2}
35
    assert all(x.objects == {'a': 1,
36
                             'b': 2} for x in rs)
37
    del reg3.objects['a']
38
    assert all(x.objects == {'b': 2} for x in rs)
39
    for i in rs:
40
        print(i.objects)
41
        assert i.objects == {'b': 2}
42