[issue18264] enum.IntEnum is not compatible with JSON serialisation
Ethan Furman
report at bugs.python.org
Thu Jun 20 03:48:06 CEST 2013
Ethan Furman added the comment:
Here's the relevant routine from _json.c:
-----------------------------------------
static PyObject *
encoder_encode_float(PyEncoderObject *s, PyObject *obj)
{
/* Return the JSON representation of a PyFloat */
double i = PyFloat_AS_DOUBLE(obj);
if (!Py_IS_FINITE(i)) {
if (!s->allow_nan) {
PyErr_SetString(PyExc_ValueError, "Out of range float values are not JSON compliant");
return NULL;
}
if (i > 0) {
return PyUnicode_FromString("Infinity");
}
else if (i < 0) {
return PyUnicode_FromString("-Infinity");
}
else {
return PyUnicode_FromString("NaN");
}
}
/* Use a better float format here? */
return PyObject_Repr(obj);
}
Possible solutions
------------------
- Use PyObject_Str() instead of PyObject_Repr()
I was unable to find any references to why it isn't currently PyObject_Str(), but switching over to it did not break any tests
- Coerce the obj to a PyFloat, and take the repr of that (just use the `i`)
float subclasses would always lose the subclass status, but that is lost on deserialization anyway unless a custom decoder is used; and if a custom decoder is being used I would think a custom encoder is also being used?
Summary
-------
Having hybrid Enums not change __str__ would solve most of the json serialization issues;
either of the above two changes will solve the json issue of enumerated floats.
Thoughts on which route to take for json?
----------
_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue18264>
_______________________________________
More information about the Python-bugs-list
mailing list