Skip to content

Commit 98e37c2

Browse files
Filter for maybe
1 parent 9277846 commit 98e37c2

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
@@ -141,6 +141,20 @@ def bind_optional(
141141
142142
"""
143143

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

355+
def filter(self, function):
356+
"""Does nothing for ``Nothing`` """
357+
return self
358+
341359
def lash(self, function):
342360
"""Composes this container with a function returning container."""
343361
return function(None)
@@ -414,6 +432,12 @@ def failure(self):
414432
"""Raises exception for successful container."""
415433
raise UnwrapFailedError(self)
416434

435+
def filter(self, function):
436+
if function(self._inner_value):
437+
return self
438+
else:
439+
return _Nothing()
440+
417441

418442
Maybe.success_type = Some
419443
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)