[Python-checkins] cpython (2.7): Issue #27934: Use float.__repr__ instead of plain repr when JSON-encoding an
mark.dickinson
python-checkins at python.org
Sat Sep 3 12:45:12 EDT 2016
https://hg.python.org/cpython/rev/86d66a627b77
changeset: 103024:86d66a627b77
branch: 2.7
parent: 102986:e065aec0e6fa
user: Mark Dickinson <dickinsm at gmail.com>
date: Sat Sep 03 17:45:00 2016 +0100
summary:
Issue #27934: Use float.__repr__ instead of plain repr when JSON-encoding an instance of a float subclass. Thanks Eddie James.
files:
Lib/json/encoder.py | 2 +-
Lib/json/tests/test_float.py | 11 +++++++++++
Misc/ACKS | 1 +
Misc/NEWS | 3 +++
Modules/_json.c | 4 ++--
5 files changed, 18 insertions(+), 3 deletions(-)
diff --git a/Lib/json/encoder.py b/Lib/json/encoder.py
--- 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
--- 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
diff --git a/Misc/ACKS b/Misc/ACKS
--- a/Misc/ACKS
+++ b/Misc/ACKS
@@ -636,6 +636,7 @@
David Jacobs
Kevin Jacobs
Kjetil Jacobsen
+Eddie James
Bertrand Janin
Geert Jansen
Jack Jansen
diff --git a/Misc/NEWS b/Misc/NEWS
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -36,6 +36,9 @@
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
--- a/Modules/_json.c
+++ b/Modules/_json.c
@@ -1960,8 +1960,8 @@
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 *
--
Repository URL: https://hg.python.org/cpython
More information about the Python-checkins
mailing list