Parsing Boolean Values with argparse
In argparse, parsing boolean command-line arguments is a common task, but a common pitfall arises when attempting to parse values like "--foo True" or "--foo False" using the type=bool argument. Surprisingly, even when using an empty string as the argument (e.g., "--foo " "), the parsed value evaluates to True.
For correct Boolean parsing, argparse offers two recommended approaches:
Canonical Approach:
Use the '--feature' and '--no-feature' syntax, supported natively by argparse. In Python 3.9 and above:
<code class="python">parser.add_argument('--feature', action=argparse.BooleanOptionalAction)</code>
In Python versions below 3.9:
<code class="python">parser.add_argument('--feature', action='store_true') parser.add_argument('--no-feature', dest='feature', action='store_false') parser.set_defaults(feature=True)</code>
With this approach, the presence of '--feature' sets the value to True, while '--no-feature' sets it to False. The absence of either argument defaults to True.
Optional Approach (Using Type Conversion):
If the "--arg
<code class="python">parser.add_argument("--arg", type=ast.literal_eval)</code>
Alternatively, a user-defined function can be created:
<code class="python">def true_or_false(arg): ua = str(arg).upper() if 'TRUE'.startswith(ua): return True elif 'FALSE'.startswith(ua): return False else: raise argparse.ArgumentTypeError('Invalid boolean value')</code>
The above is the detailed content of How Can I Parse Boolean Values Correctly in argparse?. For more information, please follow other related articles on the PHP Chinese website!