Skip to content

Commit acf7768

Browse files
Filter for maybe
1 parent 5ba3d4c commit acf7768

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

returns/maybe.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -139,6 +139,20 @@ def bind_optional(
139139
140140
"""
141141

142+
def filter(self,
143+
function: Callable[[_ValueType], bool],
144+
) -> 'Maybe[_ValueType]':
145+
"""
146+
Apply a predicate over the value. If the predicate returns true it returns the original value wrapped with Some.
147+
If the predicate returns false, Nothing is returned
148+
149+
.. code:: python
150+
>>> from returns.maybe import Maybe, Nothing, Some
151+
152+
>>> assert Some(5).filter(lambda x: x % 2 == 0) == Nothing
153+
>>> assert Some(6).filter(lambda x: x % 2 == 0) == Some(6)
154+
>>> assert Nothing.filter(lambda x: True) == Nothing
155+
"""
142156
def lash(
143157
self,
144158
function: Callable[[Any], Kind1['Maybe', _ValueType]],
@@ -334,6 +348,10 @@ def bind_optional(self, function):
334348
"""Does nothing."""
335349
return self
336350

351+
def filter(self, function):
352+
"""Does nothing for ``Nothing`` """
353+
return self
354+
337355
def lash(self, function):
338356
"""Composes this container with a function returning container."""
339357
return function(None)
@@ -408,6 +426,12 @@ def failure(self):
408426
"""Raises exception for successful container."""
409427
raise UnwrapFailedError(self)
410428

429+
def filter(self, function):
430+
if function(self._inner_value):
431+
return self
432+
else:
433+
return _Nothing()
434+
411435

412436
Maybe.success_type = Some
413437
Maybe.failure_type = _Nothing
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
from returns.maybe import Maybe, Nothing, Some
2+
3+
4+
def test_maybe_filter():
5+
def predicate(value):
6+
return value % 2 == 0
7+
8+
assert Some(5).filter(predicate) == Nothing
9+
assert Some(6).filter(predicate) == Some(6)
10+
assert Nothing.filter(predicate) == Nothing

0 commit comments

Comments
 (0)