Skip to content

Commit 6d8edf6

Browse files
committed
Add store_item() virtual method to type to implement container[index] = val.
1 parent 166bb40 commit 6d8edf6

2 files changed

Lines changed: 13 additions & 1 deletion

File tree

py/obj.h

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,7 @@ typedef mp_obj_t (*mp_unary_op_fun_t)(int op, mp_obj_t);
9797
typedef mp_obj_t (*mp_binary_op_fun_t)(int op, mp_obj_t, mp_obj_t);
9898
typedef void (*mp_load_attr_fun_t)(mp_obj_t self_in, qstr attr, mp_obj_t *dest); // for fail, do nothing; for attr, dest[1] = value; for method, dest[0] = self, dest[1] = method
9999
typedef bool (*mp_store_attr_fun_t)(mp_obj_t self_in, qstr attr, mp_obj_t value); // return true if store succeeded
100+
typedef bool (*mp_store_item_fun_t)(mp_obj_t self_in, mp_obj_t index, mp_obj_t value); // return true if store succeeded
100101

101102
typedef struct _mp_method_t {
102103
const char *name;
@@ -162,6 +163,9 @@ struct _mp_obj_type_t {
162163

163164
mp_load_attr_fun_t load_attr;
164165
mp_store_attr_fun_t store_attr;
166+
// Implements container[index] = val; note that load_item is implemented
167+
// by binary_op(RT_BINARY_OP_SUBSCR)
168+
mp_store_item_fun_t store_item;
165169

166170
// these are for dynamically created types (classes)
167171
mp_obj_t bases_tuple;

py/runtime.c

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -905,7 +905,15 @@ void rt_store_subscr(mp_obj_t base, mp_obj_t index, mp_obj_t value) {
905905
// dict store
906906
mp_obj_dict_store(base, index, value);
907907
} else {
908-
assert(0);
908+
mp_obj_type_t *type = mp_obj_get_type(base);
909+
if (type->store_item != NULL) {
910+
bool r = type->store_item(base, index, value);
911+
if (r) {
912+
return;
913+
}
914+
// TODO: call base classes here?
915+
}
916+
nlr_jump(mp_obj_new_exception_msg_varg(MP_QSTR_TypeError, "'%s' object does not support item assignment", mp_obj_get_type_str(base)));
909917
}
910918
}
911919

0 commit comments

Comments
 (0)