@@ -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
412436Maybe .success_type = Some
413437Maybe .failure_type = _Nothing
0 commit comments