Skip to content

Commit a1351fb

Browse files
committed
SF patch #408326 by Robin Thomas: slice objects comparable, not
hashable This patch changes the behavior of slice objects in the following manner: - Slice objects are now comparable with other slice objects as though they were logically tuples of (start,stop,step). The tuple is not created in the comparison function, but the comparison behavior is logically equivalent. - Slice objects are not hashable. With the above change to being comparable, slice objects now cannot be used as keys in dictionaries. [I've edited the patch for style. Note that this fixes the problem that dict[i:j] seemed to work but was meaningless. --GvR]
1 parent 26ae7cd commit a1351fb

File tree

1 file changed

+23
-3
lines changed

1 file changed

+23
-3
lines changed

Objects/sliceobject.c

+23-3
Original file line numberDiff line numberDiff line change
@@ -155,6 +155,26 @@ static PyObject *slice_getattr(PySliceObject *self, char *name)
155155
return ret;
156156
}
157157

158+
static int
159+
slice_compare(PySliceObject *v, PySliceObject *w)
160+
{
161+
int result = 0;
162+
163+
if (v == w)
164+
return 0;
165+
166+
if (PyObject_Cmp(v->start, w->start, &result) < 0)
167+
return -2;
168+
if (result != 0)
169+
return result;
170+
if (PyObject_Cmp(v->stop, w->stop, &result) < 0)
171+
return -2;
172+
if (result != 0)
173+
return result;
174+
if (PyObject_Cmp(v->step, w->step, &result) < 0)
175+
return -2;
176+
return result;
177+
}
158178

159179
PyTypeObject PySlice_Type = {
160180
PyObject_HEAD_INIT(&PyType_Type)
@@ -166,9 +186,9 @@ PyTypeObject PySlice_Type = {
166186
0, /*tp_print*/
167187
(getattrfunc)slice_getattr, /*tp_getattr*/
168188
0, /*tp_setattr*/
169-
0, /*tp_compare*/
170-
(reprfunc)slice_repr, /*tp_repr*/
189+
(cmpfunc)slice_compare, /*tp_compare*/
190+
(reprfunc)slice_repr, /*tp_repr*/
171191
0, /*tp_as_number*/
172-
0, /*tp_as_sequence*/
192+
0, /*tp_as_sequence*/
173193
0, /*tp_as_mapping*/
174194
};

0 commit comments

Comments
 (0)