Targ
Targ is a Python library that simplifies the creation of command-line interfaces (CLIs) for applications, leveraging Python's type hints and docstrings. It automatically generates CLI arguments and help text from function signatures, reducing boilerplate. The current version is 0.6.0. It maintains an active release cadence, with recent updates focusing on modern Python version support and type annotation syntax.
Common errors
-
ModuleNotFoundError: No module named 'targ'
cause The 'targ' library is not installed in your current Python environment.fixRun `pip install targ` to install the library. -
Error: the following arguments are required: NAME_OF_ARGUMENT
cause A required argument for your `targ`-generated CLI command was not provided when executing the script. `targ` infers required arguments from function parameters without default values.fixEnsure all required arguments are provided. For example, if your function is `def my_command(arg1: str):`, you must run `python your_script.py my_command VALUE_FOR_ARG1`. -
ValueError: invalid literal for int() with base 10: 'abc'
cause The value provided from the command line for a function argument does not match the expected Python type hint (e.g., a string was provided for an `int` parameter).fixProvide arguments in the format expected by their type hints. For an `int` argument, pass a number like `123`, not text like `'one hundred twenty three'`.
Warnings
- breaking Python 3.8 support was officially dropped in `targ` version 0.5.0. Projects using Python 3.8 or older will need to update their Python version to 3.9 or newer to use `targ` >= 0.5.0.
- breaking Python 3.7 support was officially dropped in `targ` version 0.4.0. Projects on Python 3.7 must remain on `targ` versions prior to 0.4.0 or upgrade their Python environment.
- gotcha `targ` versions 0.6.0 and above support the new `str | None` union type syntax in type hints. While `Optional[str]` (from `typing`) still works, ensure consistency in your codebase and be aware of potential syntax errors if using the new union syntax with older Python versions (<3.10) not supported by `targ`.
- gotcha When an exception occurs during command execution, `targ` CLI will often suppress the full traceback by default for a cleaner user experience. To view the full stack trace for debugging purposes, append `--trace` to your CLI command.
Install
-
pip install targ
Imports
- CLI
from targ import CLI
Quickstart
from targ import CLI
def greet(name: str, greeting: str = "Hello"):
"""
Say hello to someone with an optional greeting.
:param name: The name of the person to greet.
:param greeting: The greeting message. Defaults to 'Hello'.
"""
print(f"{greeting}, {name}!")
if __name__ == "__main__":
# To run: python your_script.py greet --name World
# Or: python your_script.py greet --name Alice --greeting Hi
CLI(greet)()