How to use Python argparse: Default Values, Optional Arguments, and nargs='?'
Python's argparse module provides a powerful way to create command-line interfaces.
This guide explains how to use nargs='?', const, and default in argparse to create optional arguments that have default values if the argument is either not provided at all, or is provided without a value.
Understanding nargs='?', const, and default
When working with argparse, these three arguments are often used together to define optional arguments with defaults:
nargs='?': This makes the command-line argument optional.- If the argument is provided with a value (e.g.,
--fruit banana), that value is used. - If the argument is provided without a value (e.g.,
--fruit), the value fromconstis used. - If the argument is not provided at all (e.g., no
--fruit), the value fromdefaultis used.
- If the argument is provided with a value (e.g.,
const: The value to use if the argument is present on the command line but without a value. This is only relevant whennargs='?'.default: The value to use if the argument is not present on the command line at all.