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>
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>
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>
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!