Skip to content

Instantly share code, notes, and snippets.

@harkabeeparolus
Created March 16, 2024 07:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save harkabeeparolus/80ced8d2590c74924711aeec34e0bad3 to your computer and use it in GitHub Desktop.
Save harkabeeparolus/80ced8d2590c74924711aeec34e0bad3 to your computer and use it in GitHub Desktop.
Convert a string representation of truth to True or False
# 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