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)
| 457 | |
| 458 | |
| 459 | def 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 | |
| 494 | def str2list(value: str | list | None, raise_exc: bool = True) -> list | None: |
no outgoing calls
searching dependent graphs…