Typed Argument Parser (Tap)
Typed Argument Parser (Tap) is a Python library that modernizes `argparse` by leveraging type hints for command-line argument parsing. It offers benefits like static type checking, code completion, and improved source code navigation. Additionally, it provides `tapify`, a function inspired by Google's Python Fire, to effortlessly run functions or initialize classes directly from command-line arguments while automatically handling type conversions. Currently at version 1.12.0, Tap is actively developed with a regular release cadence, supporting Python 3.10 and newer.
Warnings
- breaking Version 1.12.0 (and newer) drops support for Python 3.9. Users on Python 3.9 must upgrade their Python version to 3.10 or newer, or pin `typed-argument-parser` to an older version.
- breaking Version 1.10.1 refactored the project structure, moving code from `tap/` to `src/tap` and `setup.py` to `pyproject.toml`. While direct imports are generally unaffected (`from tap import ...`), this might impact users with custom build systems or those relying on internal package structure.
- gotcha When using `tapify` to run functions or initialize classes, by default it will raise an error if additional, unneeded arguments are provided on the command line. To ignore extra arguments, use `known_only=True`.
- gotcha The behavior for handling reproducibility information's `repo_path` changed in v1.7.1. By default, it now uses the git repository of the directory containing the executed file, rather than the current working directory.
- gotcha Boolean arguments (e.g., `arg: bool = False`) are set to `True` by merely including the `--arg` flag. If `arg: bool = True`, `--arg` sets it to `False`. For explicit `True`/`False` values on the command line (e.g., `--arg True`), `explicit_bool=True` must be passed to `parse_args()`.
Install
-
pip install typed-argument-parser
Imports
- Tap
from tap import Tap
- tapify
from tap import tapify
- TapIgnore
from tap import TapIgnore
- Positional
from tap import Positional
Quickstart
from tap import Tap
class SimpleArgumentParser(Tap):
name: str # Your name
language: str = 'Python' # Programming language
package: str = 'Tap' # Package name
stars: int # Number of stars
max_stars: int = 5 # Maximum stars
if __name__ == '__main__':
args = SimpleArgumentParser().parse_args()
print(f'My name is {args.name} and I give the {args.language} package '
f'{args.package} {args.stars}/{args.max_stars} stars!')