Total Complexity | 11 |
Total Lines | 51 |
Duplicated Lines | 0 % |
Changes | 0 |
1 | from ._enum_constructor import EnumConstructor |
||
2 | from ._match_failure import MatchFailure |
||
3 | from ._patterns import AsPattern |
||
4 | from ._unpack import unpack |
||
5 | |||
6 | |||
7 | def as_pattern_processor(target): |
||
8 | def processor(value): |
||
9 | if target is value: |
||
10 | yield target.match |
||
11 | yield target.matcher |
||
12 | else: |
||
13 | yield value |
||
14 | yield value |
||
15 | return processor |
||
16 | |||
17 | |||
18 | def enum_processor(target): |
||
19 | def processor(value): |
||
20 | if value.__class__ is not target.__class__: |
||
21 | raise MatchFailure |
||
22 | yield from reversed(unpack(value)) |
||
23 | return processor |
||
24 | |||
25 | |||
26 | def tuple_processor(target): |
||
27 | def processor(value): |
||
28 | if isinstance(value, target.__class__) and len(target) == len(value): |
||
29 | yield from reversed(value) |
||
30 | else: |
||
31 | raise MatchFailure |
||
32 | return processor |
||
33 | |||
34 | |||
35 | class ProcessorList: |
||
36 | |||
37 | def __init__(self, processors=()): |
||
38 | self.processors = list(processors) |
||
39 | |||
40 | def get_processor(self, item): |
||
41 | for typ, meta_processor in self.processors: |
||
42 | if isinstance(item, typ): |
||
43 | return meta_processor(item) |
||
44 | return None |
||
45 | |||
46 | |||
47 | PROCESSORS = ProcessorList(( |
||
48 | (AsPattern, as_pattern_processor), |
||
49 | (EnumConstructor, enum_processor), |
||
50 | (tuple, tuple_processor), |
||
51 | )) |
||
52 |