]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-124835: `tomllib.loads`: Raise TypeError not AttributeError. Improve message ...
authorTaneli Hukkinen <3275109+hukkin@users.noreply.github.com>
Wed, 2 Oct 2024 02:58:08 +0000 (05:58 +0300)
committerGitHub <noreply@github.com>
Wed, 2 Oct 2024 02:58:08 +0000 (19:58 -0700)
Lib/test/test_tomllib/test_error.py
Lib/tomllib/_parser.py
Misc/NEWS.d/next/Library/2024-10-01-12-43-42.gh-issue-124835.SVyp3K.rst [new file with mode: 0644]

index 72446267f0475995822686b7f2003aa9aa827b6b..d2ef59a29ca350cb4c9654d7fce9aa4416a56bcf 100644 (file)
@@ -39,6 +39,15 @@ class TestError(unittest.TestCase):
             tomllib.loads("v = '\n'")
         self.assertTrue(" '\\n' " in str(exc_info.exception))
 
+    def test_type_error(self):
+        with self.assertRaises(TypeError) as exc_info:
+            tomllib.loads(b"v = 1")  # type: ignore[arg-type]
+        self.assertEqual(str(exc_info.exception), "Expected str object, not 'bytes'")
+
+        with self.assertRaises(TypeError) as exc_info:
+            tomllib.loads(False)  # type: ignore[arg-type]
+        self.assertEqual(str(exc_info.exception), "Expected str object, not 'bool'")
+
     def test_module_name(self):
         self.assertEqual(tomllib.TOMLDecodeError().__module__, tomllib.__name__)
 
index 45ca7a89630f0e255645f34bf9aa7f5db27b6144..5671326646ca5a6a186b1ef5b9dbb012a1a5f82d 100644 (file)
@@ -71,7 +71,12 @@ def loads(s: str, /, *, parse_float: ParseFloat = float) -> dict[str, Any]:  # n
 
     # The spec allows converting "\r\n" to "\n", even in string
     # literals. Let's do so to simplify parsing.
-    src = s.replace("\r\n", "\n")
+    try:
+        src = s.replace("\r\n", "\n")
+    except (AttributeError, TypeError):
+        raise TypeError(
+            f"Expected str object, not '{type(s).__qualname__}'"
+        ) from None
     pos = 0
     out = Output(NestedDict(), Flags())
     header: Key = ()
diff --git a/Misc/NEWS.d/next/Library/2024-10-01-12-43-42.gh-issue-124835.SVyp3K.rst b/Misc/NEWS.d/next/Library/2024-10-01-12-43-42.gh-issue-124835.SVyp3K.rst
new file mode 100644 (file)
index 0000000..09e5a04
--- /dev/null
@@ -0,0 +1,3 @@
+Make :func:`tomllib.loads` raise :exc:`TypeError` not :exc:`AttributeError`
+on bad input types that do not have the ``replace`` attribute. Improve error
+message when :class:`bytes` is received.