I don't know how or even whether this would be possible ootb. On one side, I do really like the idea; on the other hand, it kind of seems like going down a bumpy road (as you said, datetimes? filepaths?urls?). And the de-serialization would not be easy.

What if we added a function call for the serialization, something like json.dumps(object, method=str) (don't know if that is an option at the moment)

On Wed, Jun 10, 2020 at 9:19 AM J. Pic <jpic@yourlabs.org> wrote:
Hi all,

This is a proposal to enable uuid objects serialization / deserialization by the json module out of the box.

UUID objects cast to string:

>>> example = uuid.uuid4()
>>> str(example)

The can be casted from string:

>>> example == uuid.UUID(str(example))

But are not serializable out of the box:

>>> json.dumps(example)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.8/json/__init__.py", line 231, in dumps
    return _default_encoder.encode(obj)
  File "/usr/lib/python3.8/json/encoder.py", line 199, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "/usr/lib/python3.8/json/encoder.py", line 257, in iterencode
    return _iterencode(o, 0)
  File "/usr/lib/python3.8/json/encoder.py", line 179, in default
    raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type UUID is not JSON serializable

Wouldn't it be pythonically possible to make this work out of the box, without going through the string typecasting ?

If that discussion goes well perhaps we can also talk about datetimes ... I know there's nothing about datetime formats in the json specification, that users are free to choose, but could we choose a standard format by default that would just work for people who don't care about the format they want.

Thank you in advance for your replies

Have a great day


Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-leave@python.org
Message archived at https://mail.python.org/archives/list/python-ideas@python.org/message/W23G6CWWXPCB3L5M2UGGLOEALO5WN4IN/
Code of Conduct: http://python.org/psf/codeofconduct/