Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

argparse store false if unspecified

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


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.


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