Skip to content

Bools

toolbox_python.bools 🔗

Summary

The bools module is used how to manipulate and enhance Python booleans.

Details

Primarily, this module is used to store the strtobool() function, which used to be found in the distutils.util module, until it was deprecated. As mentioned in PEP632, we should re-implement this function in our own code. And that's what we've done here.

STR_TO_BOOL_MAP module-attribute 🔗

STR_TO_BOOL_MAP: dict[str, bool] = {
    "y": True,
    "yes": True,
    "t": True,
    "true": True,
    "on": True,
    "1": True,
    "n": False,
    "no": False,
    "f": False,
    "false": False,
    "off": False,
    "0": False,
}
Summary

Map of string values to their corresponding boolean values.

strtobool 🔗

strtobool(value: str) -> bool

Summary

Convert a str value in to a bool value.

Details

This process is necessary because the distutils` module was completely deprecated in Python 3.12.

Parameters:

Name Type Description Default
value str

The string value to convert. Valid input options are defined in STR_TO_BOOL_MAP

required

Raises:

Type Description
ValueError

If the value parse'ed in to value is not a valid value to be able to convert to a bool value.

Returns:

Type Description
bool

A True or False value, having successfully converted value.

Examples
Set up
1
from toolbox_python.bools import strtobool

Example 1: `true` conversions
1
2
3
>>> print(strtobool("true"))
>>> print(strtobool("t"))
>>> print(strtobool("1"))
Terminal
True
True
True

Conclusion: Successful conversion.

Example 2: `false` conversions
1
2
3
>>> print(strtobool("false"))
>>> print(strtobool("f"))
>>> print(strtobool("0"))
Terminal
False
False
False

Conclusion: Successful conversion.

Example 3: invalid value
1
>>> print(strtobool(5))
Terminal
ValueError: Invalid bool value: '5'.
For `True`, must be one of: ['y', 'yes', 't', 'true', 'on', '1']
For `False`, must be one of: ['n', 'no', 'f', 'false', 'off', '0']

Conclusion: Invalid type.

References
Source code in src/toolbox_python/bools.py
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
def strtobool(value: str) -> bool:
    """
    !!! note "Summary"
        Convert a `#!py str` value in to a `#!py bool` value.

    ???+ abstract "Details"
        This process is necessary because the `d`istutils` module was completely deprecated in Python 3.12.

    Params:
        value (str):
            The string value to convert. Valid input options are defined in [`STR_TO_BOOL_MAP`][toolbox_python.bools.STR_TO_BOOL_MAP]

    Raises:
        ValueError:
            If the value parse'ed in to `value` is not a valid value to be able to convert to a `#!py bool` value.

    Returns:
        (bool):
            A `#!py True` or `#!py False` value, having successfully converted `value`.

    ???+ example "Examples"

        ```{.py .python linenums="1" title="Set up"}
        from toolbox_python.bools import strtobool
        ```

        ```{.py .python linenums="1" title="Example 1: `true` conversions"}
        >>> print(strtobool("true"))
        >>> print(strtobool("t"))
        >>> print(strtobool("1"))
        ```
        <div class="result" markdown>
        ```{.sh .shell title="Terminal"}
        True
        True
        True
        ```
        !!! success "Conclusion: Successful conversion."
        </div>

        ```{.py .python linenums="1" title="Example 2: `false` conversions"}
        >>> print(strtobool("false"))
        >>> print(strtobool("f"))
        >>> print(strtobool("0"))
        ```
        <div class="result" markdown>
        ```{.sh .shell title="Terminal"}
        False
        False
        False
        ```
        !!! success "Conclusion: Successful conversion."
        </div>

        ```{.py .python linenums="1" title="Example 3: invalid value"}
        >>> print(strtobool(5))
        ```
        <div class="result" markdown>
        ```{.sh .shell title="Terminal"}
        ValueError: Invalid bool value: '5'.
        For `True`, must be one of: ['y', 'yes', 't', 'true', 'on', '1']
        For `False`, must be one of: ['n', 'no', 'f', 'false', 'off', '0']
        ```
        !!! failure "Conclusion: Invalid type."
        </div>

    ??? question "References"
        - [PEP632](https://peps.python.org/pep-0632/#migration-advice)
    """
    try:
        return STR_TO_BOOL_MAP[str(value).lower()]
    except KeyError as exc:
        raise ValueError(
            f"Invalid bool value: '{value}'.\n"
            f"For `True`, must be one of: {[key for key, val in STR_TO_BOOL_MAP.items() if val]}\n"
            f"For `False`, must be one of: {[key for key, val in STR_TO_BOOL_MAP.items() if not val]}"
        ) from exc