Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion src/betterproto/templates/template.py.j2
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,13 @@ class {{ enum.py_name }}(betterproto.Enum):
def __get_pydantic_core_schema__(cls, _source_type, _handler):
from pydantic_core import core_schema

return core_schema.int_schema(ge=0)
# Return the schema for validation and serialization
return core_schema.chain_schema(
[
core_schema.int_schema(ge=0), # Validate as a string first
core_schema.no_info_plain_validator_function(lambda value: cls(value)), # Custom validation
]
)
{% endif %}

{% endfor %}
Expand Down
9 changes: 9 additions & 0 deletions tests/inputs/enum/test_enum.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,10 @@
Choice,
Test,
)
from tests.output_betterproto_pydantic.enum import (
Choice as ChoicePyd,
Test as TestPyd,
)


def test_enum_set_and_get():
Expand Down Expand Up @@ -112,3 +116,8 @@ def test_renamed_enum_members():
"MINUS",
"_0_PREFIXED",
}


def test_pydantic_enum_preserve_type():
test = TestPyd(choice=ChoicePyd.ZERO)
assert isinstance(test.choice, ChoicePyd)