argparse-addons
argparse-addons is a Python library that provides additional types and actions for the standard library's `argparse` module, enhancing command-line interface creation. The current version is 0.12.0. The project maintains a somewhat active release cadence, with the last update in January 2023.
Warnings
- gotcha Calling `parser.parse_args()` at the top level of an imported module can lead to unexpected argument parsing behavior or errors in the main script. Always guard `ArgumentParser` instantiation and `parse_args()` calls within an `if __name__ == "__main__":` block if the module is intended to be imported.
- gotcha When a positional argument is defined with `nargs='*'` (zero or more arguments) and also `choices`, providing no values for that argument can result in an 'invalid choice: []' error, because `argparse` attempts to validate an empty list against the defined choices.
- gotcha The interaction between `default` values and actions like `action='append'` or `action='extend'` can be non-intuitive. Default values might be prepended to user-provided input, making it difficult to completely override the default without custom logic.
Install
-
pip install argparse-addons
Imports
- Integer
from argparse_addons import Integer
Quickstart
import argparse
from argparse_addons import Integer
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument(
'--value',
type=Integer(0, 255),
help='An integer value between 0 and 255.'
)
args = parser.parse_args(['--value', '128'])
print(f'Parsed value: {args.value}')
# Example of invalid input (will raise an error during parse_args)
# try:
# parser.parse_args(['--value', '-1'])
# except SystemExit as e:
# print(f'Error: {e}')