Skip to content

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

@Jonxslays

Description

@Jonxslays

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.

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