DEV Community


Posted on

Python: argparse action store

As we already saw in this series, argparse is a built-in Python module that can help you build friendly CLI tools:

It's quite straightforward, but some parts, like actions, may be confusing for beginners.

Create on/off flags

It's not uncommon to need some on/off flag in our CLI commands:

import argparse

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="My client")
    parser.add_argument('-v', '--verbose', action='store_true')
Enter fullscreen mode Exit fullscreen mode

The action parameter allows setting how arguments should be handled:

'store', 'store_const', 'store_true', 'append', 'append_const', 'count', 'help', 'version'

It might seem self-explanatory, but you might struggle to understand how to use values like store_true.

Don't be confused. store_true will default to False. If you need to set a default value to True, use store_false instead.

Create arbitrary actions

If you need something like --exec / --no-exec, you can leverage BooleanOptionalAction (Python 3.9):

parser.add_argument('--exec', action=argparse.BooleanOptionalAction)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)