patternpythonModerate
Parsing boolean values with argparse
Viewed 0 times
valuesargparseparsingbooleanwith
Problem
I would like to use argparse to parse boolean command-line arguments written as "--foo True" or "--foo False". For example:
However, the following test code does not do what I would like:
Sadly,
How can I get argparse to parse
my_program --my_boolean_flag FalseHowever, the following test code does not do what I would like:
import argparse
parser = argparse.ArgumentParser(description="My parser")
parser.add_argument("--my_bool", type=bool)
cmd_line = ["--my_bool", "False"]
parsed_args = parser.parse(cmd_line)Sadly,
parsed_args.my_bool evaluates to True. This is the case even when I change cmd_line to be ["--my_bool", ""], which is surprising, since bool("") evalutates to False.How can I get argparse to parse
"False", "F", and their lower-case variants to be False?Solution
Simplest & most correct way is:
Do note that 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.
from distutils.util import strtobool
parser.add_argument('--feature', dest='feature',
type=lambda x: bool(strtobool(x)))
Do note that 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.
Context
Stack Overflow Q#15008758, score: 46
Revisions (0)
No revisions yet.