msgspec icon indicating copy to clipboard operation
msgspec copied to clipboard

Struct that contains an Enum property with a metaclass cant be decoded

Open Jonxslays opened this issue 8 months ago • 1 comments
trafficstars

Description

I don't know if this is a bug, or just something that can't be supported. I've reviewed some of the other issues surrounding metaclasses and it seems there isn't a workaround.

This case is a little different though, my classes which inherit from Struct do not define a metaclass - but instead they have a property which is a subclass of Enum with a metaclass.

I put together a minimal reproducible example. Is it possible to support this use case?

from enum import Enum, EnumMeta

import msgspec


class BaseEnumSuccess(Enum):
    ...


class BaseEnumMeta(EnumMeta):
    ...


class BaseEnumFail(Enum, metaclass=BaseEnumMeta):
    ...


class EnumSuccess(BaseEnumSuccess):
    Success = "success"


class EnumFail(BaseEnumFail):
    Success = "success"


class TesterSuccess(msgspec.Struct):
    variant: EnumSuccess


class TesterFail(msgspec.Struct):
    variant: EnumFail


decoder_success = msgspec.json.Decoder(TesterSuccess)
decoded_success = decoder_success.decode(b'{"variant": "success"}')
print(decoded_success)

decoder_fail = msgspec.json.Decoder(TesterFail)
decoded_fail = decoder_fail.decode(b'{"variant": "success"}')
print(decoded_fail)

Output:

TesterSuccess(variant=<EnumSuccess.Success: 'success'>)
Traceback (most recent call last):
  File "/home/jonx/projects/py/example.py", line 39, in <module>
    decoded_fail = decoder_fail.decode(b'{"variant": "success"}')
msgspec.ValidationError: Expected `EnumFail`, got `str` - at `$.variant`

Version info:

----------------------------------------------
Msgspec:     0.19.0
----------------------------------------------
Interpreter: CPython 3.13.1
----------------------------------------------
Compiler:    GCC 14.2.1 20240910
----------------------------------------------
OS/Arch:     Linux 6.6.72-1-lts / x86_64
----------------------------------------------

Thanks in advance for your time, love the library - it massively improved performance for me.

Jonxslays avatar Mar 07 '25 02:03 Jonxslays