| Total Complexity | 13 |
| Total Lines | 64 |
| Duplicated Lines | 0 % |
| Changes | 0 | ||
| 1 | from ._adt_constructor import ADTConstructor |
||
| 2 | from ._match_failure import MatchFailure |
||
| 3 | from ._patterns import AsPattern |
||
| 4 | from ._unpack import unpack |
||
| 5 | |||
| 6 | |||
| 7 | class Processor: |
||
| 8 | |||
| 9 | def __init__(self, target): |
||
| 10 | self.target = target |
||
| 11 | |||
| 12 | def __call__(self, value): |
||
| 13 | raise NotImplementedError |
||
| 14 | |||
| 15 | type = None |
||
| 16 | |||
| 17 | |||
| 18 | class AsPatternProcessor(Processor): |
||
| 19 | |||
| 20 | def __call__(self, value): |
||
| 21 | if self.target is value: |
||
| 22 | return reversed(self.target) |
||
| 23 | return (value, value) |
||
| 24 | |||
| 25 | type = AsPattern |
||
| 26 | |||
| 27 | |||
| 28 | class ADTProcessor(Processor): |
||
| 29 | |||
| 30 | def __call__(self, value): |
||
| 31 | if value.__class__ is not self.target.__class__: |
||
| 32 | raise MatchFailure |
||
| 33 | return reversed(unpack(value)) |
||
| 34 | |||
| 35 | type = ADTConstructor |
||
| 36 | |||
| 37 | |||
| 38 | class TupleProcessor(Processor): |
||
| 39 | |||
| 40 | def __call__(self, value): |
||
| 41 | if isinstance(value, self.target.__class__) and len(self.target) == len(value): |
||
| 42 | return reversed(value) |
||
| 43 | raise MatchFailure |
||
| 44 | |||
| 45 | type = tuple |
||
| 46 | |||
| 47 | |||
| 48 | class ProcessorList: |
||
| 49 | |||
| 50 | def __init__(self, processors=()): |
||
| 51 | self.processors = tuple(processors) |
||
| 52 | |||
| 53 | def get_processor(self, item): |
||
| 54 | for processor in self.processors: |
||
| 55 | if isinstance(item, processor.type): |
||
| 56 | return processor(item) |
||
| 57 | return None |
||
| 58 | |||
| 59 | |||
| 60 | PROCESSORS = ProcessorList(( |
||
| 61 | AsPatternProcessor, |
||
| 62 | ADTProcessor, |
||
| 63 | TupleProcessor, |
||
| 64 | )) |
||
| 65 |