Skip to main content

Auto-generate Typer CLI interfaces from Pydantic models.

Project description

typantic

CI PyPI Python License

Auto-generate Typer CLI interfaces from Pydantic models.

Define your config once as a Pydantic model with validators, and get a fully-typed CLI for free — no duplication, no drift.

Installation

pip install typantic

Quick start

from pathlib import Path
from typing import Annotated

import typer
from pydantic import AfterValidator, BaseModel, Field

from typantic import pydantic_to_typer


# 1. Define your config with validators
class Config(BaseModel):
    images: Annotated[
        list[Path],
        Field(description="Image folders to process.", kw_only=False),
    ]
    output: Annotated[
        Path,
        AfterValidator(Path.resolve),
        Field(description="Output directory.", kw_only=True),
    ]
    threshold: Annotated[
        float,
        Field(default=0.5, description="Detection threshold.", kw_only=True),
    ]
    seed: Annotated[
        int | None,
        Field(default=None, description="Random seed.", kw_only=True),
    ]


# 2. Use the decorator — that's it
app = typer.Typer()

@app.command()
@pydantic_to_typer(Config)
def run(config: Config):
    """Process images with validation."""
    print(config)

if __name__ == "__main__":
    app()
$ python example.py --help

 Usage: example.py [OPTIONS] IMAGES...

 Process images with validation.

╭─ Arguments ──────────────────────────────────────────────────╮
│ *  images  IMAGES...  Image folders to process.  [required]  │
╰──────────────────────────────────────────────────────────────╯
╭─ Options ────────────────────────────────────────────────────╮
│ *  --output     PATH     Output directory.  [required]       │
│    --threshold  FLOAT    Detection threshold.  [default: 0.5]│
│    --seed       INTEGER  Random seed.  [default: (None)]     │
│    --help                Show this message and exit.         │
╰──────────────────────────────────────────────────────────────╯

How it works

The @pydantic_to_typer(Model) decorator:

  1. Reads Model.model_fields to discover field names, types, descriptions, and defaults
  2. Strips Annotated validator metadata to extract the base types Typer understands
  3. Maps kw_only=Falsetyper.Argument, kw_only=Truetyper.Option
  4. Rewrites the function's __signature__ so Typer sees the expanded parameters
  5. At call time, passes the raw CLI values into Model(...) so all Pydantic validators run

Your function receives the validated model instance — validators, default_factory, union types, and everything else works exactly as in Pydantic.

Features

Pydantic CLI result
kw_only=False typer.Argument (positional)
kw_only=True or unset typer.Option (--flag)
Field(description=...) help=... in the CLI
Field(default=...) Default value shown in --help
Field(default_factory=...) Factory called once at decoration time
int | None Optional CLI option
default=None Rendered as [default: (None)]
list[Path] Variadic positional argument
AfterValidator, BeforeValidator Run at call time via Pydantic

Help panels for mixin-composed models

Large configs composed from mixins can group their options into titled Rich help panels. Opt in with subpanels=True and give each mixin a cli_panel class attribute — every option lands in the panel of the class that defines its field:

from typing import Annotated, ClassVar

from pydantic import BaseModel, Field

from typantic import pydantic_to_typer


class ComputeMixin(BaseModel):
    cli_panel: ClassVar[str] = "Compute"

    cpus: Annotated[int, Field(default=4, description="CPU count.")]


class Config(ComputeMixin):
    dry_run: Annotated[bool, Field(default=False, description="Dry run.")]


@app.command()
@pydantic_to_typer(Config, subpanels=True)
def run(config: Config): ...
$ python example.py --help

 Usage: example.py [OPTIONS]

╭─ Options ──────────────────────────────────────────────────────╮
│ --dry-run    --no-dry-run    Dry run.  [default: no-dry-run]   │
│ --help                       Show this message and exit.       │
╰────────────────────────────────────────────────────────────────╯
╭─ Compute ──────────────────────────────────────────────────────╮
│ --cpus        INTEGER        CPU count.  [default: 4]          │
╰────────────────────────────────────────────────────────────────╯

--cpus renders under a "Compute" panel; --dry-run stays in the default options group (its defining class declares no cli_panel). Arguments are never panelled.

Requirements

  • Python ≥ 3.12
  • Pydantic ≥ 2.0
  • Typer ≥ 0.26

License

MIT

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

typantic-0.2.1.tar.gz (5.8 kB view details)

Uploaded Source

Built Distribution

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

typantic-0.2.1-py3-none-any.whl (6.3 kB view details)

Uploaded Python 3

File details

Details for the file typantic-0.2.1.tar.gz.

File metadata

  • Download URL: typantic-0.2.1.tar.gz
  • Upload date:
  • Size: 5.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for typantic-0.2.1.tar.gz
Algorithm Hash digest
SHA256 7c04ba27bf8230057be6d8c52c6494b0fc3a39fda3842038f776619997d9d474
MD5 97f6e121f848d97accee40ed867130da
BLAKE2b-256 f164a9bc65483dbf5f648183eeb7bdeb22140c10d94ffed4155da0fe657eaeb8

See more details on using hashes here.

Provenance

The following attestation bundles were made for typantic-0.2.1.tar.gz:

Publisher: publish.yml on KiSchnelle/typantic

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file typantic-0.2.1-py3-none-any.whl.

File metadata

  • Download URL: typantic-0.2.1-py3-none-any.whl
  • Upload date:
  • Size: 6.3 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.12

File hashes

Hashes for typantic-0.2.1-py3-none-any.whl
Algorithm Hash digest
SHA256 2236c3d98bb20fbfcd04ae09ed86115e1c9d9cac87edbb25ea0de4313fffec0b
MD5 562bd5c2e5a689c42ebd644f7b253015
BLAKE2b-256 13232eef813e8fa13ccc8bf9b3e0a313648bf4f2d52b2dd19870bfefe99837ae

See more details on using hashes here.

Provenance

The following attestation bundles were made for typantic-0.2.1-py3-none-any.whl:

Publisher: publish.yml on KiSchnelle/typantic

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

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