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