argparse-ext
argparse-ext is a Python library that extends the standard `argparse` module, providing additional argument types and features for command-line interface parsing. It offers types like path, URL, JSON, email, and utilities for subcommands and config files. The current version is 1.4.2, and it maintains a steady, though not rapid, release cadence.
Common errors
-
ValueError: invalid choice: 'path' (choose from 'str', 'int', 'float', ...)
cause Attempting to use an `argparse-ext` custom type (like 'path', 'url', 'json') with the standard `argparse.ArgumentParser`.fixYou must import and use `argparse_ext.ArgumentParser`. Change `from argparse import ArgumentParser` to `from argparse_ext import ArgumentParser`. -
AttributeError: 'str' object has no attribute 'absolute'
cause The argument processed with `type='path'` (or similar extended type) was not correctly converted into its corresponding object (e.g., `pathlib.Path`). This usually happens because the standard `argparse.ArgumentParser` was used, returning a string.fixVerify that you are importing and using `argparse_ext.ArgumentParser`. The custom type conversion only occurs when using `argparse-ext`'s specialized parser.
Warnings
- gotcha Ensure you use `argparse_ext.ArgumentParser` when utilizing extended argument types (e.g., `type='path'`, `type='url'`). Standard `argparse.ArgumentParser` does not recognize these custom types and will raise a `ValueError`.
- gotcha Extended types parse arguments into specific Python objects, not just strings. For example, `type='path'` becomes a `pathlib.Path` object, and `type='url'` becomes a `urllib.parse.ParseResult` object. Do not assume they remain simple strings.
- gotcha When using `add_subcommand`, ensure that the subcommand name does not conflict with any existing arguments or built-in methods of the `ArgumentParser`. While rare, such conflicts can lead to unexpected parsing behavior or errors.
Install
-
pip install argparse-ext
Imports
- ArgumentParser
from argparse import ArgumentParser
from argparse_ext import ArgumentParser
Quickstart
from argparse_ext import ArgumentParser
parser = ArgumentParser(prog='my_cli_tool')
parser.add_argument('--path', type='path', help='A path argument which becomes a pathlib.Path object')
parser.add_argument('--url', type='url', help='A URL argument which becomes a urllib.parse.ParseResult object')
parser.add_argument('--config', type='json', help='A JSON string which is parsed into a Python object')
args = parser.parse_args(['--path', '/tmp/foo.txt', '--url', 'http://example.com/foo', '--config', '{"key": "value"}']) # Simulate args for quickstart
print(f"Path object type: {type(args.path)}, absolute: {args.path.absolute()}")
print(f"URL object type: {type(args.url)}, scheme: {args.url.scheme}")
print(f"Config object type: {type(args.config)}, value: {args.config['key']}")