importfnmatchimportrefromtypingimportTYPE_CHECKING,Any,CallableifTYPE_CHECKING:fromtyping_extensionsimportTypeAlias# import from stdlib once Python >= 3.10Predicate:TypeAlias=Callable[[str],bool]else:Predicate="Predicate"class_Predicate:def__init__(self,pred:Predicate):self._pred:Predicate=pred._predifisinstance(pred,_Predicate)elsepreddef__call__(self,line:str)->bool:returnself._pred(line)def__and__(self,other:Predicate)->"_Predicate":self_pred=self._predother_pred=other._predifisinstance(other,_Predicate)elseotherreturn_Predicate(lambdaline:self_pred(line)andother_pred(line))def__or__(self,other:Predicate)->"_Predicate":self_pred=self._predother_pred=other._predifisinstance(other,_Predicate)elseotherreturn_Predicate(lambdaline:self_pred(line)orother_pred(line))def__invert__(self)->"_Predicate":self_pred=self._predreturn_Predicate(lambdaline:notself_pred(line))def__rrshift__(self,fn:Callable[[str],str])->"_Predicate":self_pred=self._predreturn_Predicate(lambdaline:self_pred(fn(line)))
[docs]defpred(fn:Callable[[str],Any])->_Predicate:"""Create a Predicate object from any function ``fn(str)``"""return_Predicate(lambdaline:bool(fn(line)))
[docs]defnegate(fn:Predicate)->_Predicate:"""Logical ``not`` that can be applied to a predicate. >>> predicate = lambda line: "python" in line.lower() >>> predicate("Python is a programming language") True >>> opposite_predicate = negate(predicate) >>> opposite_predicate("Python is a programming language") False """return~_Predicate(fn)