How to Parse Boolean Values Accurately with `argparse`?

DDD
Release: 2024-10-26 14:05:30
Original
529 people have browsed it

How to Parse Boolean Values Accurately with `argparse`?

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>
Copy after login

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
Copy after login

and

command --no-feature
Copy after login

argparse effortlessly supports this format:

Python 3.9 and Above:

<code class="python">parser.add_argument('--feature', action=argparse.BooleanOptionalAction)</code>
Copy after login

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>
Copy after login

Alternately, if the "--arg " format is preferred, ast.literal_eval or a custom function, such as the following, can be utilized as the "type" parameter:

<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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!