WhintPy 1.1

https://sourceforge.net/projects/whintpy/

Module whintpy.filters

Class BaseComparator

Description

Base class for any comparator system.

Serve as a foundational class for creating comparator systems. It manages a collection of comparison methods and provides functionality to retrieve and apply these methods to items.

Example
 >>> comparator = BaseComparator()
 >>> comparator._methods['exact'] = lambda x, y: x == y
 >>> comparator._methods['iexact'] = lambda x, y: x.lower() == y.lower()
 >>> # Retrieve a method
 >>> exact_method = comparator.get('exact')
 >>> print(exact_method('abc', 'abc'))
 > True
 >>> # Get all method names
 >>> print(comparator.get_function_names())
 > ['exact', 'iexact']
 >>> # Match item using methods
 >>> functions = [(comparator.get('exact'), 'abc', False)]
 >>> print(BaseComparator.match('abc', functions))
 > True

Constructor

Constructor of a BaseCompare.

View Source
def __init__(self):
    """Constructor of a BaseCompare.

    """
    self._methods = dict()

Public functions

get

Return the function of the given name.

Parameters
  • name: (str) The name of a method of this class
View Source
def get(self, name: str):
    """Return the function of the given name.

        :param name: (str) The name of a method of this class

        """
    if name in self._methods:
        return self._methods[name]
    raise ValueError(f'Invalid function name {name}')

get_function_names

Return the list of comparison method names.

View Source
def get_function_names(self) -> list:
    """Return the list of comparison method names.

        """
    return list(self._methods.keys())

match

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

Parameters
  • item: (any) Item to find a match
  • functions: (list[tuples]) List of tuples(function, value, logical_not)
  • logic_bool: (str) Apply a logical "and" or a logical "or" between the functions.
Returns
  • (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
View Source
@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)