Home  >  Article  >  Backend Development  >  How Can I Parse Boolean Values Correctly in argparse?

How Can I Parse Boolean Values Correctly in argparse?

Linda Hamilton
Linda HamiltonOriginal
2024-10-26 18:56:29607browse

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>

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>

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>

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>

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!

Statement:
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