Skip to content
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

Convert inited values to corresponding Enum members #115

Closed
wants to merge 1 commit into from
Closed
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 betterproto/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -256,9 +256,17 @@ class Enum(int, enum.Enum):

@classmethod
def from_string(cls, name: str) -> int:
"""Return the value which corresponds to the string name."""
"""Return the member which corresponds to the string name."""
try:
return cls.__members__[name]
except KeyError as e:
raise ValueError(f"Unknown member {name} for enum {cls.__name__}") from e

@classmethod
def from_value(cls, value: int) -> int:
"""Return the value which corresponds to the integer value."""
try:
return cls._value2member_map_[value]
except KeyError as e:
raise ValueError(f"Unknown value {name} for enum {cls.__name__}") from e

Expand Down Expand Up @@ -694,6 +702,12 @@ 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:
enum: Enum = self._type_hint(field_name)
try:
value = enum.from_value(value)
except ValueError:
pass
elif wire_type in [WIRE_FIXED_32, WIRE_FIXED_64]:
fmt = _pack_fmt(meta.proto_type)
value = struct.unpack(fmt, value)[0]
Expand Down