Skip to content

Fix is_set for optional proto3 fields #361

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

Merged
merged 6 commits into from
Apr 23, 2022
Merged
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
7 changes: 6 additions & 1 deletion src/betterproto/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -1317,7 +1317,12 @@ def is_set(self, name: str) -> bool:
:class:`bool`
`True` if field has been set, otherwise `False`.
"""
return self.__raw_get(name) is not PLACEHOLDER
default = (
PLACEHOLDER
if not self._betterproto.meta_by_field_name[name].optional
else None
)
return self.__raw_get(name) is not default


def serialized_on_wire(message: Message) -> bool:
Expand Down
12 changes: 12 additions & 0 deletions tests/test_features.py
Original file line number Diff line number Diff line change
Expand Up @@ -517,3 +517,15 @@ class Spam(betterproto.Message):
assert spam == deepcopied
assert spam is not deepcopied
assert spam.baz is not deepcopied.baz


def test_is_set():
@dataclass
class Spam(betterproto.Message):
foo: bool = betterproto.bool_field(1)
bar: Optional[int] = betterproto.int32_field(2, optional=True)

assert not Spam().is_set("foo")
assert not Spam().is_set("bar")
assert Spam(foo=True).is_set("foo")
assert Spam(foo=True, bar=0).is_set("bar")