str2bool
- mdtools.file_handler.str2bool(val, accept_yes_no=True, accept_abbrev=True, accept_01=True)[source]
Convert a string to a boolean value.
Convert the strings
'true'
and'false'
to their corresponding booleansTrue
andFalse
. This function is case-insensitive!- Parameters:
val (
str_like
) – The input value. Can be anything that can be converted to a string.accept_yes_no (
bool
, optional) – IfTrue
, also convert'yes'
toTrue
and'no'
toFalse
.accept_abbrev (
bool
, optional) –If
True
, also convert the following abbreviations:'t'
toTrue
.'y'
toTrue
.'f'
toFalse
.'n'
toFalse
.
accept_01 (
bool
, optional) – IfTrue
, also convert'1'
toTrue
and'0'
toFalse
.
- Returns:
val (
bool
) – The input string converted toTrue
orFalse
.- Raises:
ValueError : – If val is an unknown string that cannot be converted to a boolean value.
See also
mdtools.file_handler.str2none_or_type()
Convert a string to the NoneType
None
or to a given type
Notes
This function was written to enable passing booleans to scripts via the command line. By default,
argparse
reads command-line arguments as simple strings. This makes it impossible to pass booleans to a script via the command line in an intuitive way, because the type conversion to bool will convert all non-empty strings toTrue
(including the string'false'
) . Passstr2bool(val)
to the type keyword ofargparse.ArgumentParser.add_argument()
to convert the strings'true'
and'false'
to their corresponding boolean valuesTrue
orFalse
.References
This code was adapted from https://stackoverflow.com/a/43357954.
Examples
>>> mdt.fh.str2bool('True') True >>> mdt.fh.str2bool('true') True >>> mdt.fh.str2bool('false') False >>> mdt.fh.str2bool('False') False >>> mdt.fh.str2bool('fAlSe') False
>>> mdt.fh.str2bool('yes', accept_yes_no=True) True >>> mdt.fh.str2bool('no', accept_yes_no=True) False
>>> mdt.fh.str2bool('y', accept_yes_no=True, accept_abbrev=True) True >>> mdt.fh.str2bool('n', accept_yes_no=True, accept_abbrev=True) False >>> mdt.fh.str2bool('n', accept_yes_no=True, accept_abbrev=False) Traceback (most recent call last): ... ValueError: ...
>>> mdt.fh.str2bool(1, accept_01=True) True >>> mdt.fh.str2bool('1', accept_01=True) True >>> mdt.fh.str2bool(0, accept_01=True) False >>> mdt.fh.str2bool('0', accept_01=True) False
>>> import argparse >>> parser = argparse.ArgumentParser() >>> parser.add_argument('--spam', type=mdt.fh.str2bool) _StoreAction(option_strings=['--spam'], ...) >>> parser.add_argument('--eggs', type=str) _StoreAction(option_strings=['--eggs'], ...) >>> args = parser.parse_args(['--spam', 'yes', '--eggs', 'no']) >>> args.spam True >>> args.eggs 'no'