Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 315
SuperElectric Avatar asked Feb 21 '13 17:02

SuperElectric


People also ask

How do you pass a Boolean argument in Python Argparse?

The boolean value is always assigned, so that it can be used in logical statements without checking beforehand: import argparse parser = argparse. ArgumentParser(description="Parse bool") parser. add_argument("--do-something", default=False, action="store_true", help="Flag to do something") args = parser.

What does Argparse ArgumentParser ()?

The argparse module provides a convenient interface to handle command-line arguments. It displays the generic usage of the program, help, and errors. The parse_args() function of the ArgumentParser class parses arguments and adds value as an attribute dest of the object.


1 Answers

I think a more canonical way to do this is via:

command --feature 

and

command --no-feature 

argparse supports this version nicely:

Python 3.9+:

parser.add_argument('--feature', action=argparse.BooleanOptionalAction) 

Python < 3.9:

parser.add_argument('--feature', action='store_true') parser.add_argument('--no-feature', action='store_false') parser.set_defaults(feature=True) 

Of course, if you really want the --arg <True|False> version, you could pass ast.literal_eval as the "type", or a user defined function ...

def t_or_f(arg):     ua = str(arg).upper()     if 'TRUE'.startswith(ua):        return True     elif 'FALSE'.startswith(ua):        return False     else:        pass  #error condition maybe? 
like image 70
mgilson Avatar answered Oct 21 '22 22:10

mgilson