Skip to content

Commit

Permalink
py/objfloat: Allow float() to parse anything with the buffer protocol.
Browse files Browse the repository at this point in the history
This generalises and simplifies the code and follows CPython behaviour.
  • Loading branch information
dpgeorge committed Nov 21, 2017
1 parent 8667a5f commit a07fc5b
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 6 deletions.
12 changes: 6 additions & 6 deletions py/objfloat.c
Expand Up @@ -137,19 +137,19 @@ 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];
} else {
// something else, try to cast it to a float
return mp_obj_new_float(mp_obj_get_float(args[0]));
}
}
}
}

Expand Down
4 changes: 4 additions & 0 deletions tests/float/float1.py
Expand Up @@ -36,6 +36,10 @@
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))
Expand Down

0 comments on commit a07fc5b

Please sign in to comment.