Skip to main content

Automatically generate CLI from Pydantic models

Project description

pydantic-autocli

Automatically generate CLI applications from Pydantic models.

Installation

# Using pip
pip install pydantic-autocli

# Using uv
uv pip install pydantic-autocli

Development

# Install development dependencies
uv sync --dev

# Run tests
uv run pytest

# Or using taskipy
uv run task test

Usage

from pydantic import BaseModel
from pydantic_autocli import AutoCLI, param

class MyCLI(AutoCLI):
    class CommonArgs(AutoCLI.CommonArgs):
        # Common arguments for all commands
        verbose: bool = param(False, description="Enable verbose output")

    class FooArgs(CommonArgs):
        # Arguments specific to 'foo' command
        name: str = param(..., l="--name", s="-n")
        count: int = param(1, l="--count", s="-c")

    def run_foo(self, args):
        """Run the foo command"""
        print(f"Running foo with name={args.name}, count={args.count}")
        if args.verbose:
            print("Verbose mode enabled")

    class BarArgs(CommonArgs):
        # Arguments specific to 'bar' command
        file: str = param(..., l="--file", s="-f")
        mode: str = param("read", l="--mode", s="-m", choices=["read", "write", "append"])

    def run_bar(self, args):
        """Run the bar command"""
        print(f"Running bar with file={args.file}, mode={args.mode}")
        if args.verbose:
            print("Verbose mode enabled")

if __name__ == "__main__":
    cli = MyCLI()
    cli.run()

Features

  • Automatically generate CLI commands from class methods
  • Map Pydantic model fields to CLI arguments
  • Customize CLI arguments with the param function:
    • l: Long form argument (e.g., l="--name")
    • s: Short form argument (e.g., s="-n")
    • choices: List of allowed values (e.g., choices=["read", "write", "append"])
  • Automatically handle help text generation
  • Support for common arguments across all commands
  • Support for async commands

The param Function

The library provides a param function to create CLI arguments in a more concise way:

from pydantic_autocli import param

# Basic usage
name: str = param(..., l="--name", s="-n")

# With default value
count: int = param(1, l="--count", s="-c")

# With choices
mode: str = param("read", l="--mode", s="-m", choices=["read", "write", "append"])

# With additional Field parameters
verbose: bool = param(False, description="Enable verbose output")

Note that param is just a convenience function that internally uses Pydantic's Field. You can also use Field directly if you prefer:

from pydantic import BaseModel, Field

class MyArgs(BaseModel):
    # Using param (recommended)
    name1: str = param("default", l="--name1", s="-n1")
    
    # Using Field directly
    name2: str = Field("default", json_schema_extra={"l": "--name2", "s": "-n2"})

Both approaches are valid and will work the same way. The param function is provided to make the code more readable and maintainable.

Type Annotation Support

pydantic-autocli now supports two ways to define CLI argument classes:

1. Using Type Annotations

You can directly specify the argument class using type annotations:

from pydantic import BaseModel
from pydantic_autocli import AutoCLI, param

class MyCLI(AutoCLI):
    # Define a model to use with annotations
    class CustomArgs(BaseModel):
        value: int = param(42, l="--value", s="-v")
        flag: bool = param(False, l="--flag", s="-f")
    
    # Use type annotation to specify args class
    def run_command(self, args: CustomArgs):
        print(f"Value: {args.value}")
        if args.flag:
            print("Flag is set")
        return True

2. Using Naming Convention (Traditional)

The traditional naming convention continues to work:

class MyCLI(AutoCLI):
    # Args class named after command (CommandArgs)
    class CommandArgs(AutoCLI.CommonArgs):
        name: str = param("default", l="--name", s="-n")
    
    def run_command(self, args):
        print(f"Name: {args.name}")
        return True

Resolution Priority

pydantic-autocli uses the following priority order to determine which argument class to use:

  1. Type annotation on the method parameter
  2. Naming convention (CommandArgs class for run_command method)
  3. Fall back to CommonArgs

Testing

To run the tests:

# Install development dependencies and run tests
uv sync
uv run pytest

# Or using taskipy
uv run task test

Examples

To run the example CLI:

# Run the example directly
python examples/simple.py

# Or using taskipy
uv run task example

License

See LICENSE file.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

pydantic_autocli-0.1.2.tar.gz (52.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

pydantic_autocli-0.1.2-py3-none-any.whl (10.0 kB view details)

Uploaded Python 3

File details

Details for the file pydantic_autocli-0.1.2.tar.gz.

File metadata

  • Download URL: pydantic_autocli-0.1.2.tar.gz
  • Upload date:
  • Size: 52.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.3

File hashes

Hashes for pydantic_autocli-0.1.2.tar.gz
Algorithm Hash digest
SHA256 6fe45b1e350ebdd78833466f52ef939fedd381b359708ce2bb4528d48f058e14
MD5 1f1ea08010dec529041171bdd69571d3
BLAKE2b-256 32050491c13ccdf3a7e1fd4669f0c10299bd53509249d6ecf14db68d9293be73

See more details on using hashes here.

File details

Details for the file pydantic_autocli-0.1.2-py3-none-any.whl.

File metadata

File hashes

Hashes for pydantic_autocli-0.1.2-py3-none-any.whl
Algorithm Hash digest
SHA256 2a36b44ac901df79669034f9b8ba43eb0e7dbacdd91d9d04223725953e4fd1a8
MD5 52174417cfd2611dda13ce3c7fb67ca9
BLAKE2b-256 5ef3b3ad73a191f31f2c94535df034db31db9273183b4b9e5445eea50d195265

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page