How Can I Parse Boolean Values Correctly in argparse?

Linda Hamilton
Release: 2024-10-26 18:56:29
Original
620 people have browsed it

How Can I Parse Boolean Values Correctly in argparse?

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

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

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 " syntax is desired, custom type conversion functions can be employed. One example is ast.literal_eval:

<code class="python">parser.add_argument("--arg", type=ast.literal_eval)</code>
Copy after login

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

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!

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
Latest Articles by Author
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!