Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

gh-124835: tomllib.loads: Raise TypeError not AttributeError. Improve message #124587

Merged
merged 4 commits into from
Oct 2, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions Lib/test/test_tomllib/test_error.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,15 @@ def test_invalid_char_quotes(self):
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]
picnixz marked this conversation as resolved.
Show resolved Hide resolved
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__)

Expand Down
7 changes: 6 additions & 1 deletion Lib/tomllib/_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__}'"
picnixz marked this conversation as resolved.
Show resolved Hide resolved
) from None
pos = 0
out = Output(NestedDict(), Flags())
header: Key = ()
Expand Down
Loading