Skip to content

feat: int mapped to enum #1

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

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
16 changes: 15 additions & 1 deletion src/betterproto/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -904,7 +904,14 @@ def _get_field_default_gen(cls, field: dataclasses.Field) -> Any:
return t
elif issubclass(t, Enum):
# Enums always default to zero.
return int
def default_enum():
try:
# try to create a python enum instance
return t(0)
except ValueError:
return 0 # if that does not work fallback to int

return default_enum
elif t is datetime:
# Offsets are relative to 1970-01-01T00:00:00Z
return datetime_default_gen
Expand All @@ -929,6 +936,13 @@ def _postprocess_single(
elif meta.proto_type == TYPE_BOOL:
# Booleans use a varint encoding, so convert it to true/false.
value = value > 0
elif meta.proto_type == TYPE_ENUM:
# Convert enum ints to python enum instances
cls = self._betterproto.cls_by_field[field_name]
try:
value = cls(value)
except ValueError:
pass # the received value does not exist in the enum so we have to pass it as raw int
elif wire_type in (WIRE_FIXED_32, WIRE_FIXED_64):
fmt = _pack_fmt(meta.proto_type)
value = struct.unpack(fmt, value)[0]
Expand Down