forked from danielgtaylor/python-betterproto
-
Notifications
You must be signed in to change notification settings - Fork 0
[do not merge] Enum and import fixes (based on v2.0.0b4) #2
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
maximagupov
wants to merge
3
commits into
master
Choose a base branch
from
enum-and-import-fixes
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -315,6 +315,28 @@ def from_string(cls, name: str) -> "Enum": | |
| except KeyError as e: | ||
| raise ValueError(f"Unknown value {name} for enum {cls.__name__}") from e | ||
|
|
||
| @classmethod | ||
| def from_value(cls, value: Union[int, str]) -> "Enum": | ||
| """Return the value which corresponds to the value. | ||
|
|
||
| Parameters | ||
| ----------- | ||
| value: :class:`Union[int, str]` | ||
| The name or value of the enum member to get | ||
|
|
||
| Raises | ||
| ------- | ||
| :exc:`ValueError` | ||
| The member was not found in the Enum. | ||
| """ | ||
| try: | ||
| if isinstance(value, str): | ||
| return cls.from_string(value) | ||
| value = int(value) | ||
| return cls(value) # type: ignore | ||
| except KeyError as e: | ||
| raise ValueError(f"Unknown value {name} for enum {cls.__name__}") from e | ||
|
|
||
|
|
||
| def _pack_fmt(proto_type: str) -> str: | ||
| """Returns a little-endian format string for reading/writing binary.""" | ||
|
|
@@ -845,8 +867,11 @@ def _type_hint(cls, field_name: str) -> Type: | |
|
|
||
| @classmethod | ||
| def _type_hints(cls) -> Dict[str, Type]: | ||
| module = sys.modules[cls.__module__] | ||
| return get_type_hints(cls, module.__dict__, {}) | ||
| global_vars = {} | ||
| for base in inspect.getmro(cls): | ||
| module = inspect.getmodule(base) | ||
| global_vars.update(vars(module)) | ||
| return get_type_hints(cls, global_vars, {}) | ||
|
|
||
| @classmethod | ||
| def _cls_for(cls, field: dataclasses.Field, index: int = 0) -> Type: | ||
|
|
@@ -1133,19 +1158,19 @@ def to_dict( | |
| if isinstance(value, typing.Iterable) and not isinstance( | ||
| value, str | ||
| ): | ||
| output[cased_name] = [enum_class(el).name for el in value] | ||
| output[cased_name] = [enum_class(el).value for el in value] | ||
| else: | ||
| # transparently upgrade single value to repeated | ||
| output[cased_name] = [enum_class(value).name] | ||
| output[cased_name] = [enum_class(value).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] = enum_class(value).value | ||
| else: | ||
| enum_class = field_types[field_name] # noqa | ||
| output[cased_name] = enum_class(value).name | ||
| output[cased_name] = enum_class(value).value | ||
| elif meta.proto_type in (TYPE_FLOAT, TYPE_DOUBLE): | ||
| if field_is_repeated: | ||
| output[cased_name] = [_dump_float(n) for n in value] | ||
|
|
@@ -1226,9 +1251,9 @@ def from_dict(self: T, value: Dict[str, Any]) -> T: | |
| elif meta.proto_type == TYPE_ENUM: | ||
| enum_cls = self._betterproto.cls_by_field[field_name] | ||
| if isinstance(v, list): | ||
| v = [enum_cls.from_string(e) for e in v] | ||
| elif isinstance(v, str): | ||
| v = enum_cls.from_string(v) | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. nice catch! |
||
| v = [enum_cls.from_value(e) for e in v] | ||
| else: | ||
| v = enum_cls.from_value(v) | ||
| elif meta.proto_type in (TYPE_FLOAT, TYPE_DOUBLE): | ||
| if isinstance(value[key], list): | ||
| v = [_parse_float(n) for n in value[key]] | ||
|
|
||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
is the bug that original implementation didn't loop over base classes of the
cls? why loop?not much info in globalns here https://docs.python.org/3/library/typing.html#typing.get_type_hints
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
the problem appears because betterproto generates code that uses type aliases, like:
when we inherit that class, by default python doesn't know anything about
__common__and we need that trickActually that's Andrey's fix from previous PR, I just moved it above new version
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
ah thanks for explaining! nice trick