Created
March 16, 2024 07:59
-
-
Save harkabeeparolus/80ced8d2590c74924711aeec34e0bad3 to your computer and use it in GitHub Desktop.
Convert a string representation of truth to True or False
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# This used to exist in distutils, which is removed since Python 3.12 | |
# https://github.com/pypa/distutils/blob/main/distutils/util.py#L340 | |
def strtobool(val: str) -> bool: | |
"""Convert a string representation of truth to True or False. | |
True values are 'y', 'yes', 't', 'true', 'on', and '1'; false values are 'n', 'no', | |
'f', 'false', 'off', and '0'. Raises ValueError if 'val' is anything else. | |
""" | |
val = val.strip().casefold() | |
if val in {"y", "yes", "t", "true", "on", "1"}: | |
return True | |
if val in {"n", "no", "f", "false", "off", "0"}: | |
return False | |
raise ValueError(f"invalid truth value {val!r}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment