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

Add prefixed enums in addition to pretty ones #589

Open
wants to merge 10 commits into
base: master
Choose a base branch
from
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
21 changes: 15 additions & 6 deletions src/betterproto/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -1515,24 +1515,30 @@ def to_dict(
else:
output[cased_name] = b64encode(value).decode("utf8")
elif meta.proto_type == TYPE_ENUM:
def name(enum_class, value):
obj = enum_class(value)
if hasattr(obj.__class__, 'full_name') and isinstance(obj.__class__.full_name, property):
return obj.full_name
return obj.name
Comment on lines +1518 to +1522
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
def name(enum_class, value):
obj = enum_class(value)
if hasattr(obj.__class__, 'full_name') and isinstance(obj.__class__.full_name, property):
return obj.full_name
return obj.name
def name(enum_class, value):
obj = enum_class(value)
if hasattr(obj.__class__, 'full_name') and isinstance(obj.__class__.full_name, property):
return obj.full_name
return obj.name

This should probably go in utils or enum.py

if field_is_repeated:
enum_class = field_types[field_name].__args__[0]
if isinstance(value, typing.Iterable) and not isinstance(
value, str
):
output[cased_name] = [enum_class(el).name for el in value]
output[cased_name] = [
name(enum_class, el) for el in value]
else:
# transparently upgrade single value to repeated
output[cased_name] = [enum_class(value).name]
output[cased_name] = [name(enum_class, value)]
elif value is None:
if include_default_values:
output[cased_name] = value
elif meta.optional:
enum_class = field_types[field_name].__args__[0]
output[cased_name] = enum_class(value).name
output[cased_name] = name(enum_class, value)
else:
enum_class = field_types[field_name] # noqa
output[cased_name] = enum_class(value).name
output[cased_name] = name(enum_class, value)
elif meta.proto_type in (TYPE_FLOAT, TYPE_DOUBLE):
if field_is_repeated:
output[cased_name] = [_dump_float(n) for n in value]
Expand Down Expand Up @@ -1592,10 +1598,13 @@ def _from_dict_init(cls, mapping: Mapping[str, Any]) -> Mapping[str, Any]:
)
elif meta.proto_type == TYPE_ENUM:
enum_cls = cls._betterproto.cls_by_field[field_name]

def obj(enum_class, value):
return enum_class.from_full_name(value) if hasattr(enum_class, 'from_full_name') else enum_class.from_string(value)
Comment on lines +1602 to +1603
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
def obj(enum_class, value):
return enum_class.from_full_name(value) if hasattr(enum_class, 'from_full_name') else enum_class.from_string(value)
def obj(enum_class, value):
return enum_class.from_full_name(value) if hasattr(enum_class, 'from_full_name') else enum_class.from_string(value)

Same as previous here

if isinstance(value, list):
value = [enum_cls.from_string(e) for e in value]
value = [obj(enum_cls, e) for e in value]
elif isinstance(value, str):
value = enum_cls.from_string(value)
value = obj(enum_cls, value)
elif meta.proto_type in (TYPE_FLOAT, TYPE_DOUBLE):
value = (
[_parse_float(n) for n in value]
Expand Down
3 changes: 3 additions & 0 deletions src/betterproto/plugin/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@
from betterproto.lib.google.protobuf.compiler import CodeGeneratorRequest

from .. import which_one_of
from ..casing import sanitize_name
from ..compile.importing import (
get_type_reference,
parse_source_type_name,
Expand Down Expand Up @@ -639,6 +640,7 @@ class EnumEntry:
"""Representation of an Enum entry."""

name: str
full_name: str
value: int
comment: str

Expand All @@ -649,6 +651,7 @@ def __post_init__(self) -> None:
name=pythonize_enum_member_name(
entry_proto_value.name, self.proto_obj.name
),
full_name=sanitize_name(entry_proto_value.name),
value=entry_proto_value.number,
comment=get_comment(
proto_file=self.source_file, path=self.path + [2, entry_number]
Expand Down
20 changes: 20 additions & 0 deletions src/betterproto/templates/template.py.j2
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,26 @@ class {{ enum.py_name }}(betterproto.Enum):
return core_schema.int_schema(ge=0)
{% endif %}

@property
def full_name(self):
return {{ enum.py_name }}_full_name_map[self.value]

@classmethod
def from_full_name(cls, full_name):
return cls.from_string({{ enum.py_name }}_full_name_reverse_map[full_name])


{{ enum.py_name }}_full_name_map = {
{% for entry in enum.entries %}
{{ entry.value }}: "{{ entry.full_name }}",
{% endfor %}
}

{{ enum.py_name }}_full_name_reverse_map = {
{% for entry in enum.entries %}
"{{ entry.full_name }}": "{{ entry.name }}",
{% endfor %}
}
{% endfor %}
{% endif %}
{% for message in output_file.messages %}
Expand Down
1 change: 1 addition & 0 deletions tests/inputs/enum/enum.proto
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ package enum;
message Test {
Choice choice = 1;
repeated Choice choices = 2;
ArithmeticOperator op = 3;
}

enum Choice {
Expand Down
50 changes: 50 additions & 0 deletions tests/inputs/enum/test_enum.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
import betterproto
from dataclasses import dataclass

from tests.output_betterproto.enum import (
ArithmeticOperator,
Choice,
Expand Down Expand Up @@ -112,3 +115,50 @@ def test_renamed_enum_members():
"MINUS",
"_0_PREFIXED",
}


def test_enum_full_name():
assert ArithmeticOperator.NONE.full_name == "ARITHMETIC_OPERATOR_NONE"
assert ArithmeticOperator.PLUS.full_name == "ARITHMETIC_OPERATOR_PLUS"
assert ArithmeticOperator._0_PREFIXED.full_name == "ARITHMETIC_OPERATOR_0_PREFIXED"


def test_enum_to_json():
assert Test(op=ArithmeticOperator.NONE).to_json() == '{}'
assert Test(op=ArithmeticOperator.PLUS).to_json(
) == '{"op": "ARITHMETIC_OPERATOR_PLUS"}'
assert Test(op=ArithmeticOperator._0_PREFIXED).to_json(
) == '{"op": "ARITHMETIC_OPERATOR_0_PREFIXED"}'


def test_enum_from_json():
assert Test().from_json('{}').op == ArithmeticOperator.NONE
assert Test().from_json(
'{"op": "ARITHMETIC_OPERATOR_PLUS"}').op == ArithmeticOperator.PLUS
assert Test().from_json(
'{"op": "ARITHMETIC_OPERATOR_0_PREFIXED"}').op == ArithmeticOperator._0_PREFIXED


class EnumCompat(betterproto.Enum):
NONE = 0
PLUS = 1
MINUS = 2


@dataclass(eq=False, repr=False)
class CompatTest(betterproto.Message):
enum: "EnumCompat" = betterproto.enum_field(1)


def test_enum_to_json_backwards_compat():
assert CompatTest(enum=EnumCompat.NONE).to_json() == '{}'
assert CompatTest(enum=EnumCompat.PLUS).to_json(
) == '{"enum": "PLUS"}'
assert CompatTest(enum=EnumCompat.MINUS).to_json(
) == '{"enum": "MINUS"}'


def test_enum_from_json_backwards_compat():
assert CompatTest().from_json('{}').enum == EnumCompat.NONE
assert CompatTest().from_json('{"enum": "PLUS"}').enum == EnumCompat.PLUS
assert CompatTest().from_json('{"enum": "MINUS"}').enum == EnumCompat.MINUS
Loading