diff options
author | Paul Sokolovsky <pfalcon@users.sourceforge.net> | 2018-08-29 17:59:36 +0300 |
---|---|---|
committer | Damien George <damien.p.george@gmail.com> | 2018-12-07 17:28:04 +1100 |
commit | b1d08726eeeadf0b91358cc8c46e156695b6a9c0 (patch) | |
tree | a8d8235ef2738961eab0ca0c2da74e85ecef861d /py/objtype.c | |
parent | 113f00a9ab469a83d1004dac502077af0a8f4847 (diff) |
py/obj: Add support for __int__ special method.
Based on the discussion, this special method is available unconditionally,
as converting to int is a common operation.
Diffstat (limited to 'py/objtype.c')
-rw-r--r-- | py/objtype.c | 19 |
1 files changed, 16 insertions, 3 deletions
diff --git a/py/objtype.c b/py/objtype.c index 0881ae33f..fec73f16e 100644 --- a/py/objtype.c +++ b/py/objtype.c @@ -376,6 +376,7 @@ const byte mp_unary_op_method_name[MP_UNARY_OP_NUM_RUNTIME] = { [MP_UNARY_OP_BOOL] = MP_QSTR___bool__, [MP_UNARY_OP_LEN] = MP_QSTR___len__, [MP_UNARY_OP_HASH] = MP_QSTR___hash__, + [MP_UNARY_OP_INT] = MP_QSTR___int__, #if MICROPY_PY_ALL_SPECIAL_METHODS [MP_UNARY_OP_POSITIVE] = MP_QSTR___pos__, [MP_UNARY_OP_NEGATIVE] = MP_QSTR___neg__, @@ -421,9 +422,21 @@ STATIC mp_obj_t instance_unary_op(mp_unary_op_t op, mp_obj_t self_in) { return mp_unary_op(op, self->subobj[0]); } else if (member[0] != MP_OBJ_NULL) { mp_obj_t val = mp_call_function_1(member[0], self_in); - // __hash__ must return a small int - if (op == MP_UNARY_OP_HASH) { - val = MP_OBJ_NEW_SMALL_INT(mp_obj_get_int_truncated(val)); + + switch (op) { + case MP_UNARY_OP_HASH: + // __hash__ must return a small int + val = MP_OBJ_NEW_SMALL_INT(mp_obj_get_int_truncated(val)); + break; + case MP_UNARY_OP_INT: + // Must return int + if (!MP_OBJ_IS_INT(val)) { + mp_raise_TypeError(NULL); + } + break; + default: + // No need to do anything + ; } return val; } else { |