Parsing boolean values with argparse

785    Asked by ArunSharma in SQL Server , Asked on Nov 30, -0001

I would like to use argparse to parse boolean command-line arguments written as "--foo True" or "--foo False". For example:

my_program --my_boolean_flag False

However, the following test code does not do what I would like:

import argparse

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

cmd_line = ["--my_bool", "False"]

parsed_args = parser.parse(cmd_line)

Sadly, parsed_args.my_bool evaluates to True. This is the case even when I change cmd_line to be ["--my_bool", ""], which is surprising, since bool("") evaluates to False.

How can I get argparse to parse "False", "F", and their lower-case variants to be False?

Answered by Ashish Mishra

Your Answer

Answer (1)

import argparse

# Custom function to parse boolean values
def parse_boolean(value):
if value.lower() in ['true', '1', 't', 'y', 'yes']:
return True
elif value.lower() in ['false', '0', 'f', 'n', 'no']:
return False
else:
raise argparse.ArgumentTypeError(f"Invalid boolean value: {value}")

# Setup the argument parser
parser = argparse.ArgumentParser(description="My parser")
parser.add_argument("--my_bool", type=parse_boolean)

# Example command-line input (this would be passed as sys.argv in a real case)
cmd_line = ["--my_bool", "False"]

# Parse the arguments
parsed_args = parser.parse_args(cmd_line)

# Out

To achieve the behavior you're describing, where --my_bool False is parsed as a boolean False geometry dash lite, and --my_bool True is parsed as a boolean True, you need to implement a custom type or a custom action in argparse. 


5 Months

Interviews

Parent Categories