Skip to content

Commit 9ce9020

Browse files
authored
gh-124835: tomllib.loads: Raise TypeError not AttributeError. Improve message (#124587)
1 parent 120729d commit 9ce9020

File tree

3 files changed

+18
-1
lines changed

3 files changed

+18
-1
lines changed

Lib/test/test_tomllib/test_error.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,15 @@ def test_invalid_char_quotes(self):
3939
tomllib.loads("v = '\n'")
4040
self.assertTrue(" '\\n' " in str(exc_info.exception))
4141

42+
def test_type_error(self):
43+
with self.assertRaises(TypeError) as exc_info:
44+
tomllib.loads(b"v = 1") # type: ignore[arg-type]
45+
self.assertEqual(str(exc_info.exception), "Expected str object, not 'bytes'")
46+
47+
with self.assertRaises(TypeError) as exc_info:
48+
tomllib.loads(False) # type: ignore[arg-type]
49+
self.assertEqual(str(exc_info.exception), "Expected str object, not 'bool'")
50+
4251
def test_module_name(self):
4352
self.assertEqual(tomllib.TOMLDecodeError().__module__, tomllib.__name__)
4453

Lib/tomllib/_parser.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,12 @@ def loads(s: str, /, *, parse_float: ParseFloat = float) -> dict[str, Any]: # n
7171

7272
# The spec allows converting "\r\n" to "\n", even in string
7373
# literals. Let's do so to simplify parsing.
74-
src = s.replace("\r\n", "\n")
74+
try:
75+
src = s.replace("\r\n", "\n")
76+
except (AttributeError, TypeError):
77+
raise TypeError(
78+
f"Expected str object, not '{type(s).__qualname__}'"
79+
) from None
7580
pos = 0
7681
out = Output(NestedDict(), Flags())
7782
header: Key = ()
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Make :func:`tomllib.loads` raise :exc:`TypeError` not :exc:`AttributeError`
2+
on bad input types that do not have the ``replace`` attribute. Improve error
3+
message when :class:`bytes` is received.

0 commit comments

Comments
 (0)