File tree Expand file tree Collapse file tree 2 files changed +39
-0
lines changed
Expand file tree Collapse file tree 2 files changed +39
-0
lines changed Original file line number Diff line number Diff 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
308311class _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
383390class 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.
440456Nothing : Maybe [Never ] = _Nothing ()
Original file line number Diff line number Diff line change 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 ))
You can’t perform that action at this time.
0 commit comments