edq.util.parse

 1import typing
 2
 3BOOL_TRUE_STRINGS: typing.Set[str] = {
 4    'true', 't',
 5    'yes', 'y',
 6    '1',
 7}
 8
 9BOOL_FALSE_STRINGS: typing.Set[str] = {
10    'false', 'f',
11    'no', 'n',
12    '0',
13}
14
15def soft_boolean(raw_text: typing.Union[bool, str, typing.Any]) -> typing.Union[bool, None]:
16    """
17    Parse a boolean from a string using common string representations for true/false.
18    If the input is not a bool or str, it will be converted to a str.
19    This function assumes the entire string is the boolean (not just a part of it).
20    If the string is not true or false, then return None.
21    """
22
23    if (isinstance(raw_text, bool)):
24        return raw_text
25
26    text = str(raw_text).lower().strip()
27
28    if (text in BOOL_TRUE_STRINGS):
29        return True
30
31    if (text in BOOL_FALSE_STRINGS):
32        return False
33
34    return None
35
36def boolean(raw_text: typing.Union[str, bool]) -> bool:
37    """
38    Like soft_boolean(), but raise an exception if no boolean is parsed.
39    """
40
41    value = soft_boolean(raw_text)
42    if (value is not None):
43        return value
44
45    raise ValueError(f"Could not convert text to boolean: '{raw_text}'.")
BOOL_TRUE_STRINGS: Set[str] = {'yes', 't', '1', 'y', 'true'}
BOOL_FALSE_STRINGS: Set[str] = {'0', 'false', 'no', 'f', 'n'}
def soft_boolean(raw_text: Union[bool, str, Any]) -> Optional[bool]:
16def soft_boolean(raw_text: typing.Union[bool, str, typing.Any]) -> typing.Union[bool, None]:
17    """
18    Parse a boolean from a string using common string representations for true/false.
19    If the input is not a bool or str, it will be converted to a str.
20    This function assumes the entire string is the boolean (not just a part of it).
21    If the string is not true or false, then return None.
22    """
23
24    if (isinstance(raw_text, bool)):
25        return raw_text
26
27    text = str(raw_text).lower().strip()
28
29    if (text in BOOL_TRUE_STRINGS):
30        return True
31
32    if (text in BOOL_FALSE_STRINGS):
33        return False
34
35    return None

Parse a boolean from a string using common string representations for true/false. If the input is not a bool or str, it will be converted to a str. This function assumes the entire string is the boolean (not just a part of it). If the string is not true or false, then return None.

def boolean(raw_text: Union[str, bool]) -> bool:
37def boolean(raw_text: typing.Union[str, bool]) -> bool:
38    """
39    Like soft_boolean(), but raise an exception if no boolean is parsed.
40    """
41
42    value = soft_boolean(raw_text)
43    if (value is not None):
44        return value
45
46    raise ValueError(f"Could not convert text to boolean: '{raw_text}'.")

Like soft_boolean(), but raise an exception if no boolean is parsed.