Commit e6239a3a authored by Mark Dickinson's avatar Mark Dickinson

Issue #27934: Use float.__repr__ instead of plain repr when JSON-encoding an...

Issue #27934: Use float.__repr__ instead of plain repr when JSON-encoding an instance of a float subclass. Thanks Eddie James.
parent 0ca4b6f5
...@@ -28,7 +28,7 @@ for i in range(0x20): ...@@ -28,7 +28,7 @@ for i in range(0x20):
#ESCAPE_DCT.setdefault(chr(i), '\\u%04x' % (i,)) #ESCAPE_DCT.setdefault(chr(i), '\\u%04x' % (i,))
INFINITY = float('inf') INFINITY = float('inf')
FLOAT_REPR = repr FLOAT_REPR = float.__repr__
def encode_basestring(s): def encode_basestring(s):
"""Return a JSON representation of a Python string """Return a JSON representation of a Python string
......
...@@ -32,6 +32,17 @@ class TestFloat(object): ...@@ -32,6 +32,17 @@ class TestFloat(object):
self.assertNotEqual(res[0], res[0]) self.assertNotEqual(res[0], res[0])
self.assertRaises(ValueError, self.dumps, [val], allow_nan=False) 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 TestPyFloat(TestFloat, PyTest): pass
class TestCFloat(TestFloat, CTest): pass class TestCFloat(TestFloat, CTest): pass
...@@ -636,6 +636,7 @@ Manuel Jacob ...@@ -636,6 +636,7 @@ Manuel Jacob
David Jacobs David Jacobs
Kevin Jacobs Kevin Jacobs
Kjetil Jacobsen Kjetil Jacobsen
Eddie James
Bertrand Janin Bertrand Janin
Geert Jansen Geert Jansen
Jack Jansen Jack Jansen
......
...@@ -36,6 +36,9 @@ Core and Builtins ...@@ -36,6 +36,9 @@ Core and Builtins
Library 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 - Issue #27861: Fixed a crash in sqlite3.Connection.cursor() when a factory
creates not a cursor. Patch by Xiang Zhang. creates not a cursor. Patch by Xiang Zhang.
......
...@@ -1960,8 +1960,8 @@ encoder_encode_float(PyEncoderObject *s, PyObject *obj) ...@@ -1960,8 +1960,8 @@ encoder_encode_float(PyEncoderObject *s, PyObject *obj)
return PyString_FromString("NaN"); return PyString_FromString("NaN");
} }
} }
/* Use a better float format here? */ /* Make sure to use the base float class repr method */
return PyObject_Repr(obj); return PyFloat_Type.tp_repr(obj);
} }
static PyObject * static PyObject *
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment