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 booleans True and False. 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) – If True, also convert 'yes' to True and 'no' to False.

  • accept_abbrev (bool, optional) –

    If True, also convert the following abbreviations:

    • 't' to True.

    • 'y' to True.

    • 'f' to False.

    • 'n' to False.

  • accept_01 (bool, optional) – If True, also convert '1' to True and '0' to False.

Returns:

val (bool) – The input string converted to True or False.

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 to True (including the string 'false') . Pass str2bool(val) to the type keyword of argparse.ArgumentParser.add_argument() to convert the strings 'true' and 'false' to their corresponding boolean values True or False.

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'