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(
303
303
return _Nothing (inner_value )
304
304
return Some (inner_value )
305
305
306
+ def __bool__ (self ) -> bool :
307
+ """Convert (or treat) an instance of ``Maybe`` as a boolean."""
308
+
306
309
307
310
@final
308
311
class _Nothing (Maybe [Any ]):
@@ -378,6 +381,10 @@ def failure(self) -> None:
378
381
"""Returns failed value."""
379
382
return self ._inner_value
380
383
384
+ def __bool__ (self ):
385
+ """Returns ``False``."""
386
+ return False
387
+
381
388
382
389
@final
383
390
class Some (Maybe [_ValueType_co ]):
@@ -435,6 +442,15 @@ def failure(self):
435
442
"""Raises exception for successful container."""
436
443
raise UnwrapFailedError (self )
437
444
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
+
438
454
439
455
#: Public unit value of protected :class:`~_Nothing` type.
440
456
Nothing : 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