jcrist / msgspec

A fast serialization and validation library, with builtin support for JSON, MessagePack, YAML, and TOML
https://jcristharif.com/msgspec/
BSD 3-Clause "New" or "Revised" License
2.01k stars 59 forks source link

Support encoding any Enum value type #680

Open nhairs opened 1 month ago

nhairs commented 1 month ago

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:

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 (https://github.com/nhairs/python-json-logger/pull/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