How to Parse Boolean Command-Line Arguments with argparse: Why \'--foo False\' Doesn\'t Always Mean False?

Linda Hamilton
Release: 2024-10-31 12:26:03
Original
424 people have browsed it

How to Parse Boolean Command-Line Arguments with argparse: Why

Parsing Boolean Command-Line Arguments with argparse

When using argparse to parse boolean arguments, users may encounter challenges if they input values as "--foo True" or "--foo False." Despite the intuitive assumption that "--foo False" should evaluate to False, argparse interprets it as True. This behavior also occurs when inputting an empty string for the boolean argument.

To address this issue, argparse provides alternative parsing options for boolean flags:

1. Action=argparse.BooleanOptionalAction (Python 3.9 )

By specifying action=argparse.BooleanOptionalAction, argparse will automatically interpret the presence of the flag without an argument as True, and its absence as False. For example:

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

2. Store_True and Store_False

For Python versions prior to 3.9, the following approach can be used:

<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

This allows users to enable or disable a feature by passing "--feature" or "--no-feature," respectively.

3. Custom Type Function

If desired, a custom type function can be used to handle boolean parsing. Here's an example:

<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:
        raise ValueError("Invalid input")</code>
Copy after login

This function can then be used as the type argument when adding the boolean argument to the parser.

By utilizing these methods, users can effectively parse boolean command-line arguments and ensure that values like "False" are interpreted correctly.

The above is the detailed content of How to Parse Boolean Command-Line Arguments with argparse: Why \'--foo False\' Doesn\'t Always Mean False?. 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!