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

ObjectRegistry.__new__()   A

Complexity

Conditions 2

Size

Total Lines 7
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 6
dl 0
loc 7
rs 10
c 0
b 0
f 0
cc 2
nop 3
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
        x = super().__new__(cls)
11
        if args:
12
            x.objects = args[0]
13
        else:
14
            x.objects = {}
15
        return x
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 remove 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 __contains__(self, item):
39
        return item in self.objects
40
41
class ObjectRegistryError(Exception): pass
42