Skip to content

Tutorial

In this tutorial you build weather.py, a small CLI whose settings are nested Pydantic models. It takes about ten minutes. You need CoTyper installed.

1. A first command

Start with one model and one command:

weather.py
from pydantic import BaseModel

from cotyper import App

app = App(name="weather")


class Location(BaseModel):
    city: str
    country: str = "DE"


@app.struct_command("forecast")
def forecast(location: Location):
    """Print a (fake) forecast."""
    print(f"Forecast for {location.city}, {location.country}")


if __name__ == "__main__":
    app()

App works like typer.Typer. The difference is struct_command: it sees that location is a BaseModel and creates one option per field, named --<argument>-<field>:

$ python weather.py --location-city Hannover
Forecast for Hannover, DE

city has no default, so --location-city is required. country defaults to DE.

Tip

With a single command, Typer runs it directly. After you add a second command (step 5), you call it by name: python weather.py forecast ....

2. Nesting models

Models can contain models. Group everything in a Settings model:

from typing import Literal


class Output(BaseModel):
    units: Literal["metric", "imperial"] = "metric"
    days: int = 1
    coords: tuple[float, float] = (52.37, 9.73)


class Settings(BaseModel):
    location: Location
    output: Output = Output()
    verbose: bool = False


@app.struct_command("forecast")
def forecast(settings: Settings):
    """Print a (fake) forecast."""
    loc, out = settings.location, settings.output
    print(
        f"{out.days} day(s) for {loc.city}, {loc.country} in {out.units} at {out.coords}"
    )

The option names follow the path through the models, and each type is parsed:

$ python weather.py --settings-location-city Hannover \
    --settings-output-days 3 \
    --settings-output-units imperial \
    --settings-output-coords 1.5,2
3 day(s) for Hannover, DE in imperial at (1.5, 2.0)
  • Literal only accepts the listed values.
  • tuple and list values are comma separated, not repeated flags.
  • bool becomes a flag pair: --settings-verbose / --no-settings-verbose.

3. Help text from docstrings

CoTyper reads the Args: section of a model's Google-style docstring and uses it as option help:

class Location(BaseModel):
    """
    Where to look up the weather.

    Args:
        city: Name of the city.
        country: ISO country code.
    """

    city: str
    country: str = "DE"

--help groups the options into panels named after the first part of the option name, here Settings:

$ python weather.py --help
╭─ Settings ───────────────────────────────────────────────────────────────╮
│ *  --settings-location-city     TEXT              Name of the city.      │
│                                                   [required]             │
│    --settings-location-country  TEXT              ISO country code.      │
│                                                   [default: DE]          │
│    --settings-output-units      LITERAL['METRIC', 'IMPERIAL']  ...       │
│    ...                                                                   │
╰──────────────────────────────────────────────────────────────────────────╯

4. Reading settings from a file

Long command lines get tedious. With add_config_file_option, the command gets an extra option that loads arguments from a JSON, TOML or YAML file (or an inline JSON string):

@app.struct_command("forecast", add_config_file_option="config")
def forecast(settings: Settings): ...

The file has the same shape as the function arguments. The format is picked by the file suffix: .json, .toml or .yaml/.yml.

settings.json
{"settings": {"location": {"city": "Hannover"}, "output": {"days": 3}}}
settings.toml
[settings.location]
city = "Hannover"

[settings.output]
days = 3
settings.yaml
settings:
  location:
    city: Hannover
  output:
    days: 3

YAML support needs PyYAML: pip install "cotyper[yaml]".

$ python weather.py --config settings.json
3 day(s) for Hannover, DE in metric at (52.37, 9.73)

Values from the file become defaults, so you can still override them on the command line:

$ python weather.py --config settings.json --settings-output-days 5
5 day(s) for Hannover, DE in metric at (52.37, 9.73)

5. Shorter option names with unfold_cls

If the whole command takes one settings object, the --settings- prefix is noise. unfold_cls lifts the model's fields up to function arguments:

from cotyper import App, unfold_cls


@app.struct_command("flat")
@unfold_cls(Settings)
def flat(settings: Settings):
    """Same forecast, shorter option names."""
    print(settings)
$ python weather.py flat --location-city Berlin --verbose
location=Location(city='Berlin', country='DE') output=Output(units='metric', days=1, coords=(52.37, 9.73)) verbose=True

In --help the options are now grouped into Location and Output panels. Your function still receives a complete Settings instance. @unfold_cls must sit below @app.struct_command.

6. The complete app

weather.py
--8 < --"examples/tutorial.py"
$ python weather.py --help            # lists: forecast, flat
$ python weather.py forecast --help

Next steps

  • The Guide covers naming rules, all supported types and lists of models.
  • examples/extensive.py in the repository exercises every supported type.