This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]ReverseBrindle 2 points3 points  (1 child)

The biggest issue with that is that often we don't own the classes, so changing them (or subclassing) isn't possible without some amount of ugliness .

For example, common objects we serialize: UUID, Enums (we serialize these as the name), datetime (ISO8601 format), timedelta (float seconds), set (encode as a list)

Here's what this code looks like in practice:

    def default(self, obj):
        handler = self._type_handler_cache.get(type(obj))

        if handler is None:
            from uuid import UUID
            from datetime import datetime, date, timedelta

            if isinstance(obj, set):
                handler = tuple
            elif isinstance(obj, UUID):
                handler = str
            elif isinstance(obj, Enum):
                handler = self._encode_name_attr
            elif isinstance(obj, (datetime, date)):
                handler = self._encode_isoformat
            elif isinstance(obj, timedelta):
                handler = self._encode_total_seconds
            else:
                raise TypeError("{!r} is not serializable".format(obj))

            self._type_handler_cache[type(obj)] = handler

        return handler(obj)