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