Or, there might be a way to get the best of both worlds. Consider this
silly example:

    encoded = yourobject.__jsondump__()
    # this should work
    yourobject == YourClass.__jsonload__(encoded)

Basically very similar to __getstate__ and __setstate__ with pickle, with
the following limitations:

- these functions are limited to json types, which are rudimentary on one
hand but on the other it really seems like their current standard is here
to stay
- dict, list, set and other types that may contain different types would
not be able to do any type conversion, encoding list(UUID()) does not make
it possible to get the UUID type back in the decoded list object, unless
you implement your list subclass for example then it's up to you as a user

But with this limitations come the following advantages:

- you still have full control of deserialization logic in your own classes,
- it's easier than implementing an object_hook function because you don't
have to code a type detection logic: the class __jsonload__ should know
what type to apply on what attribute,
- serialization becomes easy to safen, good for users who don't care /
don't need anything particularly sophisticated - for which the current
hooks work,
- json is a popular format, PostgreSQL's JSON field is not the only really
enjoyable thing we can do with json,

Here's a simple example to illustrate:

from uuid import UUID, uuid4


class YourClass:
    def __init__(self, uuid=None):
        self.uuid = uuid or uuid4()

    def __jsondump__(self):
        return dict(uuid=str(self.uuid))
        # if uuid has __jsondump__, then this would be possible too:
        # return dict(uuid=self.uuid.__jsondump__())
        #
        # if the encoder would call __jsondump__ automatically, then this
would
        # be enough:
        # return dict(uuid=self.uuid)

    @classmethod
    def __jsonload__(cls, data):
        return cls(UUID(data['uuid']))

    def __eq__(self, other):
        if isinstance(other, type(self)):
            return other.uuid == self.uuid
        return super().__eq__(other)


obj = YourClass()
encoded = obj.__jsondump__()
decoded = YourClass.__jsonload__(encoded)
assert obj == decoded

I'll try that in PyPi then (just have to monkey patch the stdlib objects),
if I find material to prove that it's worth the maintenance cost then I'll
come back with more.

Thank you very much for sharing some of your insight

Have a great day <3
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/ZHDEURKXYMXPKSNY722MN3WK7AQZZZ7C/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to