[issue12657] Cannot override JSON encoding of basic type subclasses

Stefan Champailler report at bugs.python.org
Tue Dec 2 11:03:19 CET 2014


Stefan Champailler added the comment:

I'm adding a scenario for this problem, a real life one, so it gives a bit more substance.

I use SQLALchemy. I do queries with it which returns KeyedTuples (an SQLALchemy type). KeyedTuples inherits from tuple. KeyedTuples are, in principle, like NamedTuple. I want to transmit the result of my queries over json. Since KeyedTuple inherit from tuple, json can't serialize them. Of course one might say that that problem is outside the scope of json. But if so, it means we have to first convert KeyedTuples to dict and then pass the dict to json. That's alot of copies to do... This problem is rather big because it affects my whole API (close to a hundred of functions)...

I've looked into the code and as noted above, one could replace 'isinstance(x,tuple)' with 'type(x) == tuple'. But without knowledge of how many people use the flexibility introduced by isinstance, it's dangerous. We could also change the nature of default and say that default is called before any type checking in json (so default is not a 'default' anymore). We could also duplicate the default functionnality (so a function called before any type checks and then a default called if all type checks fail). But for these two last cases, I guess the difficulty is : how do we know the pre-type 'default' was applied correctly ?

Patching is not easy because, at least in my case, the C code path is taken => an easy patch (i.e. full python) would force me out of the C path which may be bad for performance (I didn't measure the difference between the 2 paths).

I see this bug is old and not much commented, should we conclude that nobody cares ? That'd a good news since it'd mean a patch wouldn't hurt many people :-)

----------
nosy: +wiz21
versions: +Python 3.4

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue12657>
_______________________________________


More information about the Python-bugs-list mailing list