Skip to content

Return actual enum's from to_dict #316

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
tcamise-gpsw opened this issue Jan 12, 2022 · 3 comments
Open

Return actual enum's from to_dict #316

tcamise-gpsw opened this issue Jan 12, 2022 · 3 comments

Comments

@tcamise-gpsw
Copy link

Perhaps I don't understand the intended use of the to_dict method but, at least for my use case, I would prefer it to return the actual enum instead of it's name as a string.

For example:

class EnumResultGeneric(betterproto.Enum):
    RESULT_UNKNOWN = 0
    RESULT_SUCCESS = 1

@dataclass
class ResponseGeneric(betterproto.Message):
    result: "EnumResultGeneric" = betterproto.enum_field(1)


status = ResponseGeneric.FromString(bytes(bytearray([0x08, 0x01]))).to_dict()['result']
print(f"{status}: {type(status)}")

gives RESULT_SUCCESS: <class 'str'> instead of the actual EnumResultGeneric.

It is a simple change to get this desired behavior in the to_dict method:

    elif meta.proto_type == TYPE_ENUM:
        enum_values = list(
            self._betterproto.cls_by_field[field.name]
        )  # type: ignore
        if isinstance(v, list):
            output[cased_name] = [enum_values[e] for e in v]
        else:
            output[cased_name] = enum_values[v]

Is this desirable for other people? Maybe allow this as a parameter to to_dict?

@Gobot1234
Copy link
Collaborator

Maybe take a look at #203

@tcamise-gpsw
Copy link
Author

I just found #293. which sounds quite similar Maybe this is the same?

@tcamise-gpsw
Copy link
Author

Maybe take a look at #203

Thanks, that does look promising. I'll test it out and see if I can revive it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants