py: Improve __bool__ and __len__ dispatch; add slots for them.

This commit is contained in:
Damien George
2014-01-30 10:05:33 +00:00
parent b25711ea8f
commit 09a0c64bce
6 changed files with 56 additions and 30 deletions

View File

@@ -236,33 +236,16 @@ uint mp_get_index(const mp_obj_type_t *type, machine_uint_t len, mp_obj_t index)
// may return MP_OBJ_NULL
mp_obj_t mp_obj_len_maybe(mp_obj_t o_in) {
mp_small_int_t len = 0;
if (MP_OBJ_IS_STR(o_in)) {
len = mp_obj_str_get_len(o_in);
} else if (MP_OBJ_IS_TYPE(o_in, &tuple_type)) {
uint seq_len;
mp_obj_t *seq_items;
mp_obj_tuple_get(o_in, &seq_len, &seq_items);
len = seq_len;
} else if (MP_OBJ_IS_TYPE(o_in, &list_type)) {
uint seq_len;
mp_obj_t *seq_items;
mp_obj_list_get(o_in, &seq_len, &seq_items);
len = seq_len;
} else if (MP_OBJ_IS_TYPE(o_in, &dict_type)) {
len = mp_obj_dict_len(o_in);
return MP_OBJ_NEW_SMALL_INT((machine_int_t)mp_obj_str_get_len(o_in));
} else {
mp_obj_type_t *type = mp_obj_get_type(o_in);
if (type->unary_op != NULL) {
mp_obj_t result = type->unary_op(RT_UNARY_OP_LEN, o_in);
if (result != MP_OBJ_NULL) {
return result;
}
return type->unary_op(RT_UNARY_OP_LEN, o_in);
} else {
return MP_OBJ_NULL;
}
return MP_OBJ_NULL;
}
return MP_OBJ_NEW_SMALL_INT(len);
}
// Return input argument. Useful as .getiter for objects which are