summaryrefslogtreecommitdiff
path: root/py/runtime.c
diff options
context:
space:
mode:
authorPaul Sokolovsky <pfalcon@users.sourceforge.net>2018-08-29 17:59:36 +0300
committerDamien George <damien.p.george@gmail.com>2018-12-07 17:28:04 +1100
commitb1d08726eeeadf0b91358cc8c46e156695b6a9c0 (patch)
treea8d8235ef2738961eab0ca0c2da74e85ecef861d /py/runtime.c
parent113f00a9ab469a83d1004dac502077af0a8f4847 (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/runtime.c')
-rw-r--r--py/runtime.c20
1 files changed, 16 insertions, 4 deletions
diff --git a/py/runtime.c b/py/runtime.c
index 33c4c1822..e512b8b0d 100644
--- a/py/runtime.c
+++ b/py/runtime.c
@@ -228,6 +228,7 @@ mp_obj_t mp_unary_op(mp_unary_op_t op, mp_obj_t arg) {
case MP_UNARY_OP_HASH:
return arg;
case MP_UNARY_OP_POSITIVE:
+ case MP_UNARY_OP_INT:
return arg;
case MP_UNARY_OP_NEGATIVE:
// check for overflow
@@ -265,12 +266,23 @@ mp_obj_t mp_unary_op(mp_unary_op_t op, mp_obj_t arg) {
return result;
}
}
+ // With MP_UNARY_OP_INT, mp_unary_op() becomes a fallback for mp_obj_get_int().
+ // In this case provide a more focused error message to not confuse, e.g. chr(1.0)
if (MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE) {
- mp_raise_TypeError("unsupported type for operator");
+ if (op == MP_UNARY_OP_INT) {
+ mp_raise_TypeError("can't convert to int");
+ } else {
+ mp_raise_TypeError("unsupported type for operator");
+ }
} else {
- nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
- "unsupported type for %q: '%s'",
- mp_unary_op_method_name[op], mp_obj_get_type_str(arg)));
+ if (op == MP_UNARY_OP_INT) {
+ nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
+ "can't convert %s to int", mp_obj_get_type_str(arg)));
+ } else {
+ nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_TypeError,
+ "unsupported type for %q: '%s'",
+ mp_unary_op_method_name[op], mp_obj_get_type_str(arg)));
+ }
}
}
}