Skip to content

Commit a07fc5b

Browse files
committed
py/objfloat: Allow float() to parse anything with the buffer protocol.
This generalises and simplifies the code and follows CPython behaviour.
1 parent 8667a5f commit a07fc5b

File tree

2 files changed

+10
-6
lines changed

2 files changed

+10
-6
lines changed

py/objfloat.c

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -137,19 +137,19 @@ STATIC mp_obj_t float_make_new(const mp_obj_type_t *type_in, size_t n_args, size
137137
return mp_obj_new_float(0);
138138

139139
case 1:
140-
default:
141-
if (MP_OBJ_IS_STR(args[0])) {
142-
// a string, parse it
143-
size_t l;
144-
const char *s = mp_obj_str_get_data(args[0], &l);
145-
return mp_parse_num_decimal(s, l, false, false, NULL);
140+
default: {
141+
mp_buffer_info_t bufinfo;
142+
if (mp_get_buffer(args[0], &bufinfo, MP_BUFFER_READ)) {
143+
// a textual representation, parse it
144+
return mp_parse_num_decimal(bufinfo.buf, bufinfo.len, false, false, NULL);
146145
} else if (mp_obj_is_float(args[0])) {
147146
// a float, just return it
148147
return args[0];
149148
} else {
150149
// something else, try to cast it to a float
151150
return mp_obj_new_float(mp_obj_get_float(args[0]));
152151
}
152+
}
153153
}
154154
}
155155

tests/float/float1.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,10 @@
3636
except ValueError:
3737
print("ValueError")
3838

39+
# construct from something with the buffer protocol
40+
print(float(b"1.2"))
41+
print(float(bytearray(b"3.4")))
42+
3943
# unary operators
4044
print(bool(0.0))
4145
print(bool(1.2))

0 commit comments

Comments
 (0)