This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author sfreilich
Recipients Tom.Brown, amirouche, barry, daniel.urban, eric.araujo, ezio.melotti, nikow, rhettinger, serhiy.storchaka, sfreilich, wiz21
Date 2021-04-01.15:26:18
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1617290779.01.0.900578629379.issue12657@roundup.psfhosted.org>
In-reply-to
Content
> 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.
History
Date User Action Args
2021-04-01 15:26:19sfreilichsetrecipients: + sfreilich, barry, rhettinger, ezio.melotti, eric.araujo, daniel.urban, Tom.Brown, nikow, amirouche, serhiy.storchaka, wiz21
2021-04-01 15:26:19sfreilichsetmessageid: <1617290779.01.0.900578629379.issue12657@roundup.psfhosted.org>
2021-04-01 15:26:19sfreilichlinkissue12657 messages
2021-04-01 15:26:18sfreilichcreate