summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorDavid Lechner <david@lechnology.com>2023-01-12 19:51:45 -0600
committerDamien George <damien@micropython.org>2023-05-19 12:06:06 +1000
commit8491eb190f2ea27f113c0cc7c0e619807a84f7ed (patch)
treebcd942be0d98eb80209d2028c673e7cfa7e5f54d
parenteaccaa36771f784dfb458b8ba3591f11513824e6 (diff)
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@pybricks.com>
-rw-r--r--py/objslice.c7
-rw-r--r--tests/basics/slice_op.py15
2 files changed, 22 insertions, 0 deletions
diff --git a/py/objslice.c b/py/objslice.c
index 01d4da0db..75fa3bc3f 100644
--- a/py/objslice.c
+++ b/py/objslice.c
@@ -46,6 +46,12 @@ STATIC void slice_print(const mp_print_t *print, mp_obj_t o_in, mp_print_kind_t
mp_print_str(print, ")");
}
+STATIC mp_obj_t slice_unary_op(mp_unary_op_t op, mp_obj_t o_in) {
+ // Needed to explicitly opt out of default __hash__.
+ // REVISIT: CPython implements comparison operators for slice.
+ return MP_OBJ_NULL;
+}
+
#if MICROPY_PY_BUILTINS_SLICE_INDICES
STATIC mp_obj_t slice_indices(mp_obj_t self_in, mp_obj_t length_obj) {
mp_int_t length = mp_obj_int_get_checked(length_obj);
@@ -104,6 +110,7 @@ MP_DEFINE_CONST_OBJ_TYPE(
mp_type_slice,
MP_QSTR_slice,
MP_TYPE_FLAG_NONE,
+ unary_op, slice_unary_op,
SLICE_TYPE_ATTR_OR_LOCALS_DICT
print, slice_print
);
diff --git a/tests/basics/slice_op.py b/tests/basics/slice_op.py
new file mode 100644
index 000000000..f1e83c5e2
--- /dev/null
+++ b/tests/basics/slice_op.py
@@ -0,0 +1,15 @@
+
+try:
+ t = [][:]
+except:
+ print("SKIP")
+ raise SystemExit
+
+
+# REVISIT: slice comparison operators are not implemented in MicroPython
+
+# test that slice is not hashable, i.e. it can't be used to copy a dict
+try:
+ {}[:] = {}
+except TypeError:
+ print('TypeError')