diff --git a/Doc/library/functions.rst b/Doc/library/functions.rst index f45ab397e93693..71217e4e7059c4 100644 --- a/Doc/library/functions.rst +++ b/Doc/library/functions.rst @@ -778,7 +778,7 @@ are always available. They are listed here in alphabetical order. single: NaN single: Infinity - Return a floating-point number constructed from a number or a string. + Return a floating-point number constructed from a string, number, or bytes-like object, if possible. Examples: @@ -794,12 +794,26 @@ are always available. They are listed here in alphabetical order. 1000000.0 >>> float('-Infinity') -inf + >>> float(b'3.2e2') + 320.0 + >>> float(bytearray(b'-2.5')) + -2.5 + >>> float(memoryview(b'6.7')) + 6.7 + >>> import array + >>> float(array.array('b', [49, 50, 51])) + 123.0 If the argument is a string, it should contain a decimal number, optionally preceded by a sign, and optionally embedded in whitespace. The optional sign may be ``'+'`` or ``'-'``; a ``'+'`` sign has no effect on the value produced. The argument may also be a string representing a NaN (not-a-number), or positive or negative infinity. + + If the argument is a bytes-like object, its contents are parsed as a decimal + string. Therefore, the bytes-like object must contain a valid representation + of a floating-point number, otherwise :exc:`ValueError` is raised. + More precisely, the input must conform to the :token:`~float:floatvalue` production rule in the following grammar, after leading and trailing whitespace characters are removed: diff --git a/Objects/clinic/floatobject.c.h b/Objects/clinic/floatobject.c.h index 8768555c909257..d1e46d43983640 100644 --- a/Objects/clinic/floatobject.c.h +++ b/Objects/clinic/floatobject.c.h @@ -210,7 +210,7 @@ PyDoc_STRVAR(float_new__doc__, "float(x=0, /)\n" "--\n" "\n" -"Convert a string or number to a floating-point number, if possible."); +"Convert a string, number, or bytes-like object to a float, if possible."); static PyObject * float_new_impl(PyTypeObject *type, PyObject *x); @@ -353,4 +353,4 @@ float___format__(PyObject *self, PyObject *arg) exit: return return_value; } -/*[clinic end generated code: output=5d7b0bf9e47ff997 input=a9049054013a1b77]*/ +/*[clinic end generated code: output=de62deb586e0486a input=a9049054013a1b77]*/ diff --git a/Objects/floatobject.c b/Objects/floatobject.c index 17e6a729dcd83f..68e4c3c1dab5b1 100644 --- a/Objects/floatobject.c +++ b/Objects/floatobject.c @@ -1560,12 +1560,12 @@ float.__new__ as float_new x: object(c_default="NULL") = 0 / -Convert a string or number to a floating-point number, if possible. +Convert a string, number, or bytes-like object to a float, if possible. [clinic start generated code]*/ static PyObject * float_new_impl(PyTypeObject *type, PyObject *x) -/*[clinic end generated code: output=ccf1e8dc460ba6ba input=55909f888aa0c8a6]*/ +/*[clinic end generated code: output=ccf1e8dc460ba6ba input=27eb1f7c62226a39]*/ { if (type != &PyFloat_Type) { if (x == NULL) {