Total Complexity | 13 |
Total Lines | 49 |
Duplicated Lines | 0 % |
Changes | 0 |
1 | from .._match_failure import MatchFailure |
||
2 | from .basic_patterns import DISCARD |
||
3 | from .compound_match import CompoundMatch |
||
4 | |||
5 | |||
6 | class Guard(CompoundMatch, tuple): |
||
7 | |||
8 | __slots__ = () |
||
9 | |||
10 | def __new__(cls, guard, structure=DISCARD): |
||
11 | if structure is not DISCARD: |
||
12 | return AsGuard(guard, structure) |
||
13 | return super().__new__(cls, (guard,)) |
||
14 | |||
15 | def __getitem__(self, key): |
||
16 | return Guard(self.guard, key) |
||
17 | |||
18 | @property |
||
19 | def guard(self): |
||
20 | return tuple.__getitem__(self, 0) |
||
21 | |||
22 | def destructure(self, value): |
||
23 | if value is self or self.guard(value): |
||
24 | return () |
||
25 | raise MatchFailure |
||
26 | |||
27 | |||
28 | class AsGuard(CompoundMatch, tuple): |
||
29 | |||
30 | __slots__ = () |
||
31 | |||
32 | def __new__(cls, guard, structure): |
||
33 | return super().__new__(cls, (guard, structure)) |
||
34 | |||
35 | @property |
||
36 | def guard(self): |
||
37 | return self[0] |
||
38 | |||
39 | @property |
||
40 | def structure(self): |
||
41 | return self[1] |
||
42 | |||
43 | def destructure(self, value): |
||
44 | if value is self: |
||
45 | return (self.structure,) |
||
46 | if self.guard(value): |
||
47 | return (value,) |
||
48 | raise MatchFailure |
||
49 |