MCPcopy Create free account
hub / github.com/Project-MONAI/MONAI / str2bool

Function str2bool

monai/utils/misc.py:459–491  ·  view source on GitHub ↗

Convert a string to a boolean. Case insensitive. True: yes, true, t, y, 1. False: no, false, f, n, 0. Args: value: string to be converted to a boolean. If value is a bool already, simply return it. raise_exc: if value not in tuples of expected true or false inputs,

(value: str | bool, default: bool = False, raise_exc: bool = True)

Source from the content-addressed store, hash-verified

457
458
459def str2bool(value: str | bool, default: bool = False, raise_exc: bool = True) -> bool:
460 """
461 Convert a string to a boolean. Case insensitive.
462 True: yes, true, t, y, 1. False: no, false, f, n, 0.
463
464 Args:
465 value: string to be converted to a boolean. If value is a bool already, simply return it.
466 raise_exc: if value not in tuples of expected true or false inputs,
467 should we raise an exception? If not, return `default`.
468 Raises
469 ValueError: value not in tuples of expected true or false inputs and
470 `raise_exc` is `True`.
471 Useful with argparse, for example:
472 parser.add_argument("--convert", default=False, type=str2bool)
473 python mycode.py --convert=True
474 """
475
476 if isinstance(value, bool):
477 return value
478
479 true_set = ("yes", "true", "t", "y", "1")
480 false_set = ("no", "false", "f", "n", "0")
481
482 if isinstance(value, str):
483 value = value.lower()
484 if value in true_set:
485 return True
486 if value in false_set:
487 return False
488
489 if raise_exc:
490 raise ValueError(f"Got \"{value}\", expected a value from: {', '.join(true_set + false_set)}")
491 return default
492
493
494def str2list(value: str | list | None, raise_exc: bool = True) -> list | None:

Callers 3

test_str_2_boolMethod · 0.90
debugMethod · 0.85
allow_pickleMethod · 0.85

Calls

no outgoing calls

Tested by 1

test_str_2_boolMethod · 0.72

Used in the wild real call sites across dependent graphs

searching dependent graphs…