Passed
Push — master ( b636f8...bb23a2 )
by Max
56s
created

structured_data._patterns.guard.AsGuard.guard()   A

Complexity

Conditions 1

Size

Total Lines 3
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 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