Skip to content

Commit

Permalink
simplify bool vs int type checking
Browse files Browse the repository at this point in the history
  • Loading branch information
wbolster committed Dec 6, 2021
1 parent cbf5c40 commit 4775ba5
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 3 deletions.
5 changes: 3 additions & 2 deletions jsonlines/jsonlines.py
Original file line number Diff line number Diff line change
Expand Up @@ -319,8 +319,9 @@ def read(

if type is not None:
valid = isinstance(value, type)
if type is int: # bool is a subclass of int
valid = valid and not isinstance(value, bool)
if type is int and isinstance(value, bool):
# isinstance() is not sufficient, since bool is an int subclass
valid = False
if not valid:
raise InvalidLineError(
"line does not match requested type", line, lineno
Expand Down
9 changes: 8 additions & 1 deletion tests/test_jsonlines.py
Original file line number Diff line number Diff line change
Expand Up @@ -166,8 +166,15 @@ def test_empty_lines() -> None:


def test_typed_reads() -> None:
with jsonlines.Reader(io.StringIO('12\n"foo"\n')) as reader:
with jsonlines.Reader(io.StringIO('12\ntrue\n"foo"\n')) as reader:
assert reader.read(type=int) == 12

with pytest.raises(jsonlines.InvalidLineError) as excinfo:
reader.read(type=int)
exc = excinfo.value
assert "does not match requested type" in str(exc)
assert exc.line == 'true'

with pytest.raises(jsonlines.InvalidLineError) as excinfo:
reader.read(type=float)
exc = excinfo.value
Expand Down

0 comments on commit 4775ba5

Please sign in to comment.