Skip to content

Support encoding any Enum value type #680

@nhairs

Description

@nhairs

Description

Currently msgspec only supports encoding Enum values that strings or integers, throwing msgspec.EncodeError: Only enums with int or str values are supported when attempting to encode anything else.

As far as I can tell this affects the following encoders:

  • msgpack (have not tested, only from reading source code)
  • json (have tested)

It feels like any value supported by the encoder should be encoded rather than just these two specific types.

Alternatively, in the case of the JSON encoder (I haven't checked the other encoders), it should be possible to use the enc_hook to handle the other types. Currently this is not possible as the error is thrown before the enc_hook is called.

The specific use case that I'm hitting this on is in adding support for the msgspec encoder to python-json-logger (nhairs/python-json-logger#12)

>>> import msgspec.json
>>> e = msgspec.json.Encoder()
>>> import enum
>>> class SomeEnum(enum.Enum):
...  NULL = None
... 
>>> e.encode(SomeEnum.NULL)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
msgspec.EncodeError: Only enums with int or str values are supported

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions