jsonargparse
jsonargparse is a Python library that extends `argparse` to simplify the creation of Command-Line Interfaces (CLIs) and make Python applications easily configurable. It allows parsing configuration options from command line arguments, config files (JSON, YAML, Jsonnet, TOML), and environment variables, leveraging type hints for validation. It is a well-maintained project with frequent releases, adhering to high standards of development, including semantic versioning, deprecation periods, changelog, automated testing, and full test coverage.
Warnings
- breaking In `jsonargparse` v4.0.0, the default error handling behavior of `ArgumentParser` changed. It now raises a `ParserError` by default on parsing failure instead of printing usage and exiting the program. Additionally, `error_handler` and `formatter_class` arguments no longer accept string values.
- breaking The internal `SimpleNamespace` class was replaced by `Namespace` in `jsonargparse` v4.0.0 to align more closely with `argparse`. Code directly interacting with `jsonargparse.namespace.SimpleNamespace` might break.
- gotcha Using `type=bool` directly in `add_argument` for boolean flags in standard `argparse` (and by extension, potentially `jsonargparse` if not careful) does not behave as expected for command-line parsing, as it treats any non-empty string as `True`. `jsonargparse` provides `ActionYesNo` for clear boolean handling.
- gotcha The `ArgumentParser.parse_known_args()` method is intentionally not implemented in `jsonargparse` to prevent typos in configuration files or arguments from going unnoticed. If `parse_known_args` were allowed, unknown arguments would be silently ignored, potentially hiding critical configuration errors.
- gotcha By default, `ArgumentParser.parse_args()` does not check environment variables. You must explicitly enable this behavior.
Install
-
pip install jsonargparse -
pip install "jsonargparse[all]"
Imports
- ArgumentParser
from jsonargparse import ArgumentParser
- CLI
from jsonargparse import CLI
- auto_cli
from jsonargparse import auto_cli
Quickstart
from jsonargparse import CLI
def main(name: str, greeting: str = 'Hello') -> None:
"""
A simple command-line interface function.
Args:
name: The name of the person to greet.
greeting: The greeting message to use.
"""
print(f'{greeting}, {name}!')
if __name__ == '__main__':
# Run this from the command line:
# python your_script.py --name World
# python your_script.py --name Alice --greeting Hi
CLI(main)