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.1.tar.gz (50.6 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.1-py3-none-any.whl (8.5 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: pydantic_autocli-0.1.1.tar.gz
  • Upload date:
  • Size: 50.6 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.1.tar.gz
Algorithm Hash digest
SHA256 60a1e7e4dd532515b40e5f9638f68b570b348c91f81284fecbf7ed9b8e128d22
MD5 371d9d00d17add218f29167e992ef11e
BLAKE2b-256 c7c03e909e3a4e8eb213ba5e758521f71cb69dcee4b7ee3a73df1f2986039065

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for pydantic_autocli-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 d1d90d134789550716b2601d2b829db3444ff44a9114301b2c31f60df0a9d2e0
MD5 c1f6e090cc32d0cc49b1a2ea84d8fca1
BLAKE2b-256 de2a48847e47b58a6a1516945cfb3c4c8d90da342ad5f5dc261a2f1a8d6e8fc6

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