Specify Enum loading and dumping? #161
-
Sorry if the title is slightly misleading. Basically wondering if there is a way to do what marshmallow_enum does? Is there a way to specify if one wants to use the enum value for loading/dumping, or the enum type? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
As described in the documentation, apischema (de)serializes enumeration based on the However, it is possible to modify this behavior by registering a conversion. For example, to use 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.serializer(
apischema.conversions.Conversion(
lambda elt: elt.name, source=enum_cls, target=names
)
)
return enum_cls
@as_names
class MyEnum(Enum):
FOO = object()
BAR = object()
assert apischema.deserialize(MyEnum, "FOO") == MyEnum.FOO
assert apischema.serialize(MyEnum, MyEnum.FOO) == "FOO" By the way, this |
Beta Was this translation helpful? Give feedback.
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: