diff --git a/README.md b/README.md index 8677495..a6f617c 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/json5/lib.py b/json5/lib.py index ecf375a..16aa9f7 100644 --- a/json5/lib.py +++ b/json5/lib.py @@ -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' diff --git a/tests/lib_test.py b/tests/lib_test.py index fa85e7e..c3fac89 100644 --- a/tests/lib_test.py +++ b/tests/lib_test.py @@ -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 = ( @@ -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