Source code for ppc_robot_lib.utils.field

from typing import TypeVar


T = TypeVar('T')


[docs] def get_base_name(field_name: str, suffixes: dict[str, T], separator='_', max_expansions=3) -> tuple[str, T]: """ Tries to find a suffix that is appended after a ``separator``. The suffix must be defined in the ``suffixes`` dictionary. This can be used to extract base name and a suffix from fixed range field names, e.g. ``Cost_7_day``. This method tries to find the longest suffix that is present in the dictionary. It finds all separators in the string and tries to match the suffix with the dictionary. If no match is found, it moves onto the next separator, until the ``max_expansions`` is reached. :param field_name: Name of the field to analyze. :param suffixes: Dictionary of suffixes, keys are the suffix, values can be anything. :param separator: Suffix separator. :param max_expansions: Maximum number of expansions to perform. :return: Tuple with base name and value for given suffix. """ separator_len = len(separator) name_len = len(field_name) split_pos = 0 expansion = 0 while split_pos < name_len and field_name[split_pos : split_pos + separator_len] == separator: split_pos += separator_len while expansion < max_expansions and split_pos < name_len: split_pos = field_name.find(separator, split_pos) if split_pos == -1: break suffix_candidate = field_name[split_pos + separator_len :] if suffix_candidate in suffixes: return field_name[:split_pos], suffixes[suffix_candidate] split_pos += separator_len expansion += 1 return field_name, None