Parsing boolean values with argparse

2.5K    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

Answers (2)

I just joined the JanBask Training Community debate about interpreting boolean values, and I completely understand! I recall dealing with command line arguments in my Python project. Switching from basic flags to booleans seems scary at first, but utilizing argparse made it lot easy! Your suggestions for dealing with defaults and type conversions are quite helpful—I can't wait to use them in my next script! Thank you for providing these fnaf 2 insights!

5 Months

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. 


1 Year

Interviews

Parent Categories