so_magic.utils.registry.ObjectRegistry.get()   A
last analyzed

Complexity

Conditions 2

Size

Total Lines 4
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 4
nop 2
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
from abc import ABC
2
3
__all__ = ['ObjectRegistry', 'ObjectRegistryError']
4
5
6
class ObjectRegistry(ABC):
7
    """Simple dict-like retrieval/inserting "store" facility."""
8
9
    def __new__(cls, *args, **kwargs):
10
        object_registry = super().__new__(cls)
11
        if args:
12
            object_registry.objects = args[0]
13
        else:
14
            object_registry.objects = {}
15
        return object_registry
16
17
    def add(self, key, value):
18
        if self.objects.get(key, None):
19
            raise ObjectRegistryError(f"Requested to insert value '{value}' in already existing key '{key}'. "
20
                                      f"All keys are [{', '.join(_ for _ in self.objects)}]")
21
        self.objects[key] = value
22
23
    def remove(self, key):
24
        if key not in self.objects:
25
            raise ObjectRegistryError(f"Requested to remove item with key {key}, which does not exist.")
26
        self.objects.pop(key)
27
28
    def pop(self, key):
29
        if key not in self.objects:
30
            raise ObjectRegistryError(f"Requested to pop item with key {key}, which does not exist.")
31
        return self.objects.pop(key)
32
33
    def get(self, key):
34
        if key not in self.objects:
35
            raise ObjectRegistryError(f"Requested to get item with key {key}, which does not exist.")
36
        return self.objects[key]
37
38
    def __iter__(self):
39
        return iter(self.objects.items())
40
41
    def __contains__(self, item):
42
        return item in self.objects
43
44
    def __eq__(self, other):
45
        return dict(self.objects) == dict(other)
46
47
    def __repr__(self):
48
        return repr(self.objects)
49
50
51
class ObjectRegistryError(Exception): pass
52