@@ -66,55 +66,78 @@ class RangeMap(dict):
66
66
key_match_comparator, which defaults to less-than-or-equal.
67
67
A value is returned for a key if it is the first key that matches in
68
68
the sorted list of keys.
69
+
69
70
One may supply keyword parameters to be passed to the sort function used
70
71
to sort keys (i.e. key, reverse) as sort_params.
72
+
71
73
Let's create a map that maps 1-3 -> 'a', 4-6 -> 'b'
74
+
72
75
>>> r = RangeMap({3: 'a', 6: 'b'}) # boy, that was easy
73
76
>>> r[1], r[2], r[3], r[4], r[5], r[6]
74
77
('a', 'a', 'a', 'b', 'b', 'b')
78
+
75
79
Even float values should work so long as the comparison operator
76
80
supports it.
81
+
77
82
>>> r[4.5]
78
83
'b'
84
+
79
85
But you'll notice that the way rangemap is defined, it must be open-ended
80
86
on one side.
87
+
81
88
>>> r[0]
82
89
'a'
83
90
>>> r[-1]
84
91
'a'
92
+
85
93
One can close the open-end of the RangeMap by using undefined_value
94
+
86
95
>>> r = RangeMap({0: RangeMap.undefined_value, 3: 'a', 6: 'b'})
87
96
>>> r[0]
88
97
Traceback (most recent call last):
89
98
...
90
99
KeyError: 0
100
+
91
101
One can get the first or last elements in the range by using RangeMap.Item
102
+
92
103
>>> last_item = RangeMap.Item(-1)
93
104
>>> r[last_item]
94
105
'b'
106
+
95
107
.last_item is a shortcut for Item(-1)
108
+
96
109
>>> r[RangeMap.last_item]
97
110
'b'
111
+
98
112
Sometimes it's useful to find the bounds for a RangeMap
113
+
99
114
>>> r.bounds()
100
115
(0, 6)
116
+
101
117
RangeMap supports .get(key, default)
118
+
102
119
>>> r.get(0, 'not found')
103
120
'not found'
121
+
104
122
>>> r.get(7, 'not found')
105
123
'not found'
124
+
106
125
One often wishes to define the ranges by their left-most values,
107
126
which requires use of sort params and a key_match_comparator.
127
+
108
128
>>> r = RangeMap({1: 'a', 4: 'b'},
109
129
... sort_params=dict(reverse=True),
110
130
... key_match_comparator=operator.ge)
111
131
>>> r[1], r[2], r[3], r[4], r[5], r[6]
112
132
('a', 'a', 'a', 'b', 'b', 'b')
133
+
113
134
That wasn't nearly as easy as before, so an alternate constructor
114
135
is provided:
136
+
115
137
>>> r = RangeMap.left({1: 'a', 4: 'b', 7: RangeMap.undefined_value})
116
138
>>> r[1], r[2], r[3], r[4], r[5], r[6]
117
139
('a', 'a', 'a', 'b', 'b', 'b')
140
+
118
141
"""
119
142
120
143
def __init__ (self , source , sort_params = {}, key_match_comparator = operator .le ):
0 commit comments