1
|
|
|
import collections |
2
|
|
|
import typing |
3
|
|
|
|
4
|
|
|
from ._patterns.basic_patterns import Pattern |
5
|
|
|
|
6
|
|
|
|
7
|
|
|
def _as_name(key): |
8
|
|
|
if isinstance(key, Pattern): |
9
|
|
|
return key.name |
10
|
|
|
return key |
11
|
|
|
|
12
|
|
|
|
13
|
|
|
def _multi_index(dct, key): |
14
|
|
|
if isinstance(key, tuple): |
15
|
|
|
return tuple(dct[sub_key] for sub_key in key) |
16
|
|
|
if isinstance(key, dict): |
17
|
|
|
return {name: dct[value] for (name, value) in key.items()} |
18
|
|
|
raise KeyError(key) |
19
|
|
|
|
20
|
|
|
|
21
|
|
|
class MatchDict(collections.abc.MutableMapping): |
22
|
|
|
"""A MutableMapping that allows for retrieval into structures. |
23
|
|
|
|
24
|
|
|
The actual keys in the mapping must be string values. Most of the mapping |
25
|
|
|
methods will only operate on or yield string keys. The exception is |
26
|
|
|
subscription: the "key" in subscription can be a structure made of tuples |
27
|
|
|
and dicts. For example, ``md["a", "b"] == (md["a"], md["b"])``, and |
28
|
|
|
``md[{1: "a"}] == {1: md["a"]}``. The typical use of this will be to |
29
|
|
|
extract many match values at once, as in ``a, b, c == md["a", "b", "c"]``. |
30
|
|
|
|
31
|
|
|
The behavior of most of the pre-defined MutableMapping methods is currently |
32
|
|
|
neither tested nor guaranteed. |
33
|
|
|
""" |
34
|
|
|
|
35
|
|
|
def __init__(self) -> None: |
36
|
|
|
self.data: typing.Dict[str, typing.Any] = {} |
37
|
|
|
|
38
|
|
|
def __getitem__(self, key): |
39
|
|
|
key = _as_name(key) |
40
|
|
|
if isinstance(key, str): |
41
|
|
|
return self.data[key] |
42
|
|
|
return _multi_index(self, key) |
43
|
|
|
|
44
|
|
|
def __setitem__(self, key, value): |
45
|
|
|
key = _as_name(key) |
46
|
|
|
if not isinstance(key, str): |
47
|
|
|
raise TypeError |
48
|
|
|
self.data[key] = value |
49
|
|
|
|
50
|
|
|
def __delitem__(self, key): |
51
|
|
|
del self.data[_as_name(key)] |
52
|
|
|
|
53
|
|
|
def __iter__(self): |
54
|
|
|
yield from self.data |
55
|
|
|
|
56
|
|
|
def __len__(self): |
57
|
|
|
return len(self.data) |
58
|
|
|
|