argparse store false if unspecified

siamii picture siamii · Nov 20, 2011 · Viewed 73.7k times · Source
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

Answer

Raymond Hettinger picture Raymond Hettinger · Nov 20, 2011

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