New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Serializing computed fields returning enums #9394
Comments
One other observation to note, if I add a static field to the model with the same enum type, the field_serializer on the computed field works. class MyModel(BaseModel):
static_a_or_b: MyEnum | None = None
... The above snippet succeeds. |
Another workaround is to annotate the enum with a WrapSerializer. from enum import Enum
from pydantic import BaseModel, computed_field, WrapSerializer
from typing import Annotated, Any
class MyEnum(Enum):
A = "a"
B = "b"
def serialize_my_enum(value: Any, handler, info) -> str:
partial_result = handler(value, info)
return partial_result.value
MySerializableEnum = Annotated[MyEnum, WrapSerializer(serialize_my_enum)]
class MyModel(BaseModel):
@computed_field
@property
def computed_a_or_b(self) -> MySerializableEnum:
return MyEnum.B
if __name__ == "__main__":
m = MyModel()
assert m.model_dump()['computed_a_or_b'] == "b" |
Thanks for reporting. Adding to our 2.7 issues milestone. Looks similar (at least in terms of the error) to #9319. |
Hmm, looks like this issue has been around for a while (not introduced in 2.7). Moving to the 2.8 milestone - still a priority, but not a rush to get out for 2.7. |
Hey @sydney-runkle I'd like to work on this if it's still available. |
Initial Checks
Description
I am unable to serialize a computed field that returns an enum,
Example Code
The above snippet raises the following error:
Python, Pydantic & OS Version
The text was updated successfully, but these errors were encountered: