forked from fluentpython/example-code-2e
-
Notifications
You must be signed in to change notification settings - Fork 0
/
uppermixin.py
140 lines (103 loc) · 2.96 KB
/
uppermixin.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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
"""
Short demos
===========
``UpperDict`` behaves like a case-insensitive mapping`::
# tag::UPPERDICT_DEMO[]
>>> d = UpperDict([('a', 'letter A'), (2, 'digit two')])
>>> list(d.keys())
['A', 2]
>>> d['b'] = 'letter B'
>>> 'b' in d
True
>>> d['a'], d.get('B')
('letter A', 'letter B')
>>> list(d.keys())
['A', 2, 'B']
# end::UPPERDICT_DEMO[]
And ``UpperCounter`` is also case-insensitive::
# tag::UPPERCOUNTER_DEMO[]
>>> c = UpperCounter('BaNanA')
>>> c.most_common()
[('A', 3), ('N', 2), ('B', 1)]
# end::UPPERCOUNTER_DEMO[]
Detailed tests
==============
UpperDict uppercases all string keys.
>>> d = UpperDict([('a', 'letter A'), ('B', 'letter B'), (2, 'digit two')])
Tests for item retrieval using `d[key]` notation::
>>> d['A']
'letter A'
>>> d['b']
'letter B'
>>> d[2]
'digit two'
Tests for missing key::
>>> d['z']
Traceback (most recent call last):
...
KeyError: 'Z'
>>> d[99]
Traceback (most recent call last):
...
KeyError: 99
Tests for item retrieval using `d.get(key)` notation::
>>> d.get('a')
'letter A'
>>> d.get('B')
'letter B'
>>> d.get(2)
'digit two'
>>> d.get('z', '(not found)')
'(not found)'
Tests for the `in` operator::
>>> ('a' in d, 'B' in d, 'z' in d)
(True, True, False)
Test for item assignment using lowercase key::
>>> d['c'] = 'letter C'
>>> d['C']
'letter C'
Tests for update using a `dict` or a sequence of pairs::
>>> d.update({'D': 'letter D', 'e': 'letter E'})
>>> list(d.keys())
['A', 'B', 2, 'C', 'D', 'E']
>>> d.update([('f', 'letter F'), ('G', 'letter G')])
>>> list(d.keys())
['A', 'B', 2, 'C', 'D', 'E', 'F', 'G']
>>> d # doctest:+NORMALIZE_WHITESPACE
{'A': 'letter A', 'B': 'letter B', 2: 'digit two',
'C': 'letter C', 'D': 'letter D', 'E': 'letter E',
'F': 'letter F', 'G': 'letter G'}
UpperCounter uppercases all `str` keys.
Test for initializer: keys are uppercased.
>>> d = UpperCounter('AbracAdaBrA')
>>> sorted(d.keys())
['A', 'B', 'C', 'D', 'R']
Tests for count retrieval using `d[key]` notation::
>>> d['a']
5
>>> d['z']
0
"""
# tag::UPPERCASE_MIXIN[]
import collections
def _upper(key): # <1>
try:
return key.upper()
except AttributeError:
return key
class UpperCaseMixin: # <2>
def __setitem__(self, key, item):
super().__setitem__(_upper(key), item)
def __getitem__(self, key):
return super().__getitem__(_upper(key))
def get(self, key, default=None):
return super().get(_upper(key), default)
def __contains__(self, key):
return super().__contains__(_upper(key))
# end::UPPERCASE_MIXIN[]
# tag::UPPERDICT[]
class UpperDict(UpperCaseMixin, collections.UserDict): # <1>
pass
class UpperCounter(UpperCaseMixin, collections.Counter): # <2>
"""Specialized 'Counter' that uppercases string keys""" # <3>
# end::UPPERDICT[]