Message389995
> 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. |
|
Date |
User |
Action |
Args |
2021-04-01 15:26:19 | sfreilich | set | recipients:
+ sfreilich, barry, rhettinger, ezio.melotti, eric.araujo, daniel.urban, Tom.Brown, nikow, amirouche, serhiy.storchaka, wiz21 |
2021-04-01 15:26:19 | sfreilich | set | messageid: <1617290779.01.0.900578629379.issue12657@roundup.psfhosted.org> |
2021-04-01 15:26:19 | sfreilich | link | issue12657 messages |
2021-04-01 15:26:18 | sfreilich | create | |
|