+1 vote
in Programming Languages by (74.2k points)

I want to pass boolean values (True/False) from the command line using argparse module, but the value is treated as a string. I am using the following way to pass boolean values. How can I make it work?

parser.add_argument("-trim_results", type=bool, choices=[True, False], default=True,

                help="want to trim the results?")

1 Answer

+1 vote
by (56.8k points)
selected by
 
Best answer

"type=bool" is not recommended as the bool() function converts empty strings to False and non-empty strings to True. You can use a user-defined function as a type to convert a string to a boolean value.

Here is an example:

def str_to_bool(s):
    """
    convert command line True/False to boolean as argparse considers them string.
    """
    if s == 'True':
        return True
    elif s == 'False':
        return False
    else:
        print("invalid boolean value provided")
        
parser.add_argument("-trim_results", type=str_to_bool, choices=[True, False], default=True,
                help="want to trim the results")

...