argparse store false if unspecified

Question:

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

How can I store false if -auto is unspecified? I can faintly remember that this way, it stores None if unspecified

Asked By: siamii

||

Answers:

With

import argparse
parser=argparse.ArgumentParser()
parser.add_argument('-auto', action='store_true', )
args=parser.parse_args()
print(args)

running

% test.py

yields

Namespace(auto=False)

So it appears to be storing False by default.

Answered By: unutbu

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

Answered By: Raymond Hettinger

store_false will actually default to 0 by default (you can test to verify). To change what it defaults to, just add default=True to your declaration.

So in this case:
parser.add_argument('-auto', action='store_true', default=True)

Answered By: Unix-Ninja

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
Answered By: MonsieurBeilto

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.

Answered By: Pete Mueller