Skip to content

Commit 8926788

Browse files
committed
py/objlist: For list slice assignment, allow RHS to be a tuple or list.
Before this patch, assigning anything other than a list would lead to a crash. Fixes issue adafruit#2886.
1 parent 6fc6f10 commit 8926788

2 files changed

Lines changed: 16 additions & 5 deletions

File tree

py/objlist.c

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -192,13 +192,13 @@ STATIC mp_obj_t list_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) {
192192
#if MICROPY_PY_BUILTINS_SLICE
193193
if (MP_OBJ_IS_TYPE(index, &mp_type_slice)) {
194194
mp_obj_list_t *self = MP_OBJ_TO_PTR(self_in);
195-
mp_check_self(MP_OBJ_IS_TYPE(value, &mp_type_list));
196-
mp_obj_list_t *slice = MP_OBJ_TO_PTR(value);
195+
mp_uint_t value_len; mp_obj_t *value_items;
196+
mp_obj_get_array(value, &value_len, &value_items);
197197
mp_bound_slice_t slice_out;
198198
if (!mp_seq_get_fast_slice_indexes(self->len, index, &slice_out)) {
199199
mp_not_implemented("");
200200
}
201-
mp_int_t len_adj = slice->len - (slice_out.stop - slice_out.start);
201+
mp_int_t len_adj = value_len - (slice_out.stop - slice_out.start);
202202
//printf("Len adj: %d\n", len_adj);
203203
if (len_adj > 0) {
204204
if (self->len + len_adj > self->alloc) {
@@ -208,10 +208,10 @@ STATIC mp_obj_t list_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) {
208208
self->alloc = self->len + len_adj;
209209
}
210210
mp_seq_replace_slice_grow_inplace(self->items, self->len,
211-
slice_out.start, slice_out.stop, slice->items, slice->len, len_adj, sizeof(*self->items));
211+
slice_out.start, slice_out.stop, value_items, value_len, len_adj, sizeof(*self->items));
212212
} else {
213213
mp_seq_replace_slice_no_grow(self->items, self->len,
214-
slice_out.start, slice_out.stop, slice->items, slice->len, sizeof(*self->items));
214+
slice_out.start, slice_out.stop, value_items, value_len, sizeof(*self->items));
215215
// Clear "freed" elements at the end of list
216216
mp_seq_clear(self->items, self->len + len_adj, self->len, sizeof(*self->items));
217217
// TODO: apply allocation policy re: alloc_size

tests/basics/list_slice_assign.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,3 +34,14 @@
3434
l = list(x)
3535
del l[:-3]
3636
print(l)
37+
38+
# assign a tuple
39+
l = [1, 2, 3]
40+
l[0:1] = (10, 11, 12)
41+
print(l)
42+
43+
# RHS of slice must be an iterable
44+
try:
45+
[][0:1] = 123
46+
except TypeError:
47+
print('TypeError')

0 commit comments

Comments
 (0)