"""Types for representing strings that match a pattern... code-block:: python class Greeting(Match, pattern=r"^(Hi|Hello)"): ... assert isinstance("Hello Jane!", Greeting)"""from__future__importannotationsimportrefromreimportPatternfromtypingimportAnyfrom.importPhantomfrom.import_hypothesisfrom._utils.miscimportresolve_class_attrfrom.predicates.reimportis_full_matchfrom.predicates.reimportis_matchfrom.schemaimportSchema__all__=("Match","FullMatch")def_compile(pattern:Pattern[str]|str)->Pattern[str]:ifnotisinstance(pattern,Pattern):returnre.compile(pattern)returnpattern
[docs]classMatch(str,Phantom,abstract=True):""" Takes ``pattern: Pattern[str] | str`` as class argument as either a compiled :py:class:`Pattern` or a :py:class:`str` to be compiled. Uses the :py:func:`phantom.predicates.re.is_match` predicate. """__pattern__:Pattern[str]def__init_subclass__(cls,pattern:Pattern[str]|str,**kwargs:Any)->None:resolve_class_attr(cls,"__pattern__",_compile(pattern))super().__init_subclass__(predicate=is_match(cls.__pattern__),**kwargs)@classmethoddef__schema__(cls)->Schema:return{**super().__schema__(),"description":("A string starting with a match of the format regular expression."),"format":str(cls.__pattern__.pattern),}
[docs]classFullMatch(str,Phantom,abstract=True):""" Takes ``pattern: Pattern[str] | str`` as class argument as either a compiled :py:class:`Pattern` or a :py:class:`str` to be compiled. Uses the :py:func:`phantom.predicates.re.is_full_match` predicate. """__pattern__:Pattern[str]def__init_subclass__(cls,pattern:Pattern[str]|str,**kwargs:Any)->None:resolve_class_attr(cls,"__pattern__",_compile(pattern))super().__init_subclass__(predicate=is_full_match(cls.__pattern__),**kwargs)@classmethoddef__schema__(cls)->Schema:return{**super().__schema__(),"description":"A string that matches the format regular expression.","format":str(cls.__pattern__.pattern),}@classmethoddef__register_strategy__(cls)->_hypothesis.SearchStrategy|None:fromhypothesis.strategiesimportfrom_regexreturnfrom_regex(cls.__pattern__,fullmatch=True)