Skip to content
Open
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
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -269,6 +269,8 @@ to activate it.
## Version History / Release Notes:

* Unreleased
* Encode float subclasses using their underlying values without calling
custom equality or float conversion methods.
* Preserve duck-typed mapping contents without testing their truth value.
* Preserve duck-typed array contents without testing their truth value.
* Honor explicit false-valued callable parsing hooks and default encoders
Expand Down
3 changes: 3 additions & 0 deletions json5/lib.py
Original file line number Diff line number Diff line change
Expand Up @@ -751,6 +751,9 @@ def _encode_int(self, obj: int, *, as_key: bool) -> str:
return f'"{s}"' if as_key else s

def _encode_float(self, obj: float, *, as_key: bool) -> str:
# Inspect the underlying value without invoking subclass overrides,
# matching the json module and our use of float.__repr__ below.
obj = float.__float__(obj)
if obj == float('inf'):
allowed = self.allow_nan
s = 'Infinity'
Expand Down
40 changes: 40 additions & 0 deletions tests/lib_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,20 @@ def __bool__(self):
) # pragma: no cover


class NoCompareFloat(float):
__hash__ = float.__hash__

def __eq__(self, other):
raise AssertionError(
'Float equality must not be called'
) # pragma: no cover

def __float__(self):
raise AssertionError(
'Float conversion must not be called'
) # pragma: no cover


class TestOptionalHooks(unittest.TestCase):
def test_decoding_hooks(self):
cases = (
Expand Down Expand Up @@ -855,6 +869,32 @@ def __repr__(other): # pragma: no cover

self.assertEqual(json5.dumps(MyFloat(0.5)), '0.5')

def test_custom_float_finite(self):
for number in (1.5, -0.0):
value = NoCompareFloat(number)
for obj in (value, {value: 'value'}):
with self.subTest(number=number, obj_type=type(obj)):
self.assertEqual(
json5.dumps(obj, allow_nan=False),
json.dumps(obj, allow_nan=False),
)

def test_custom_float_nonfinite(self):
for number, expected in (
(float('inf'), 'Infinity'),
(float('-inf'), '-Infinity'),
(float('nan'), 'NaN'),
):
value = NoCompareFloat(number)
for obj, text in (
(value, expected),
({value: 'value'}, '{"' + expected + '": "value"}'),
):
with self.subTest(number=number, obj_type=type(obj)):
self.assertEqual(json5.dumps(obj), text)
with self.assertRaises(ValueError):
json5.dumps(obj, allow_nan=False)

def test_custom_objects(self):
class MyDict:
def __iter__(self): # pragma: no cover
Expand Down