CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-jsonargparse

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

Pending
Overview
Eval results
Files

advanced-actions.mddocs/

Advanced Actions

Specialized action classes for handling complex argument patterns including configuration files, yes/no options, JSON schema validation, Jsonnet processing, and custom validation. These actions extend the standard argparse action system with advanced functionality for sophisticated CLI applications.

Capabilities

Configuration File Action

Action for handling configuration file arguments that can parse and merge configuration from files or strings.

class ActionConfigFile:
    def __init__(self, **kwargs):
        """
        Initialize configuration file action.
        
        Args:
            **kwargs: Standard argparse action keyword arguments
        """
    
    def __call__(self, parser, cfg, values, option_string=None) -> None:
        """
        Process configuration file argument.
        
        Args:
            parser: ArgumentParser instance
            cfg: Current configuration namespace
            values: Configuration file path or string
            option_string: Option string that triggered this action
        """
    
    @staticmethod
    def apply_config(parser, cfg, dest, value) -> None:
        """
        Apply configuration to parser.
        
        Args:
            parser: ArgumentParser instance
            cfg: Configuration namespace to update
            dest: Destination attribute name
            value: Configuration value to apply
        """

Yes/No Action

Action that creates paired boolean options with customizable prefixes for setting True/False values.

class ActionYesNo:
    def __init__(self, yes_prefix: str = "", no_prefix: str = "no_", **kwargs):
        """
        Initialize yes/no action with customizable prefixes.
        
        Args:
            yes_prefix: Prefix for the "yes" option (empty for base name)
            no_prefix: Prefix for the "no" option (default: "no_")
            **kwargs: Standard argparse action keyword arguments
        """
    
    def __call__(self, parser, namespace, values, option_string=None) -> None:
        """
        Process yes/no argument.
        
        Args:
            parser: ArgumentParser instance
            namespace: Namespace to update
            values: Argument values (unused for boolean flags)
            option_string: Option string that triggered this action
        """

Fail Action

Action that always fails with a custom error message, useful for deprecating or disabling options.

class ActionFail:
    def __init__(self, message: str = "option unavailable", **kwargs):
        """
        Initialize fail action with custom error message.
        
        Args:
            message: Error message to display when action is triggered
            **kwargs: Standard argparse action keyword arguments
        """
    
    def __call__(self, parser, namespace, values, option_string=None) -> None:
        """
        Always raise an ArgumentError with the configured message.
        
        Args:
            parser: ArgumentParser instance
            namespace: Namespace (unused)
            values: Argument values (unused)
            option_string: Option string that triggered this action
            
        Raises:
            ArgumentError: Always raised with the configured message
        """

JSON Schema Action

Action for parsing and validating JSON arguments against a JSON schema.

class ActionJsonSchema:
    def __init__(self, schema: Union[str, Dict], **kwargs):
        """
        Initialize JSON schema action.
        
        Args:
            schema: JSON schema as string (path) or dict (schema object)
            **kwargs: Standard argparse action keyword arguments
        """
    
    def __call__(self, parser, namespace, values, option_string=None) -> None:
        """
        Parse and validate JSON against schema.
        
        Args:
            parser: ArgumentParser instance
            namespace: Namespace to update
            values: JSON string or file path to validate
            option_string: Option string that triggered this action
            
        Raises:
            ArgumentError: If JSON is invalid or doesn't match schema
        """

Jsonnet Action

Action for parsing Jsonnet configuration files with optional JSON schema validation.

class ActionJsonnet:
    def __init__(self, **kwargs):
        """
        Initialize Jsonnet action.
        
        Args:
            **kwargs: Standard argparse action keyword arguments plus:
                schema: Optional JSON schema for validation
                ext_vars: External variables for Jsonnet
        """
    
    def __call__(self, parser, namespace, values, option_string=None) -> None:
        """
        Parse Jsonnet file or string.
        
        Args:
            parser: ArgumentParser instance
            namespace: Namespace to update
            values: Jsonnet file path or string
            option_string: Option string that triggered this action
            
        Raises:
            ArgumentError: If Jsonnet parsing fails or validation fails
        """

Parser Action

Action for parsing options with a nested ArgumentParser, optionally loading from files.

class ActionParser:
    def __init__(self, parser: Optional[ArgumentParser] = None, **kwargs):
        """
        Initialize parser action with nested parser.
        
        Args:
            parser: ArgumentParser to use for parsing (created if None)
            **kwargs: Standard argparse action keyword arguments
        """
    
    def __call__(self, parser, namespace, values, option_string=None) -> None:
        """
        Parse values using nested parser.
        
        Args:
            parser: Parent ArgumentParser instance
            namespace: Namespace to update
            values: String or file path to parse
            option_string: Option string that triggered this action
        """

Usage Examples

Configuration File Handling

from jsonargparse import ArgumentParser, ActionConfigFile

parser = ArgumentParser()

# Add configuration file argument
parser.add_argument(
    "--config", 
    action=ActionConfigFile,
    help="Path to configuration file or configuration string"
)

# Add other arguments
parser.add_argument("--name", type=str, default="default")
parser.add_argument("--value", type=int, default=42)

# Parse arguments - config file values are merged
config = parser.parse_args()

print(f"Name: {config.name}")
print(f"Value: {config.value}")

With config file settings.yaml:

name: "from_config"
value: 100

Usage:

# Load from file
python script.py --config settings.yaml --name "override"

# Load from string
python script.py --config '{"name": "json_config", "value": 200}'

Yes/No Options

from jsonargparse import ArgumentParser, ActionYesNo

parser = ArgumentParser()

# Standard yes/no option (--verbose / --no_verbose)
parser.add_argument(
    "--verbose",
    action=ActionYesNo,
    help="Enable verbose output"
)

# Custom prefixes (--enable-debug / --disable-debug)
parser.add_argument(
    "--debug",
    action=ActionYesNo,
    yes_prefix="enable-",
    no_prefix="disable-",
    help="Enable debug mode"
)

config = parser.parse_args()

print(f"Verbose: {config.verbose}")
print(f"Debug: {config.debug}")

Usage:

python script.py --verbose --enable-debug     # Both True
python script.py --no_verbose --disable-debug # Both False
python script.py --verbose --disable-debug    # verbose=True, debug=False

Deprecated Options

from jsonargparse import ArgumentParser, ActionFail

parser = ArgumentParser()

# Current option
parser.add_argument("--output-format", type=str, default="json")

# Deprecated option that fails with helpful message
parser.add_argument(
    "--format",
    action=ActionFail,
    message="Option --format is deprecated. Use --output-format instead."
)

config = parser.parse_args()

Usage:

python script.py --output-format yaml  # Works
python script.py --format json         # Fails with helpful message

JSON Schema Validation

from jsonargparse import ArgumentParser, ActionJsonSchema

# Define JSON schema
user_schema = {
    "type": "object",
    "properties": {
        "name": {"type": "string"},
        "age": {"type": "integer", "minimum": 0},
        "email": {"type": "string", "format": "email"}
    },
    "required": ["name", "age"]
}

parser = ArgumentParser()

# Add JSON argument with schema validation
parser.add_argument(
    "--user",
    action=ActionJsonSchema,
    schema=user_schema,
    help="User information as JSON"
)

config = parser.parse_args()

if config.user:
    print(f"User: {config.user['name']}, Age: {config.user['age']}")

Usage:

# Valid JSON
python script.py --user '{"name": "Alice", "age": 30, "email": "alice@example.com"}'

# Invalid JSON (missing required field)
python script.py --user '{"name": "Bob"}'  # Fails validation

# From file
echo '{"name": "Charlie", "age": 25}' > user.json
python script.py --user user.json

Jsonnet Configuration

from jsonargparse import ArgumentParser, ActionJsonnet

parser = ArgumentParser()

# Add Jsonnet configuration argument
parser.add_argument(
    "--config",
    action=ActionJsonnet,
    help="Jsonnet configuration file or string"
)

parser.add_argument("--name", type=str)
parser.add_argument("--count", type=int)

config = parser.parse_args()

print(f"Name: {config.name}")
print(f"Count: {config.count}")

With Jsonnet file config.jsonnet:

{
  name: "jsonnet_config",
  count: 10 * 5,  // Jsonnet expressions
  computed: "Name is " + self.name
}

Usage:

python script.py --config config.jsonnet

Nested Parser Action

from jsonargparse import ArgumentParser, ActionParser

# Create nested parser for database configuration
db_parser = ArgumentParser()
db_parser.add_argument("--host", type=str, default="localhost")
db_parser.add_argument("--port", type=int, default=5432)
db_parser.add_argument("--username", type=str, required=True)
db_parser.add_argument("--password", type=str, required=True)

# Main parser
parser = ArgumentParser()
parser.add_argument("--app-name", type=str, required=True)

# Add database config as nested parser
parser.add_argument(
    "--database",
    action=ActionParser,
    parser=db_parser,
    help="Database configuration"
)

config = parser.parse_args()

print(f"App: {config.app_name}")
print(f"DB: {config.database.host}:{config.database.port}")

Usage:

# Inline database config
python script.py --app-name MyApp --database "--host db.example.com --port 3306 --username user --password pass"

# Database config from file
echo "--host prod-db --username admin --password secret" > db.conf
python script.py --app-name MyApp --database db.conf

Combining Multiple Actions

from jsonargparse import ArgumentParser, ActionConfigFile, ActionYesNo, ActionFail

parser = ArgumentParser()

# Configuration file support
parser.add_argument("--config", action=ActionConfigFile)

# Yes/no options
parser.add_argument("--verbose", action=ActionYesNo)
parser.add_argument("--debug", action=ActionYesNo)

# Regular arguments
parser.add_argument("--name", type=str, required=True)
parser.add_argument("--count", type=int, default=1)

# Deprecated option
parser.add_argument(
    "--old-count",
    action=ActionFail,
    message="Use --count instead of --old-count"
)

config = parser.parse_args()

if config.verbose:
    print(f"Processing {config.name} with count {config.count}")
if config.debug:
    print("Debug mode enabled")

With config file:

name: "config_name"
count: 5
verbose: true

Usage:

python script.py --config config.yaml --no_verbose --debug

Install with Tessl CLI

npx tessl i tessl/pypi-jsonargparse@4.41.1

docs

advanced-actions.md

cli-creation.md

core-parser.md

index.md

namespace-management.md

settings.md

signature-arguments.md

types-validation.md

utilities.md

tile.json