[issue17961] Use enum names as values in enum.Enum() functional API

Barry A. Warsaw report at bugs.python.org
Wed Jun 19 15:54:54 CEST 2013


Barry A. Warsaw added the comment:

On Jun 19, 2013, at 01:48 PM, Nick Coghlan wrote:

>I created issue 18264 after I tried it and found my theoretical concern
>wasn't theoretical at all: swapping a true integer for the current
>incarnation of enum.IntEnum breaks (at least) JSON serialisation, which means
>we can't use it in its current form to replace stdlib constants.

JSON has to be taught how to serialize enums.  Of course, it also has to be
taught how to serialize datetimes, timedeltas, and other common data types.

In Mailman, I use the following subclass of json.JSONEncoder.  Note though
that in my REST API, I always know the class/enum that a string should be
associated with so my deserializer always does the right thing.

class ExtendedEncoder(json.JSONEncoder):
    """An extended JSON encoder which knows about other data types."""

    def default(self, obj):
        if isinstance(obj, datetime):
            return obj.isoformat()
        elif isinstance(obj, timedelta):
            # as_timedelta() does not recognize microseconds, so convert these
            # to floating seconds, but only if there are any seconds.
            if obj.seconds > 0 or obj.microseconds > 0:
                seconds = obj.seconds + obj.microseconds / 1000000.0
                return '{0}d{1}s'.format(obj.days, seconds)
            return '{0}d'.format(obj.days)
        elif isinstance(obj, Enum):
            # It's up to the decoding validator to associate this name with
            # the right Enum class.
            return obj.name
        return json.JSONEncoder.default(self, obj)

----------

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue17961>
_______________________________________


More information about the Python-bugs-list mailing list