[Python-checkins] bpo-28146: Fix a confusing error message in str.format() (GH-24213)

miss-islington webhook-mailer at python.org
Thu May 13 16:56:03 EDT 2021


https://github.com/python/cpython/commit/4aeee0b47b3a2b604bbac37040320ffc88c291f2
commit: 4aeee0b47b3a2b604bbac37040320ffc88c291f2
branch: main
author: Irit Katriel <iritkatriel at yahoo.com>
committer: miss-islington <31488909+miss-islington at users.noreply.github.com>
date: 2021-05-13T13:55:55-07:00
summary:

bpo-28146: Fix a confusing error message in str.format() (GH-24213)



Automerge-Triggered-By: GH:pitrou

files:
A Misc/NEWS.d/next/Core and Builtins/2021-01-13-19-34-41.bpo-28146.AZBBkH.rst
M Lib/test/test_unicode.py
M Python/formatter_unicode.c

diff --git a/Lib/test/test_unicode.py b/Lib/test/test_unicode.py
index 6f5d40f84bd07..ffe3e82804ea9 100644
--- a/Lib/test/test_unicode.py
+++ b/Lib/test/test_unicode.py
@@ -1231,8 +1231,11 @@ def __repr__(self):
                           0, 1, 2, 3, 4, 5, 6, 7)
 
         # string format spec errors
-        self.assertRaises(ValueError, "{0:-s}".format, '')
-        self.assertRaises(ValueError, format, "", "-")
+        sign_msg = "Sign not allowed in string format specifier"
+        self.assertRaisesRegex(ValueError, sign_msg, "{0:-s}".format, '')
+        self.assertRaisesRegex(ValueError, sign_msg, format, "", "-")
+        space_msg = "Space not allowed in string format specifier"
+        self.assertRaisesRegex(ValueError, space_msg, "{: }".format, '')
         self.assertRaises(ValueError, "{0:=s}".format, '')
 
         # Alternate formatting is not supported
diff --git a/Misc/NEWS.d/next/Core and Builtins/2021-01-13-19-34-41.bpo-28146.AZBBkH.rst b/Misc/NEWS.d/next/Core and Builtins/2021-01-13-19-34-41.bpo-28146.AZBBkH.rst
new file mode 100644
index 0000000000000..e619881938953
--- /dev/null
+++ b/Misc/NEWS.d/next/Core and Builtins/2021-01-13-19-34-41.bpo-28146.AZBBkH.rst	
@@ -0,0 +1 @@
+Fix a confusing error message in :func:`str.format`.
diff --git a/Python/formatter_unicode.c b/Python/formatter_unicode.c
index 5ccf9d303e34e..7b5a7bd04eb3a 100644
--- a/Python/formatter_unicode.c
+++ b/Python/formatter_unicode.c
@@ -773,8 +773,14 @@ format_string_internal(PyObject *value, const InternalFormatSpec *format,
 
     /* sign is not allowed on strings */
     if (format->sign != '\0') {
-        PyErr_SetString(PyExc_ValueError,
-                        "Sign not allowed in string format specifier");
+        if (format->sign == ' ') {
+            PyErr_SetString(PyExc_ValueError,
+                "Space not allowed in string format specifier");
+        }
+        else {
+            PyErr_SetString(PyExc_ValueError,
+                "Sign not allowed in string format specifier");
+        }
         goto done;
     }
 



More information about the Python-checkins mailing list