How to Properly Handle Boolean Arguments with argparse in Python?

Susan Sarandon
Release: 2024-10-28 08:11:30
Original
477 people have browsed it

How to Properly Handle Boolean Arguments with argparse in Python?

Handling Boolean Arguments in argparse

Parsing arguments from the command line can be simplified using the argparse module in Python. While it supports parsing boolean flags, certain scenarios can lead to unexpected results.

To correctly parse boolean values like "--foo True" or "--foo False," the default behavior of argparse may not suffice. For instance, using type=bool alone can result in unexpected outcomes when arguments are set to "False" or empty strings.

One solution is to leverage the BooleanOptionalAction introduced in Python 3.9. This action provides a more intuitive handling of boolean values, automatically converting True, t, y, yes, and 1 to True, and False, f, n, no, and 0 to False.

For Python versions before 3.9, a workaround involves combining the 'store_true' and 'store_false' actions. The 'store_true' action sets a flag to True when present, while 'store_false' sets it to False. By default, the flag is assumed to be True, allowing users to specify both positive and negative flags:

<code class="python">import argparse

parser = argparse.ArgumentParser(description="My parser")
parser.add_argument('--feature', action='store_true')
parser.add_argument('--no-feature', dest='feature', action='store_false')
parser.set_defaults(feature=True)

cmd_line = ["--no-feature"]
parsed_args = parser.parse_args(cmd_line)

if parsed_args.feature:
    print("Feature is True.")
else:
    print("Feature is False.")</code>
Copy after login

Alternatively, custom functions can be defined to handle specific parsing logic. For example, a function that distinguishes between "True" and "False" case-insensitively:

<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 argument: {}".format(arg))</code>
Copy after login

This function can then be used with the type parameter of argparse:

<code class="python">import argparse

parser = argparse.ArgumentParser(description="My parser")
parser.add_argument('--my_bool', type=t_or_f)

cmd_line = ["--my_bool", "False"]
parsed_args = parser.parse_args(cmd_line)

if parsed_args.my_bool:
    print("my_bool is True.")
else:
    print("my_bool is False.")</code>
Copy after login

The above is the detailed content of How to Properly Handle Boolean Arguments with argparse in Python?. 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!