Skip to content

Commit 4e245a4

Browse files
authored
tomli.loads: Raise TypeError not AttributeError. Improve message (#229)
1 parent facdab0 commit 4e245a4

2 files changed

Lines changed: 15 additions & 1 deletion

File tree

src/tomli/_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]: # no
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 = ()

tests/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

0 commit comments

Comments
 (0)