Skip to content

Specify Enum loading and dumping? #161

Answered by wyfo
CaptainDriftwood asked this question in Q&A
Discussion options

You must be logged in to vote

As described in the documentation, apischema (de)serializes enumeration based on the Enum member value, not the name.

However, it is possible to modify this behavior by registering a conversion. For example, to use Enum names instead of values, you could write the following:

from enum import Enum
from typing import Literal, TypeVar

import apischema

EnumCls = TypeVar("EnumCls", bound=type[Enum])


def as_names(enum_cls: EnumCls) -> EnumCls:
    names = Literal[tuple(elt.name for elt in enum_cls)]  # type: ignore
    apischema.deserializer(
        apischema.conversions.Conversion(
            lambda name: getattr(enum_cls, name), source=names, target=enum_cls
        )
    )
    apischema.

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by CaptainDriftwood
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants