forked from fluentpython/example-code-2e
-
Notifications
You must be signed in to change notification settings - Fork 0
/
missing.py
122 lines (88 loc) · 2.38 KB
/
missing.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
"""
Semantics of ``__missing__`` across mappings.
✅ = indicates ``__missing__`` was called
Subclass of ``dict``::
>>> d = DictSub(A = 'letter A')
>>> d['a'] # ✅
'letter A'
>>> d.get('a', '')
''
>>> 'a' in d
False
Subclass of ``UserDict``::
>>> ud = UserDictSub(A = 'letter A')
>>> ud['a'] # ✅
'letter A'
>>> ud.get('a', '') # ✅
'letter A'
>>> 'a' in ud
False
Simple subclass of ``abc.Mapping``::
>>> sms = SimpleMappingSub(A = 'letter A')
>>> sms['a']
Traceback (most recent call last):
...
KeyError: 'a'
>>> sms.get('a', '')
''
>>> 'a' in sms
False
Subclass of ``abc.Mapping`` with support for ``__missing__``::
>>> mms = MappingMissingSub(A = 'letter A')
>>> mms['a'] # ✅
'letter A'
>>> mms.get('a', '') # ✅
'letter A'
>>> 'a' in mms # ✅
True
Subclass of ``abc.Mapping`` with support for ``__missing__``::
>>> dms = DictLikeMappingSub(A = 'letter A')
>>> dms['a'] # ✅
'letter A'
>>> dms.get('a', '')
''
>>> 'a' in dms
False
"""
from collections import UserDict
from collections import abc
def _upper(x):
try:
return x.upper()
except AttributeError:
return x
class DictSub(dict):
def __missing__(self, key):
return self[_upper(key)]
class UserDictSub(UserDict):
def __missing__(self, key):
return self[_upper(key)]
class SimpleMappingSub(abc.Mapping):
def __init__(self, *args, **kwargs):
self._data = dict(*args, **kwargs)
# next three methods: abstract in ABC
def __getitem__(self, key):
return self._data[key]
def __len__(self):
return len(self._data)
def __iter__(self):
return iter(self._data)
# never called by instances of this class
def __missing__(self, key):
return self[_upper(key)]
class MappingMissingSub(SimpleMappingSub):
def __getitem__(self, key):
try:
return self._data[key]
except KeyError:
return self[_upper(key)]
class DictLikeMappingSub(SimpleMappingSub):
def __getitem__(self, key):
try:
return self._data[key]
except KeyError:
return self[_upper(key)]
def get(self, key, default=None):
return self._data.get(key, default)
def __contains__(self, key):
return key in self._data