Skip to content

Commit b8c6bb4

Browse files
committed
py/objslice: Ensure slice is not hashable.
As per https://bugs.python.org/issue408326, the slice object should not be hashable. Since MicroPython has an implicit fallback when the unary_op slot is empty, we need to fill this slot. Signed-off-by: David Lechner <david@lechnology.com>
1 parent 08afb68 commit b8c6bb4

File tree

2 files changed

+22
-0
lines changed

2 files changed

+22
-0
lines changed

py/objslice.c

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,12 @@ STATIC void slice_print(const mp_print_t *print, mp_obj_t o_in, mp_print_kind_t
4646
mp_print_str(print, ")");
4747
}
4848

49+
STATIC mp_obj_t slice_unary_op(mp_unary_op_t op, mp_obj_t o_in) {
50+
// Needed to explicitly op out of default __hash__.
51+
// REVISIT: CPython implements comparison operators for slice.
52+
return MP_OBJ_NULL;
53+
}
54+
4955
#if MICROPY_PY_BUILTINS_SLICE_INDICES
5056
STATIC mp_obj_t slice_indices(mp_obj_t self_in, mp_obj_t length_obj) {
5157
mp_int_t length = mp_obj_int_get_checked(length_obj);
@@ -104,6 +110,7 @@ MP_DEFINE_CONST_OBJ_TYPE(
104110
mp_type_slice,
105111
MP_QSTR_slice,
106112
MP_TYPE_FLAG_NONE,
113+
unary_op, slice_unary_op,
107114
SLICE_TYPE_ATTR_OR_LOCALS_DICT
108115
print, slice_print
109116
);

tests/basics/slice_op.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
2+
try:
3+
t = [][:]
4+
except:
5+
print("SKIP")
6+
raise SystemExit
7+
8+
9+
# REVISIT: slice comparison operators are not implemented in MicroPython
10+
11+
# test that slice is not hashable, i.e. it can't be used to copy a dict
12+
try:
13+
{}[:] = {}
14+
except TypeError:
15+
print('TypeError')

0 commit comments

Comments
 (0)