Question:
When parsing boolean command-line arguments with argparse, why do values like "--foo False" evaluate to True instead of False?
Answer:
Canonical Method:
The recommended approach is to use the following format:
command --feature
For negating the feature, use:
command --no-feature
argparse provides built-in support for this:
Python < 3.9:
parser.add_argument('--feature', action='store_true') parser.add_argument('--no-feature', dest='feature', action='store_false') parser.set_defaults(feature=True)
Alternative Method for Custom Parsing:
If the "--foo True/False" format is preferred, one option is to use ast.literal_eval or a custom function as the type:
import ast def t_or_f(arg): ua = str(arg).upper() if 'TRUE'.startswith(ua): return True elif 'FALSE'.startswith(ua): return False else: pass # Handle error condition appropriately
<code class="python">parser.add_argument("--my_bool", type=ast.literal_eval) parser.add_argument("--my_bool", type=t_or_f)</code>
This custom function interprets uppercase True/False as boolean values, allowing for flexible parsing of these values.
The above is the detailed content of Why Does '--foo False' Evaluate to True When Parsing Boolean Arguments with argparse?. For more information, please follow other related articles on the PHP Chinese website!