Passed
Push — master ( d0bccf...cb153d )
by Max
58s
created

structured_data._processors   A

Complexity

Total Complexity 18

Size/Duplication

Total Lines 83
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 57
dl 0
loc 83
rs 10
c 0
b 0
f 0
wmc 18

9 Methods

Rating   Name   Duplication   Size   Complexity  
A Processor.__call__() 0 2 1
A ProcessorList.__init__() 0 2 1
A Processor.__init__() 0 2 1
A AsPatternProcessor.__call__() 0 4 2
A ProcessorList.get_processor() 0 5 3
A ADTProcessor.__call__() 0 4 2
A TupleProcessor.__call__() 0 4 3
A ProcessorList.names() 0 15 4
A ProcessorList.custom() 0 3 1
1
from ._adt_constructor import ADTConstructor
2
from ._match_failure import MatchFailure
3
from ._not_in import not_in
4
from ._patterns import AsPattern
5
from ._patterns import Pattern
6
from ._unpack import unpack
7
8
9
class Processor:
10
11
    def __init__(self, target):
12
        self.target = target
13
14
    def __call__(self, value):
15
        raise NotImplementedError
16
17
    type = None
18
19
20
class AsPatternProcessor(Processor):
21
22
    def __call__(self, value):
23
        if self.target is value:
24
            return reversed(self.target)
25
        return (value, value)
26
27
    type = AsPattern
28
29
30
class ADTProcessor(Processor):
31
32
    def __call__(self, value):
33
        if value.__class__ is not self.target.__class__:
34
            raise MatchFailure
35
        return reversed(unpack(value))
36
37
    type = ADTConstructor
38
39
40
class TupleProcessor(Processor):
41
42
    def __call__(self, value):
43
        if isinstance(value, self.target.__class__) and len(self.target) == len(value):
44
            return reversed(value)
45
        raise MatchFailure
46
47
    type = tuple
48
49
50
class ProcessorList:
51
52
    def __init__(self, *processors):
53
        self.processors = tuple(processors)
54
55
    def get_processor(self, item):
56
        for processor in self.processors:
57
            if isinstance(item, processor.type):
58
                return processor(item)
59
        return None
60
61
    @classmethod
62
    def custom(cls, *processors):
63
        return cls(AsPatternProcessor, ADTProcessor, *processors, TupleProcessor)
64
65
    def names(self, target):
66
        name_list = []
67
        names_seen = set()
68
        to_process = [target]
69
        while to_process:
70
            item = to_process.pop()
71
            if isinstance(item, Pattern):
72
                not_in(names_seen, item.name)
73
                names_seen.add(item.name)
74
                name_list.append(item.name)
75
            else:
76
                processor = self.get_processor(item)
77
                if processor:
78
                    to_process.extend(processor(item))
79
        return name_list
80
81
82
PROCESSORS = ProcessorList.custom()
83