Skip to content

Add conversion to bool for Maybe #2178

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 9 commits into from
Jun 27, 2025
16 changes: 16 additions & 0 deletions returns/maybe.py
Original file line number Diff line number Diff line change
Expand Up @@ -303,6 +303,9 @@ def from_optional(
return _Nothing(inner_value)
return Some(inner_value)

def __bool__(self) -> bool:
"""Convert (or treat) an instance of ``Maybe`` as a boolean."""


@final
class _Nothing(Maybe[Any]):
Expand Down Expand Up @@ -378,6 +381,10 @@ def failure(self) -> None:
"""Returns failed value."""
return self._inner_value

def __bool__(self):
"""Returns ``False``."""
return False


@final
class Some(Maybe[_ValueType_co]):
Expand Down Expand Up @@ -435,6 +442,15 @@ def failure(self):
"""Raises exception for successful container."""
raise UnwrapFailedError(self)

def __bool__(self):
"""
Returns ``True```.

Any instance of ``Something`` is treated
as ``True``, even ``Something(None)``.
"""
return True


#: Public unit value of protected :class:`~_Nothing` type.
Nothing: Maybe[Never] = _Nothing()
Expand Down
23 changes: 23 additions & 0 deletions tests/test_maybe/test_maybe_conversions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
from returns.maybe import Nothing, Some


def test_some_is_true() -> None:
"""Ensures that ``Something(...)`` is ``True`` when treated as a boolean."""
assert bool(Some(123))
assert bool(Some('abc'))


def test_nothing_is_false() -> None:
"""Ensures that ``Nothing`` is ``False`` when treated as a boolean."""
assert not bool(Nothing)


def test_some_none_is_true() -> None:
"""
Ensures that ``Something(None)`` is ``True`` when treated as a boolean.

See <https://github.com/dry-python/returns/issues/2177> for the discussion
of this design choice.
"""
assert bool(Some(None))
assert bool(Some(Nothing))