Ask a Question
Ask Question Login
Corporate Training
  1. Community
  2. SQL Server
  3. Question
SQL Server

Parsing boolean values with argparse

Asked by Arun Sharma Nov 30, -0001 3.2K views 3 answers
Share

About this question

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?

Your answer

3 Answers

Bhim Marasini Latest answer

Answered on Jan 14, 2026

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!

Was this helpful?

Claude Holloway

Answered on Nov 12, 2024

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. 


Was this helpful?

Arun Sharma

Answered on Jun 20, 2021

Was this helpful?

More SQL Server discussions

Learn & Explore

Free tutorials and interview questions from industry experts — learn the skill, then get ready to prove it.

Latest SQL Server Blogs

Guides, tips and career advice on SQL Server from JanBask experts.