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

Raise a friendly TypeError for wrong file mode #175

Merged
merged 4 commits into from
Jan 30, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
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
8 changes: 7 additions & 1 deletion src/tomli/_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,13 @@ class TOMLDecodeError(ValueError):

def load(__fp: BinaryIO, *, parse_float: ParseFloat = float) -> dict[str, Any]:
"""Parse TOML from a binary file object."""
s = __fp.read().decode()
b = __fp.read()
try:
s = b.decode()
except AttributeError:
raise TypeError(
"File must be opened in binary mode, e.g. use `open('foo.toml', 'rb')`"
) from None
return loads(s, parse_float=parse_float)


Expand Down
10 changes: 10 additions & 0 deletions tests/test_misc.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,16 @@ def test_load(self):
actual = tomllib.load(bin_f)
self.assertEqual(actual, expected)

def test_incorrect_load(self):
content = "one=1"
with tempfile.TemporaryDirectory() as tmp_dir_path:
file_path = Path(tmp_dir_path) / "test.toml"
file_path.write_text(content)

with open(file_path, "r") as txt_f:
with self.assertRaises(TypeError):
tomllib.load(txt_f) # type: ignore[arg-type]

def test_parse_float(self):
doc = """
val=0.1
Expand Down