Using '.attr' and '.locals_dict' to create an object with attributes and methods #9249
-
I'm not sure if I'm missing something obvious here, but I seem to have run into an issue where I can create an object that has attributes, or methods, but not both. I am defining it like this: // typedef struct _mp_obj_abc_t {...} mp_type_abc
// STATIC mp_obj_t abc_make_new(...)
// STATIC mp_obj_t abc_add_option()
// STATIC mp_obj_t abc_remove_option()
STATIC void abc_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest) {
if (dest[0] != MP_OBJ_NULL) {
return;
}
mp_obj_upy_channel_t *self = MP_OBJ_TO_PTR(self_in);
if (attr == MP_QSTR_text) {
dest[0] = self->text;
}
else if (attr == MP_QSTR_options) {
dest[0] = self->options;
}
else if (attr == MP_QSTR_config) {
dest[0] = self->config;
}
}
#define MAP_ENTRY_ABC(n) {MP_OBJ_NEW_QSTR(MP_QSTR_##n), (mp_obj_t)&abc_##n##_obj}
STATIC const mp_map_elem_t abc_locals_dict_table[] = {
{MP_OBJ_NEW_QSTR(MP_QSTR_add_option), (mp_obj_t)&abc_add_option_obj},
{MP_OBJ_NEW_QSTR(MP_QSTR_remove_option), (mp_obj_t)&abc_remove_option_obj},
};
STATIC MP_DEFINE_CONST_DICT(abc_locals_dict, abc_locals_dict_table);
const mp_obj_type_t mp_type_abc = {
{ &mp_type_type },
.name = MP_QSTR_abc,
.make_new = abc_make_new,
.locals_dict = (mp_obj_t)&abc_locals_dict,
.attr = abc_attr,
}; If I comment out the I looked in /py/obj.c but couldn't see any obvious reason why this was happening. Any insight would be helpful, thanks! |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 3 replies
-
IIRC if you have |
Beta Was this translation helpful? Give feedback.
-
This is pretty subtle. In |
Beta Was this translation helpful? Give feedback.
This is pretty subtle. In
attr
you need to signal that you still want the locals dict to be searched. See https://github.com/micropython/micropython/blob/master/py/runtime.c#L1177