Parsing Boolean Values with argparse
When utilizing argparse to parse boolean command-line arguments, it's common to encounter scenarios where the desired behavior differs from the actual output. This occurs when arguments are specified as "--foo True" or "--foo False."
To address this issue, it's essential to delve deeper into the code:
<code class="python">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)</code>
Surprisingly, despite specifying "False" as the argument, parsed_args.my_bool evaluates to True. This anomaly also persists when cmd_line is modified to ["--my_bool", ""], which should logically evaluate to False.
Resolution
To overcome this challenge and accurately parse boolean values, one recommended approach is to adopt the more conventional style:
command --feature
and
command --no-feature
argparse effortlessly supports this format:
Python 3.9 and Above:
<code class="python">parser.add_argument('--feature', action=argparse.BooleanOptionalAction)</code>
Python 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>
Alternately, if the "--arg
<code class="python">def t_or_f(arg): ua = str(arg).upper() if 'TRUE'.startswith(ua): return True elif 'FALSE'.startswith(ua): return False else: pass #error condition maybe?</code>
The above is the detailed content of How to Parse Boolean Values Accurately with `argparse`?. For more information, please follow other related articles on the PHP Chinese website!