Skip to content

Commit e04c801

Browse files
InAnYanpre-commit-ci[bot]sobolevn
authored
Add conversion to bool for Maybe (#2178)
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: sobolevn <mail@sobolevn.me>
1 parent 0d9b751 commit e04c801

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

returns/maybe.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -303,6 +303,9 @@ def from_optional(
303303
return _Nothing(inner_value)
304304
return Some(inner_value)
305305

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

307310
@final
308311
class _Nothing(Maybe[Any]):
@@ -378,6 +381,10 @@ def failure(self) -> None:
378381
"""Returns failed value."""
379382
return self._inner_value
380383

384+
def __bool__(self):
385+
"""Returns ``False``."""
386+
return False
387+
381388

382389
@final
383390
class Some(Maybe[_ValueType_co]):
@@ -435,6 +442,15 @@ def failure(self):
435442
"""Raises exception for successful container."""
436443
raise UnwrapFailedError(self)
437444

445+
def __bool__(self):
446+
"""
447+
Returns ``True```.
448+
449+
Any instance of ``Something`` is treated
450+
as ``True``, even ``Something(None)``.
451+
"""
452+
return True
453+
438454

439455
#: Public unit value of protected :class:`~_Nothing` type.
440456
Nothing: Maybe[Never] = _Nothing()
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
from returns.maybe import Nothing, Some
2+
3+
4+
def test_some_is_true() -> None:
5+
"""Ensures that ``Something(...)`` is ``True`` when treated as a boolean."""
6+
assert bool(Some(123))
7+
assert bool(Some('abc'))
8+
9+
10+
def test_nothing_is_false() -> None:
11+
"""Ensures that ``Nothing`` is ``False`` when treated as a boolean."""
12+
assert not bool(Nothing)
13+
14+
15+
def test_some_none_is_true() -> None:
16+
"""
17+
Ensures that ``Something(None)`` is ``True`` when treated as a boolean.
18+
19+
See <https://github.com/dry-python/returns/issues/2177> for the discussion
20+
of this design choice.
21+
"""
22+
assert bool(Some(None))
23+
assert bool(Some(Nothing))

0 commit comments

Comments
 (0)