or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

advanced-actions.mdcli-creation.mdcore-parser.mdindex.mdnamespace-management.mdsettings.mdsignature-arguments.mdtypes-validation.mdutilities.md
tile.json

tessl/pypi-jsonargparse

Implement minimal boilerplate CLIs derived from type hints and parse from command line, config files and environment variables.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/jsonargparse@4.41.x

To install, run

npx @tessl/cli install tessl/pypi-jsonargparse@4.41.0

index.mddocs/

Jsonargparse

A comprehensive Python library for creating command-line interfaces (CLIs) derived from type hints. Jsonargparse enables developers to build powerful, configurable Python applications with minimal boilerplate code by automatically generating argument parsers from function and class signatures. It supports parsing from command line arguments, configuration files (YAML, JSON, TOML, Jsonnet), and environment variables simultaneously, making it ideal for machine learning frameworks, data processing pipelines, and any Python application requiring sophisticated configuration management.

Package Information

  • Package Name: jsonargparse
  • Language: Python
  • Installation: pip install jsonargparse
  • Documentation: https://jsonargparse.readthedocs.io/en/stable/

Core Imports

import jsonargparse
from jsonargparse import ArgumentParser, CLI, auto_cli

Common patterns:

# For manual parser creation
from jsonargparse import ArgumentParser, Namespace

# For automatic CLI creation  
from jsonargparse import auto_cli, CLI

# For signature-based arguments
from jsonargparse import SignatureArguments

# For advanced features
from jsonargparse import ActionConfigFile, ActionYesNo, lazy_instance

Basic Usage

Automatic CLI Creation

from jsonargparse import auto_cli

def main(
    name: str,
    age: int = 25,
    verbose: bool = False
) -> None:
    """Simple CLI function.
    
    Args:
        name: Person's name
        age: Person's age
        verbose: Enable verbose output
    """
    if verbose:
        print(f"Processing for {name}, age {age}")
    else:
        print(f"Hello {name}!")

if __name__ == "__main__":
    # Automatically creates CLI from function signature
    auto_cli(main)

Manual Parser Creation

from jsonargparse import ArgumentParser

# Create parser
parser = ArgumentParser(
    prog="myapp",
    description="My application",
    env_prefix="MYAPP_",
    default_config_files=["~/.myapp.yaml"]
)

# Add arguments
parser.add_argument("--name", type=str, required=True, help="Person's name")
parser.add_argument("--age", type=int, default=25, help="Person's age")
parser.add_argument("--verbose", action="store_true", help="Enable verbose output")

# Parse arguments
config = parser.parse_args()
print(f"Hello {config.name}!")

Configuration File Support

from jsonargparse import ArgumentParser

parser = ArgumentParser()
parser.add_argument("--config", action="config_file", help="Path to config file")
parser.add_argument("--name", type=str)
parser.add_argument("--age", type=int, default=25)

# Can parse from command line and config file
# python script.py --config config.yaml --name Alice
config = parser.parse_args()

Architecture

Jsonargparse builds upon Python's argparse with several key enhancements:

  • Enhanced ArgumentParser: Extends argparse.ArgumentParser with configuration file support, environment variable parsing, and advanced type handling
  • Namespace Objects: Nested namespace support with dictionary-like access and serialization capabilities
  • Signature Integration: Automatic argument creation from function, method, and class signatures using type hints
  • Action System: Extensible action classes for complex argument handling patterns
  • Type System: Comprehensive support for Python type hints including generics, unions, and custom classes
  • Configuration Sources: Unified parsing from multiple sources with precedence handling

Capabilities

Core Parser Functionality

The ArgumentParser class provides the foundation for all argument parsing with support for multiple configuration sources, advanced type handling, and nested configurations.

class ArgumentParser:
    def __init__(self, 
        env_prefix: Union[bool, str] = True,
        formatter_class: Type = DefaultHelpFormatter,
        exit_on_error: bool = True,
        logger: Union[bool, str, dict, logging.Logger] = False,
        version: Optional[str] = None,
        print_config: Optional[str] = "--print_config",
        parser_mode: str = "yaml",
        default_config_files: Optional[List[Union[str, os.PathLike]]] = None,
        **kwargs
    ): ...
    
    def parse_args(self, args: Optional[List[str]] = None) -> Namespace: ...
    def parse_path(self, cfg_path: Union[str, os.PathLike]) -> Namespace: ...
    def parse_string(self, cfg_str: str) -> Namespace: ...
    def dump(self, cfg: Optional[Namespace] = None, **kwargs) -> str: ...
    def save(self, cfg: Namespace, path: Union[str, os.PathLike], **kwargs) -> None: ...

Core Parser

Automatic CLI Creation

Functions for creating command-line interfaces automatically from function and class signatures with minimal boilerplate code.

def auto_cli(
    components: Optional[Union[Callable, List, Dict]] = None,
    args: Optional[List[str]] = None,
    as_positional: bool = True,
    fail_untyped: bool = True,
    **kwargs
) -> Any: ...

def CLI(*args, **kwargs) -> Any: ...  # Alias of auto_cli

def auto_parser(
    components: Optional[Union[Callable, List, Dict]] = None,
    **kwargs
) -> ArgumentParser: ...

CLI Creation

Signature-Based Arguments

Tools for adding arguments based on function, method, and class signatures with automatic type detection and documentation generation.

class SignatureArguments:
    def add_class_arguments(self, 
        theclass: Type,
        nested_key: Optional[str] = None,
        as_group: bool = True,
        skip: Optional[Set[str]] = None,
        **kwargs
    ) -> List[str]: ...
    
    def add_method_arguments(self, 
        theclass: Type,
        themethod: str,
        **kwargs
    ) -> List[str]: ...
    
    def add_function_arguments(self,
        function: Callable,
        **kwargs
    ) -> List[str]: ...

def compose_dataclasses(*dataclasses: Type) -> Type: ...

Signature Arguments

Namespace and Configuration Management

Enhanced namespace objects with nested structure support, serialization capabilities, and configuration manipulation tools.

class Namespace:
    def __init__(self, *args, **kwargs): ...
    def __getitem__(self, key: str) -> Any: ...
    def __setitem__(self, key: str, value: Any) -> None: ...
    def as_dict(self) -> Dict[str, Any]: ...
    def clone(self) -> "Namespace": ...
    def update(self, value: Union["Namespace", Any]) -> "Namespace": ...
    def get(self, key: str, default: Any = None) -> Any: ...

def dict_to_namespace(obj: Dict[str, Any]) -> Namespace: ...
def strip_meta(cfg: Union[Namespace, Dict]) -> Union[Namespace, Dict]: ...

Namespace Management

Advanced Actions

Specialized action classes for handling complex argument patterns including configuration files, yes/no options, and custom validation.

class ActionConfigFile:
    def __init__(self, **kwargs): ...

class ActionYesNo:
    def __init__(self, yes_prefix: str = "", no_prefix: str = "no_", **kwargs): ...

class ActionFail:
    def __init__(self, message: str = "option unavailable", **kwargs): ...

class ActionJsonSchema:
    def __init__(self, schema: Union[str, Dict], **kwargs): ...

class ActionJsonnet:
    def __init__(self, **kwargs): ...

Advanced Actions

Utilities and Type Support

Utility functions and classes for path handling, lazy instantiation, and advanced type support.

class Path:
    def __init__(self, path: Union[str, os.PathLike], mode: str = "fr"): ...
    def __str__(self) -> str: ...
    @property
    def absolute(self) -> pathlib.Path: ...

def lazy_instance(init_fn: Callable[[], Any]) -> Any: ...
def capture_parser() -> ArgumentParser: ...
def class_from_function(function: Callable, *args, **kwargs) -> Type: ...

Utilities

Configuration and Settings

Functions for customizing parsing behavior, loader/dumper settings, and global configuration options.

def set_parsing_settings(
    validation: Optional[bool] = None,
    docstring_parser: Optional[str] = None,
    parse_as_dict: Optional[bool] = None,
    **kwargs
) -> None: ...

def set_loader(mode: str, loader: Callable[[str], Any]) -> None: ...
def set_dumper(mode: str, dumper: Callable[[Any], str]) -> None: ...  
def get_loader(mode: str) -> Callable[[str], Any]: ...
def get_dumper(mode: str) -> Callable[[Any], str]: ...

Settings

Types and Validation

Advanced type system with built-in validators, custom type registration, and predefined types for common validation patterns.

def register_type(custom_type: Type, serializer: Optional[Callable] = None) -> None: ...
def restricted_number_type(base_type: Union[Type[int], Type[float]], **kwargs) -> Type: ...
def restricted_string_type(pattern: Optional[str] = None, **kwargs) -> Type: ...
def path_type(mode: str) -> Type: ...

# Predefined numeric types
PositiveInt: Type
PositiveFloat: Type
NonNegativeInt: Type
NonNegativeFloat: Type
ClosedUnitInterval: Type
OpenUnitInterval: Type

# Predefined string types
NotEmptyStr: Type
Email: Type
SecretStr: Type

# Predefined path types
Path_fr: Type
Path_fc: Type
Path_dw: Type
Path_dc: Type
Path_drw: Type

Types and Validation

Types

# Import types from argparse
from argparse import ArgumentError, OPTIONAL, REMAINDER, SUPPRESS, PARSER, ONE_OR_MORE, ZERO_OR_MORE

# Core namespace type
from typing import Union, Optional, List, Dict, Any, Callable, Type