The Python Oracle

argparse store false if unspecified

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Riding Sky Waves v001

--

Chapters
00:00 Argparse Store False If Unspecified
00:18 Answer 1 Score 36
00:34 Accepted Answer Score 310
00:59 Answer 3 Score 17
01:52 Answer 4 Score 3
02:17 Thank you

--

Full question
https://stackoverflow.com/questions/8203...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #commandlinearguments #argparse

#avk47



ACCEPTED ANSWER

Score 310


The store_true option automatically creates a default value of False.

Likewise, store_false will default to True when the command-line argument is not present.

The source for this behavior is succinct and clear: http://hg.python.org/cpython/file/2.7/Lib/argparse.py#l861

The argparse docs aren't clear on the subject, so I'll update them now: http://hg.python.org/cpython/rev/49677cc6d83a




ANSWER 2

Score 36


With

import argparse

parser = argparse.ArgumentParser()
parser.add_argument('-flag', action='store_true')
args = parser.parse_args()

print(args.flag)

running yields

False

So it appears to be storing False by default.




ANSWER 3

Score 17


Raymond Hettinger answers OP's question already.

However, my group has experienced readability issues using "store_false". Especially when new members join our group. This is because it is most intuitive way to think is that when a user specifies an argument, the value corresponding to that argument will be True or 1.

For example, if the code is -

parser.add_argument('--stop_logging', action='store_false')

The code reader may likely expect the logging statement to be off when the value in stop_logging is true. But code such as the following will lead to the opposite of the desired behavior -

if not stop_logging:
    #log

On the other hand, if the interface is defined as the following, then the "if-statement" works and is more intuitive to read -

parser.add_argument('--stop_logging', action='store_true')
if not stop_logging:
    #log



ANSWER 4

Score 3


I've found the default, when unspecified, to vary between OSX and Linux.

With the following line of code,

parser.add_argument('-auto', action='store_true')

and then omitting -auto from the command line a Mac results in auto being assigned a value of False, as expected, whereas on Ubuntu Linux auto is assigned True by default.