Home > Backend Development > Python Tutorial > Why Does \'--foo False\' Evaluate to True When Parsing Boolean Arguments with argparse?

Why Does \'--foo False\' Evaluate to True When Parsing Boolean Arguments with argparse?

Linda Hamilton
Release: 2024-10-26 19:05:29
Original
913 people have browsed it

Why Does

Parsing Boolean Values with argparse

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

For negating the feature, use:

command --no-feature
Copy after login

argparse provides built-in support for this:

  • Python 3.9 : parser.add_argument('--feature', action=argparse.BooleanOptionalAction)
  • 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)
    Copy after login

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
Copy after login
<code class="python">parser.add_argument("--my_bool", type=ast.literal_eval)
parser.add_argument("--my_bool", type=t_or_f)</code>
Copy after login

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!

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