ijl / orjson

Fast, correct Python JSON library supporting dataclasses, datetimes, and numpy
Apache License 2.0
6.29k stars 215 forks source link

BUG: unable to use default to serialize enums #529

Closed rteqs closed 3 weeks ago

rteqs commented 3 weeks ago

version: 3.10.10

I'm trying to override the default serialization of enums to use its name instead of val. However, it's calling the default encoder at all.

Additionally, the following snippet from the readme returns the incorrect result.

class Custom:
    def __init__(self, val):
        self.val = val

def default(obj):
    if isinstance(obj, Custom):
        return obj.val
    raise TypeError

class CustomEnum(Enum):
    ONE = Custom(1)

>>> print(orjson.dumps(CustomEnum.ONE, default=default))
b'null'

The correct result should be b'1' per the readme

ijl commented 3 weeks ago

This functionality was added four years ago and the exact case has been tested since in test_enum.py. I run this now and get:

Python 3.11.10 (main, Sep  9 2024, 00:00:00) [GCC 14.2.1 20240905 (Red Hat 14.2.1-2)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from enum import Enum
>>> import orjson
>>> class Custom:
...     def __init__(self, val):
...         self.val = val
...
>>> def default(obj):
...     if isinstance(obj, Custom):
...         return obj.val
...     raise TypeError
...
>>> class CustomEnum(Enum):
...     ONE = Custom(1)
...
>>> print(orjson.dumps(CustomEnum.ONE, default=default))
b'1'

This is so odd you would need to engage with the tests and what package you have installed from where and so on to be worth looking at this more.