Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why in argparse, a 'True' is always 'True'? [duplicate]

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() print(args.bool) 

But when I run this code on the command line:

python test.py --bool False True 

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

Why?

like image 298
Lu Zhang Avatar asked Jun 15 '17 07:06

Lu Zhang


People also ask

What is the purpose of Argparse?

The standard Python library argparse used to incorporate the parsing of command line arguments. Instead of having to manually set variables inside of the code, argparse can be used to add flexibility and reusability to your code by allowing user input values to be parsed and utilized.

What does Nargs do in Argparse?

Number of Arguments If you want your parameters to accept a list of items you can specify nargs=n for how many arguments to accept. Note, if you set nargs=1 , it will return as a list not a single value.

What does parse_args return?

Adding arguments Later, calling parse_args() will return an object with two attributes, integers and accumulate . The integers attribute will be a list of one or more ints, and the accumulate attribute will be either the sum() function, if --sum was specified at the command line, or the max() function if it was not.

What is const in Argparse?

const is the value it gets when given.


1 Answers

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('') False >>> bool('Any other string is True') True >>> bool('False')  # this includes the string 'False' True 

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 True  python test.py --bool False 

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.

like image 53
Martijn Pieters Avatar answered Oct 03 '22 20:10

Martijn Pieters