Skip to content

Commit

Permalink
py/objtype: Support full object model for get/set/delitem special meths.
Browse files Browse the repository at this point in the history
This makes these special methods have the same calling behaviour as other
methods in a class instance (mp_convert_member_lookup() is already called
by mp_obj_class_lookup()).
  • Loading branch information
dpgeorge committed Sep 28, 2018
1 parent 2eb0170 commit dd28890
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 11 deletions.
15 changes: 4 additions & 11 deletions py/objtype.c
Original file line number Diff line number Diff line change
Expand Up @@ -797,36 +797,29 @@ STATIC void mp_obj_instance_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest) {

STATIC mp_obj_t instance_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) {
mp_obj_instance_t *self = MP_OBJ_TO_PTR(self_in);
mp_obj_t member[2] = {MP_OBJ_NULL};
mp_obj_t member[4] = {MP_OBJ_NULL, MP_OBJ_NULL, index, value};
struct class_lookup_data lookup = {
.obj = self,
.meth_offset = offsetof(mp_obj_type_t, subscr),
.dest = member,
.is_type = false,
};
size_t meth_args;
if (value == MP_OBJ_NULL) {
// delete item
lookup.attr = MP_QSTR___delitem__;
mp_obj_class_lookup(&lookup, self->base.type);
meth_args = 2;
} else if (value == MP_OBJ_SENTINEL) {
// load item
lookup.attr = MP_QSTR___getitem__;
mp_obj_class_lookup(&lookup, self->base.type);
meth_args = 2;
} else {
// store item
lookup.attr = MP_QSTR___setitem__;
mp_obj_class_lookup(&lookup, self->base.type);
meth_args = 3;
}
mp_obj_class_lookup(&lookup, self->base.type);
if (member[0] == MP_OBJ_SENTINEL) {
return mp_obj_subscr(self->subobj[0], index, value);
} else if (member[0] != MP_OBJ_NULL) {
mp_obj_t args[3] = {self_in, index, value};
// TODO probably need to call mp_convert_member_lookup, and use mp_call_method_n_kw
mp_obj_t ret = mp_call_function_n_kw(member[0], meth_args, 0, args);
size_t n_args = value == MP_OBJ_NULL || value == MP_OBJ_SENTINEL ? 1 : 2;
mp_obj_t ret = mp_call_method_n_kw(n_args, 0, member);
if (value == MP_OBJ_SENTINEL) {
return ret;
} else {
Expand Down
15 changes: 15 additions & 0 deletions tests/basics/class_staticclassmethod.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,24 @@ def __sub__(rhs):
def __add__(self, rhs):
print('add', rhs)

# subscript special methods wrapped in staticmethod
@staticmethod
def __getitem__(item):
print('static get', item)
return 'item'
@staticmethod
def __setitem__(item, value):
print('static set', item, value)
@staticmethod
def __delitem__(item):
print('static del', item)

c = C()

c.f(0)
c.g(0)
c - 1
c + 2
print(c[1])
c[1] = 2
del c[3]

0 comments on commit dd28890

Please sign in to comment.