Issue #27934: Use float.__repr__ instead of plain repr when JSON-encoding an instance of a float subclass. Thanks Eddie James.
diff --git a/Lib/json/encoder.py b/Lib/json/encoder.py
index f5eeed7..97ffe8e 100644
--- a/Lib/json/encoder.py
+++ b/Lib/json/encoder.py
@@ -28,7 +28,7 @@
#ESCAPE_DCT.setdefault(chr(i), '\\u%04x' % (i,))
INFINITY = float('inf')
-FLOAT_REPR = repr
+FLOAT_REPR = float.__repr__
def encode_basestring(s):
"""Return a JSON representation of a Python string
diff --git a/Lib/json/tests/test_float.py b/Lib/json/tests/test_float.py
index 049f9ae..c10381d 100644
--- a/Lib/json/tests/test_float.py
+++ b/Lib/json/tests/test_float.py
@@ -32,6 +32,17 @@
self.assertNotEqual(res[0], res[0])
self.assertRaises(ValueError, self.dumps, [val], allow_nan=False)
+ def test_float_subclasses_use_float_repr(self):
+ # Issue 27934.
+ class PeculiarFloat(float):
+ def __repr__(self):
+ return "I'm not valid JSON"
+ def __str__(self):
+ return "Neither am I"
+
+ val = PeculiarFloat(3.2)
+ self.assertEqual(self.loads(self.dumps(val)), val)
+
class TestPyFloat(TestFloat, PyTest): pass
class TestCFloat(TestFloat, CTest): pass