Programming
python boolean argparse command-line-arguments
Updated Sat, 30 Jul 2022 00:01:28 GMT

Parsing boolean values with argparse


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("") evalutates to False.

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




Solution

This is actually outdated. For Python 3.7+, Argparse now supports boolean args (search BooleanOptionalAction).

The implementation looks like this:

import argparse
ap = argparse.ArgumentParser()
# List of args
ap.add_argument('--foo', default=True, type=bool, help='Some helpful text that is not bar. Default = True')
# Importable object
args = ap.parse_args()

One other thing to mention: this will block all entries other than True and False for the argument via argparse.ArgumentTypeError. You can create a custom error class for this if you want to try to change this for any reason.





Comments (5)

  • +0 – You are mentioning this working in 3.7+ and 3.9+. Which one is it? — Aug 23, 2021 at 14:19  
  • +0 – 3.7+. Clarified in an edit — Nov 05, 2021 at 17:50  
  • +1 – The python documentation mentions New in version 3.9 and I cannot import BooleanOptionalAction from argparse in 3.7... — Nov 26, 2021 at 17:27  
  • +5NO. That is not how action=argparse.BooleanOptionalAction works. Earlier under type, it warns against using the type=bool, "The bool() function is not recommended as a type converter. All it does is convert empty strings to False and non-empty strings to True. This is usually not what is desired.". — Jan 08, 2022 at 07:44  
  • +1 – Agreed, this answer should not be accepted: args = ap.parse_args(['--foo', 'False']) returns True (and in my opinion it shouldn't — Mar 22, 2022 at 11:19  


External Links

External links referenced by this document: