"""Miscellaneous utility functions.""" import re def parse_string_as_bool(value: str) -> bool: """Parses the given string into a boolean based on its content. This is used to parse environment variables as boolean values. The following strings are parsed as `True`: "yes", "Yes", "YES", "true", "True", "TRUE", "1" The following strings are parsed as `False`: "no", "No", "NO", "false", "False", "FALSE", "0" In any other case, a `ValueError` is raised. """ if not isinstance(value, str): raise TypeError("Expected a string argument.") regex_true = re.compile(r"^(YES)|(Yes)|(yes)|(TRUE)|(True)|(true)|(1)$") regex_false = re.compile(r"^(NO)|(No)|(no)|(FALSE)|(False)|(false)|(0)$") if regex_true.fullmatch(value): return True if regex_false.fullmatch(value): return False raise ValueError(f"Failed to parse the supplied value as a boolean: {value!r}")