Python: argparse - add binary arguments

Akshay Chavan
5 min readJan 28, 2024
Flip switch on a musical instrument.
Photo by Mikkel Bech on Unsplash

The argparse module provides an easy and fast way to design a command line interface for your script or program. Command line interface gives your script the functionality to run in different configurations by providing a combination of values to the arguments.

The actions that you set specifics how the command line argument works. Some action values that you can set are store, store_true, append, and count. As the names suggest, the store option helps store the input provided in a variable, the append action appends the argument values provided multiple times into a list. The count action counts the number of times the keyword argument occurs. store_const action helps set a constant value to a variable, else it’s set to None.

In this article, we will limit ourselves to store_true and store_false action. This action is a special case of store_const where only true or false values can be stored. The store true and false action is useful for storing binary values, which can enable/disable multiple code flows in a script. There is no other way in argparse, except the store_* and *_const actions, that will not take a value for an argument. The nargs=0 option is not allowed while using the action store.

Let’s look at an example to on how to use the action store_true/false using door as an example. A door can be opened or closed.

--

--