Why in argparse, a 'True' is always 'True'?


Here is the simplest Python script, named test.py:

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('--bool', default=True, type=bool, help='Bool type')
args = parser.parse_args()

But when I run this code on the command line:

python test.py --bool False

Whereas when my code reads '--bool', default=False, the argparse runs correctly.


Asked By: Lu Zhang



You are not passing in the False object. You are passing in the 'False' string, and that’s a string of non-zero length.

Only a string of length 0 tests as false:

>>> bool('')
>>> bool('Any other string is True')
>>> bool('False')  # this includes the string 'False'

Use a store_true or store_false action instead. For default=True, use store_false:

parser.add_argument('--bool', default=True, action='store_false', help='Bool type')

Now omitting the switch sets args.bool to True, using --bool (with no further argument) sets args.bool to False:

python test.py

python test.py --bool

If you must parse a string with True or False in it, you’ll have to do so explicitly:

def boolean_string(s):
    if s not in {'False', 'True'}:
        raise ValueError('Not a valid boolean string')
    return s == 'True'

and use that as the conversion argument:

parser.add_argument('--bool', default=True, type=boolean_string, help='Bool type')

at which point --bool False will work as you expect it to.

Answered By: Martijn Pieters
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.