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

green_magic.utils.registry   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 42
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 11
eloc 29
dl 0
loc 42
rs 10
c 0
b 0
f 0

6 Methods

Rating   Name   Duplication   Size   Complexity  
A ObjectRegistry.get() 0 4 2
A ObjectRegistry.__contains__() 0 2 1
A ObjectRegistry.add() 0 5 2
A ObjectRegistry.__new__() 0 7 2
A ObjectRegistry.pop() 0 4 2
A ObjectRegistry.remove() 0 4 2
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