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.3.tar.gz (52.7 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.3-py3-none-any.whl (10.3 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: pydantic_autocli-0.1.3.tar.gz
  • Upload date:
  • Size: 52.7 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.3.tar.gz
Algorithm Hash digest
SHA256 f3b9eee2fc5f9282d80921f348f9f871b2807cf94f56f6e9f17c73c157e24d04
MD5 b22c1cf114b079fb3d2e75c8850bf232
BLAKE2b-256 d6cd1a095a08d6518350f41f71c82b1a85b43e02bb37b5dbd19fb9ce9e51b10c

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for pydantic_autocli-0.1.3-py3-none-any.whl
Algorithm Hash digest
SHA256 817529e0e2a2311c57f0ceb46442ba1eb4689b7db89dadf897d9539757f469a0
MD5 9d94e2326e5d3f0af49fc7792ccc103f
BLAKE2b-256 725a963dfa62299a88c898f0a6f4a2c936a8e1c7913b5b6a2c44d939fdacde86

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