aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorDamien George2017-11-21 15:01:38 +1100
committerDamien George2017-11-21 15:01:38 +1100
commita07fc5b6403b9a8bf7e7cb64f857272e5346d7e2 (patch)
tree7a74e3d2d8c4c3925316a5063b9bad4b089bf338
parent8667a5f0534238e3144adc35d487deb0ac5be5d6 (diff)
py/objfloat: Allow float() to parse anything with the buffer protocol.
This generalises and simplifies the code and follows CPython behaviour.
-rw-r--r--py/objfloat.c12
-rw-r--r--tests/float/float1.py4
2 files changed, 10 insertions, 6 deletions
diff --git a/py/objfloat.c b/py/objfloat.c
index 743287be6..75212a4d2 100644
--- a/py/objfloat.c
+++ b/py/objfloat.c
@@ -137,12 +137,11 @@ STATIC mp_obj_t float_make_new(const mp_obj_type_t *type_in, size_t n_args, size
return mp_obj_new_float(0);
case 1:
- default:
- if (MP_OBJ_IS_STR(args[0])) {
- // a string, parse it
- size_t l;
- const char *s = mp_obj_str_get_data(args[0], &l);
- return mp_parse_num_decimal(s, l, false, false, NULL);
+ default: {
+ mp_buffer_info_t bufinfo;
+ if (mp_get_buffer(args[0], &bufinfo, MP_BUFFER_READ)) {
+ // a textual representation, parse it
+ return mp_parse_num_decimal(bufinfo.buf, bufinfo.len, false, false, NULL);
} else if (mp_obj_is_float(args[0])) {
// a float, just return it
return args[0];
@@ -150,6 +149,7 @@ STATIC mp_obj_t float_make_new(const mp_obj_type_t *type_in, size_t n_args, size
// something else, try to cast it to a float
return mp_obj_new_float(mp_obj_get_float(args[0]));
}
+ }
}
}
diff --git a/tests/float/float1.py b/tests/float/float1.py
index c64f965a7..54807e5ac 100644
--- a/tests/float/float1.py
+++ b/tests/float/float1.py
@@ -36,6 +36,10 @@ try:
except ValueError:
print("ValueError")
+# construct from something with the buffer protocol
+print(float(b"1.2"))
+print(float(bytearray(b"3.4")))
+
# unary operators
print(bool(0.0))
print(bool(1.2))