From b31c2fc263bf36265b72c36bd5d2cae898c7684a Mon Sep 17 00:00:00 2001 From: Mark Dickinson Date: Thu, 4 Aug 2022 18:49:00 +0100 Subject: [PATCH 1/2] Fix float(s) error message when s contains only whitespace --- Lib/test/test_float.py | 3 +++ .../2022-08-04-18-46-54.gh-issue-95605.FbpCoG.rst | 2 ++ Objects/floatobject.c | 9 ++++++++- 3 files changed, 13 insertions(+), 1 deletion(-) create mode 100644 Misc/NEWS.d/next/Core and Builtins/2022-08-04-18-46-54.gh-issue-95605.FbpCoG.rst diff --git a/Lib/test/test_float.py b/Lib/test/test_float.py index b5e271abc86a5e..7dbbdebef17558 100644 --- a/Lib/test/test_float.py +++ b/Lib/test/test_float.py @@ -137,6 +137,9 @@ def check(s): check('123\xbd') check(' 123 456 ') check(b' 123 456 ') + # all whitespace (cf. https://github.com/python/cpython/issues/95605) + check(' ') + check('\t \n') # non-ascii digits (error came from non-digit '!') check('\u0663\u0661\u0664!') diff --git a/Misc/NEWS.d/next/Core and Builtins/2022-08-04-18-46-54.gh-issue-95605.FbpCoG.rst b/Misc/NEWS.d/next/Core and Builtins/2022-08-04-18-46-54.gh-issue-95605.FbpCoG.rst new file mode 100644 index 00000000000000..49441c6b3118b4 --- /dev/null +++ b/Misc/NEWS.d/next/Core and Builtins/2022-08-04-18-46-54.gh-issue-95605.FbpCoG.rst @@ -0,0 +1,2 @@ +Fix misleading contents of error message when converting an all-whitespace +string to :class:`float`. diff --git a/Objects/floatobject.c b/Objects/floatobject.c index 4b1b24f2e702a4..c4353572d32d8e 100644 --- a/Objects/floatobject.c +++ b/Objects/floatobject.c @@ -162,11 +162,18 @@ float_from_string_inner(const char *s, Py_ssize_t len, void *obj) double x; const char *end; const char *last = s + len; - /* strip space */ + /* strip leading whitespace */ while (s < last && Py_ISSPACE(*s)) { s++; } + if (s == last) { + PyErr_Format(PyExc_ValueError, + "could not convert string to float: " + "%R", obj); + return NULL; + } + /* strip trailing whitespace */ while (s < last - 1 && Py_ISSPACE(last[-1])) { last--; } From e5175696413dc2fa6c191679bf6666169cb9e693 Mon Sep 17 00:00:00 2001 From: Mark Dickinson Date: Thu, 4 Aug 2022 19:37:36 +0100 Subject: [PATCH 2/2] Add check for empty string --- Lib/test/test_float.py | 1 + 1 file changed, 1 insertion(+) diff --git a/Lib/test/test_float.py b/Lib/test/test_float.py index 7dbbdebef17558..f8350c1e4caa27 100644 --- a/Lib/test/test_float.py +++ b/Lib/test/test_float.py @@ -138,6 +138,7 @@ def check(s): check(' 123 456 ') check(b' 123 456 ') # all whitespace (cf. https://github.com/python/cpython/issues/95605) + check('') check(' ') check('\t \n') pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy