Passed
Push — master ( bcf14c...4a1f1b )
by Max
57s
created

structured_data._match.patterns.bind   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 55
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 25
dl 0
loc 55
rs 10
c 0
b 0
f 0
wmc 6

4 Methods

Rating   Name   Duplication   Size   Complexity  
A Bind.structure() 0 4 1
A Bind.bindings() 0 4 1
A Bind.destructure() 0 15 2
A Bind.__new__() 0 6 2
1
"""A pattern to bind external values to a match."""
2
3
from ..._not_in import not_in
4
from ..._pep_570_when import pep_570_when
5
from .basic_patterns import Pattern
6
from .compound_match import CompoundMatch
7
8
9
class Bind(CompoundMatch, tuple):
10
    """A wrapper that adds additional bindings to a successful match.
11
12
    The ``Bind`` constructor takes a single required argument, and any number
13
    of keyword arguments. The required argument is a matcher. When matching, if
14
    the match succeeds, the ``Bind`` instance adds bindings corresponding to
15
    its keyword arguments.
16
17
    First, the matcher is checked, then the bindings are added in the order
18
    they were passed.
19
    """
20
21
    __slots__ = ()
22
23
    @pep_570_when
24
    def __new__(cls, structure, kwargs):
25
        if not kwargs:
26
            return structure
27
        not_in(container=kwargs, item="_")
28
        return super(Bind, cls).__new__(cls, (structure, tuple(kwargs.items())))
29
30
    @property
31
    def structure(self):
32
        """Return the structure to match against."""
33
        return self[0]
34
35
    @property
36
    def bindings(self):
37
        """Return the bindings to add to the match."""
38
        return self[1]
39
40
    def destructure(self, value):
41
        """Return a list of sub-values to check.
42
43
        If ``value is self``, return all of the bindings, and the structure.
44
45
        Otherwise, return the corresponding bound values, followed by the
46
        original value.
47
        """
48
        # Letting mutmut touch this line thoroughly locked things up.
49
        if value is self:  # pragma: no mutate
50
            return [Pattern(name) for (name, _) in reversed(self.bindings)] + [
51
                self.structure
52
            ]
53
        return [binding_value for (_, binding_value) in reversed(self.bindings)] + [
54
            value
55
        ]
56