Samuel Freilich <sfreil...@google.com> added the comment:
> A modern solution for this is to define a singledispatch function (with > implementations for your custom types) and pass it as the `default` parameter > to the dump functions. Does that work? I thought the default function only got called for non-serializable types. I'm running into the same issue with some code that would like to do round-trip serialization of a datastructure (which doesn't need 100% generality of supported values but would like to deal with the existing structure of types). Dealing with set is easy, for example: def default(obj): # pass to default parameter of json.dumps if isinstance(obj, frozenset): return {'_class': 'set', 'items': list(obj)} ... def object_hook(obj): # pass to object_hook parameter of json.loads if obj.get('_class') == 'set': return set(decoded_dict['items']) ... But you can't do the equivalent thing for tuple, even if you override encode/iterencode. It seems like the JSON module is making performance versus generality tradeoffs, it doesn't make a fresh call to encode/iterencode for every dict key/value for example. Which is fine, but it would be nice if there was a mode that allowed getting custom behavior for every type, taking the performance cost. ---------- nosy: +sfreilich _______________________________________ Python tracker <rep...@bugs.python.org> <https://bugs.python.org/issue12657> _______________________________________ _______________________________________________ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com