Skip to content

Implement Message.__bool__ #142

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 13 commits into from
Nov 24, 2020
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
2 changes: 1 addition & 1 deletion docs/api.rst
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ Message

.. autoclass:: betterproto.Message
:members:
:special-members: __bytes__
:special-members: __bytes__, __bool__


.. autofunction:: betterproto.serialized_on_wire
Expand Down
12 changes: 12 additions & 0 deletions src/betterproto/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -516,6 +516,10 @@ class Message(ABC):
.. describe:: bytes(x)

Calls :meth:`__bytes__`.

.. describe:: bool(x)

Calls :meth:`__bool__`.
"""

_serialized_on_wire: bool
Expand Down Expand Up @@ -606,6 +610,14 @@ def __setattr__(self, attr: str, value: Any) -> None:

super().__setattr__(attr, value)

def __bool__(self) -> bool:
"""True if the Message has any fields with non-default values."""
return any(
self.__raw_get(field_name)
not in (PLACEHOLDER, self._get_field_default(field_name))
for field_name in self._betterproto.meta_by_field_name
)

@property
def _betterproto(self) -> ProtoClassMetadata:
"""
Expand Down
30 changes: 30 additions & 0 deletions tests/test_features.py
Original file line number Diff line number Diff line change
Expand Up @@ -365,3 +365,33 @@ def test_message_repr():

assert repr(Test(name="Loki")) == "Test(name='Loki')"
assert repr(Test(child=Test(), name="Loki")) == "Test(name='Loki', child=Test())"


def test_bool():
"""Messages should evaluate similarly to a collection
>>> test = []
>>> bool(test)
... False
>>> test.append(1)
>>> bool(test)
... True
>>> del test[0]
>>> bool(test)
... False
"""

@dataclass
class Falsy(betterproto.Message):
pass

@dataclass
class Truthy(betterproto.Message):
bar: int = betterproto.int32_field(1)

assert not Falsy()
t = Truthy()
assert not t
t.bar = 1
assert t
t.bar = 0
assert not t