@staticmethod
def match(item, functions: list, logic_bool: str='and') -> bool:
"""Return True if the given item matches all or any of the functions.
The functions parameter is a list of tuples to match against:
- function: a function in python which takes 2 arguments: (item, value)
- value: the expected value for the item
- logical_not: boolean
:param item: (any) Item to find a match
:param functions: (list[tuples]) List of tuples(function, value, logical_not)
:param logic_bool: (str) Apply a logical "and" or a logical "or" between the functions.
:return: (bool)
:raises: TypeError: Invalid functions parameter
:Example:
>>> # Search if a string is exactly matching "toto":
>>> StringComparator.match("toto", [(exact, "toto", False)])
True
>>> StringComparator.match("TOTO", [(exact, "toto", False)])
False
>>> StringComparator.match("TOTO", [(iexact, "toto", False)])
True
>>> # Search if a string is starting with "p" or starting with "t":
>>> StringComparator.match("my_string", [(startswith, "p", False), (startswith, "t", False)], logic_bool="or")
False
>>> # Search if a date is exactly (2024, 3, 4):
>>> DatetimeComparator.match(datetime.date((2024, 3, 4)), [(equal, (2024, 3, 4), False)])
True
>>> # Search if a date is between two other ones:
>>> DatetimeComparator.match(datetime.date((2024, 3, 4)), [(gt, (2022, 1, 1), False), (lt, (2024, 12, 31), False)], logic_bool="and")
True
"""
if isinstance(functions, (list, tuple)) is False:
raise TypeError('Invalid functions parameter {}.'.format(functions))
for f in functions:
if len(f) != 3:
raise TypeError('Invalid functions parameter {}.'.format(functions))
matches = list()
for func, value, logical_not in functions:
if logical_not is True:
matches.append(not func(item, value))
else:
matches.append(func(item, value))
if logic_bool == 'and':
return all(matches)
else:
return any(matches)