"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Can I Parse Boolean Values Correctly in argparse?

How Can I Parse Boolean Values Correctly in argparse?

Published on 2024-11-23
Browse:419

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:

parser.add_argument('--feature', action=argparse.BooleanOptionalAction)

In Python versions below 3.9:

parser.add_argument('--feature', action='store_true')
parser.add_argument('--no-feature', dest='feature', action='store_false')
parser.set_defaults(feature=True)

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:

parser.add_argument("--arg", type=ast.literal_eval)

Alternatively, a user-defined function can be created:

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')
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3