diff options
| author | Mark Dickinson <dickinsm@gmail.com> | 2016-09-03 16:45:00 (GMT) |
|---|---|---|
| committer | Mark Dickinson <dickinsm@gmail.com> | 2016-09-03 16:45:00 (GMT) |
| commit | e6239a3ab3e009a1b15918c1b8182290bb8a2e91 (patch) | |
| tree | 0087bebcd0f62e86f755dfade4326f54845b87d2 | |
| parent | 0ca4b6f5a62ecf75f80a2d8497b30464acfb205e (diff) | |
| download | cpython-e6239a3ab3e009a1b15918c1b8182290bb8a2e91.zip cpython-e6239a3ab3e009a1b15918c1b8182290bb8a2e91.tar.gz cpython-e6239a3ab3e009a1b15918c1b8182290bb8a2e91.tar.bz2 | |
Issue #27934: Use float.__repr__ instead of plain repr when JSON-encoding an instance of a float subclass. Thanks Eddie James.
| -rw-r--r-- | Lib/json/encoder.py | 2 | ||||
| -rw-r--r-- | Lib/json/tests/test_float.py | 11 | ||||
| -rw-r--r-- | Misc/ACKS | 1 | ||||
| -rw-r--r-- | Misc/NEWS | 3 | ||||
| -rw-r--r-- | Modules/_json.c | 4 |
5 files changed, 18 insertions, 3 deletions
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 @@ for i in range(0x20): #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 @@ class TestFloat(object): 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 @@ -636,6 +636,7 @@ Manuel Jacob David Jacobs Kevin Jacobs Kjetil Jacobsen +Eddie James Bertrand Janin Geert Jansen Jack Jansen @@ -36,6 +36,9 @@ Core and Builtins Library ------- +- Issue #27934: Use ``float.__repr__`` instead of plain ``repr`` when JSON- + encoding an instance of a float subclass. Thanks Eddie James. + - Issue #27861: Fixed a crash in sqlite3.Connection.cursor() when a factory creates not a cursor. Patch by Xiang Zhang. diff --git a/Modules/_json.c b/Modules/_json.c index c301546..2d66083 100644 --- a/Modules/_json.c +++ b/Modules/_json.c @@ -1960,8 +1960,8 @@ encoder_encode_float(PyEncoderObject *s, PyObject *obj) return PyString_FromString("NaN"); } } - /* Use a better float format here? */ - return PyObject_Repr(obj); + /* Make sure to use the base float class repr method */ + return PyFloat_Type.tp_repr(obj); } static PyObject * |
