Skip to content

Guide

How it works

@app.struct_command does three things:

  1. Unfold. It walks the function signature. It replaces every BaseModel argument, recursively, with one keyword argument per leaf field, and gives each a matching Click type (see Supported types).
  2. Register. It passes the generated function to typer.Typer.command, so the CLI is built by Typer as usual.
  3. Fold. When the command runs, it groups the parsed values by prefix, builds and validates the model instances with Pydantic, and calls your original function.

Your function always receives real, validated model instances.

Naming rules

Python CLI option
def f(config: Config) → config.user_name --config-user-name
nested: config.meta.date --config-meta-date
bool field config.verbose --config-verbose / --no-config-verbose
with @unfold_cls(Config): config.user_name --user-name

Underscores become dashes. In --help, options are grouped into panels by the first part of their name: all --config-* options land in a Config panel, unfolded --meta-* options in a Meta panel.

The top of each model's panel shows a description. It comes from the parameter's entry in the command's Args: docstring section, or else from the model class's docstring. Each command shows its own descriptions, even when two commands share a panel name. Help panels of plain Typer commands are not changed.

Supported types

Field type CLI input
str, int, float --x 1.5
bool --x / --no-x
datetime.datetime --x 2024-01-31 or --x 2024-01-31T12:00:00
datetime.date, datetime.time --x 2024-01-31, --x 12:30
datetime.timedelta --x PT1H or --x 01:30:00
Enum, IntEnum --x red (the member's value)
pathlib.Path, uuid.UUID --x ./data
Decimal, bytes --x 1.50
other pydantic-validated types, e.g. SecretStr, HttpUrl, IPv4Address --x https://example.org
Literal["a", "b"], Literal[1, 2] --x a
list[T], set[T], frozenset[T] of any type above --x 1,2,3
tuple[float, float], tuple[int, ...] --x 1.0,2.0
Union[tuple[float, float], float] --x 1.0,2.0 or --x 1.0
Union[int, str], Union[date, int] --x 5 (members are tried in order)
dict[K, V]: K a scalar (str, int, float, bool, Enum, Literal, date, UUID, Path, ...), V any type above or a BaseModel --x '{"1": "one"}'
nested BaseModel, dataclass or TypedDict unfolded into --x-<field> options, see Dataclasses and TypedDicts
list[BaseModel] --x '{"a": 1},{"a": 2}' (needs parse_json_fields)
Optional[...] of the above same, and the field may be omitted

Types that Typer cannot parse by itself (date, timedelta, Decimal, SecretStr, …) are passed through as strings and validated by Pydantic, using its usual parsing rules. Collections of collections (e.g. list[list[int]]) are not supported, because the comma is already used to separate the outer items.

Dict keys come from JSON object keys, which are always strings, so the key type must be something a string converts to. Containers or models as keys (dict[tuple[int, int], V]) raise UnsupportedTypeError when the command is defined.

examples/new_types.py in the repository has a runnable command for each of these types.

Dataclasses and TypedDicts

Parameters can also be standard-library or pydantic dataclasses, or TypedDicts. They're unfolded into options just like pydantic models, and the command receives instances of the original types:

@dataclasses.dataclass
class Address:
    """Where to send things."""

    city: str
    zip_code: str = "00000"


class Limits(TypedDict, total=False):
    cpu: int
    memory: int


@app.struct_command("ship")
def ship(
    address: Address, limits: Limits, backup: Address | None = None
): ...  # address is an Address, limits a dict
python app.py --address-city Oslo --limits-cpu 2

Nested dataclasses and TypedDicts, Optional groups and default instances work as they do for models. The class docstring appears at the top of the help panel. TypedDict keys that aren't required and weren't given are left out of the dict. Two things remain pydantic-only: unfold_cls, and lists of models with parse_json_fields.

Loading arguments from a file

@app.struct_command("train", add_config_file_option="config")
def train(config: TrainConfig): ...

This adds --config PATH_OR_JSON. The config is flattened ({"a": {"b": 1}} → a_b) and used as the command's default values, so environment variables and options given on the command line still win. You can pass a file path or an inline JSON object (a value starting with {). Any other value that isn't an existing file is an error: config file '...' does not exist.

The file format is picked by the suffix:

Suffix Format Requirement
.json JSON –
.toml TOML – (tomli is installed on Python 3.10)
.yaml / .yml YAML PyYAML, e.g. pip install "cotyper[yaml]"

Files with any other suffix are read as JSON.

To pick up a config file without passing the option, list candidates in default_config_files. The first file that exists is used when the option isn't given. ~ is expanded.

@app.struct_command(
    "train",
    add_config_file_option="config",
    default_config_files=["train.json", "~/.config/train.json"],
)
def train(config: TrainConfig): ...

With env_prefix set, the config-file option itself can come from the environment too (TRAIN_CONFIG=/path/to/file.json).

Printing the effective configuration

add_print_config_option="print_config" adds a --print-config flag. It prints the values the command would run with as JSON, then exits without running the command. The values combine defaults, the config file, environment variables and command-line options. Secrets (SecretStr) are masked. The output has the nested shape --config reads, so it can be saved and loaded again:

python train.py --config-learning-rate 0.01 --print-config > train.json
python train.py --config train.json

Environment variables

Give the app an env_prefix and every option of its struct_commands can also be set through an environment variable. The name is the prefix plus the option name, upper-cased, with underscores:

app = App(env_prefix="TRAIN_")


@app.struct_command("train")
def train(config: TrainConfig): ...
TRAIN_CONFIG_LEARNING_RATE=0.01 TRAIN_CONFIG_LAYERS=64,32 python train.py

Values are parsed exactly like on the command line (comma-separated lists, true/false for flags, JSON for dicts), and --help shows each option's variable. A required option set through its environment variable counts as given. Options of unfold_cls models use their unprefixed name (TRAIN_LEARNING_RATE). An empty prefix (env_prefix="") uses the bare option names. Without env_prefix, no environment variables are read.

When a value is given in several places, this order applies (last wins):

  1. the field's default
  2. the file or JSON from add_config_file_option
  3. the environment variable
  4. the command-line option

Flattening a model with unfold_cls

@app.struct_command("run")
@unfold_cls(Config)
def run(config: Config, other: Other = Other()): ...

unfold_cls(*classes) removes the <argument>- prefix for the listed classes, so Config.url becomes --url instead of --config-url. Other arguments are unchanged. If an unfolded field name clashes with another argument, it raises a ValueError. Put the decorator below struct_command.

Optional nested models

An Optional[Model] field is flattened just like a required one. If none of its options are given, the field stays None:

class Bar(BaseModel):
    baz: str
    count: int = 1


class Foo(BaseModel):
    bar: Optional[Bar] = None
$ python app.py --foo-bar-baz hallo      # foo.bar == Bar(baz="hallo", count=1)
$ python app.py                          # foo.bar is None
$ python app.py --foo-bar-count 5
Error: incomplete `bar`: missing required field(s) 'baz'. ...

Because the whole group is optional, none of its options are marked as required in --help. If you'd rather pass the field as a single JSON option (--foo-bar '{"baz": "hallo"}'), decorate Foo with @parse_json_fields("bar", Bar). Under @unfold_cls optional models are always flattened.

Lists of models

A list[SomeModel] field is given on the CLI as comma separated JSON objects. To have Pydantic parse these strings, decorate the model that contains the field with parse_json_fields(field_name, SomeModel):

from cotyper import parse_json_fields


class Bar(BaseModel):
    baz: str


@parse_json_fields("bars", Bar)
class Config(BaseModel):
    bars: list[Bar]
$ python app.py --config-bars '{"baz": "a"},{"baz": "b"}'

It also accepts several fields at once: @parse_json_fields((["bar", "baz"], Bar), ("foobar", Bar)).

Help text

Descriptions come from the Args: section of the model's Google-style docstring. The help= argument of struct_command sets the command description, just like in Typer.

Async commands

Commands can be async def, with struct_command and with command. CoTyper runs them to completion with asyncio.run once the options are parsed:

@app.struct_command("fetch")
async def fetch(config: FetchConfig):
    async with httpx.AsyncClient() as client:
        ...

Each invocation gets its own event loop, so the command can't be called from code that already runs one. If you need a different event loop (trio, uvloop, ...), keep the command synchronous and start the loop yourself.

Custom types

For a field type CoTyper does not support, register a type processor on the app. It is a predicate plus a function that returns a TypeProcessingResult: the annotation Typer should see, and optionally a parser for the raw string, a click_type, a callback and a doc_suffix for the help text.

from pydantic import BaseModel, ConfigDict

from cotyper import App, TypeProcessingResult


class Point:
    def __init__(self, x: float, y: float):
        self.x, self.y = x, y


def parse_point(raw):
    return raw if isinstance(raw, Point) else Point(*map(float, raw.split(",")))


app = App()
app.register_type_processor(
    lambda annotation: annotation is Point,
    lambda annotation: TypeProcessingResult(
        annotation=Point, parser=parse_point, doc_suffix=" (x,y)"
    ),
)


class Shape(BaseModel):
    model_config = ConfigDict(arbitrary_types_allowed=True)
    origin: Point = Point(0, 0)


@app.struct_command("draw")
def draw(shape: Shape):  # --shape-origin 1,2
    ...

Register processors before decorating the commands that use them. They only apply to that App, not to other apps or sub-apps added with add_typer. Later registrations take precedence, and all of them are tried before the built-in handling. The module-level cotyper.register_type_processor still exists, but it changes a registry shared by every app in the process.

Logging

CoTyper never configures logging on import. It logs to the cotyper logger, which only has a NullHandler and no level of its own, so your application's logging setup decides what is shown:

import logging

logging.basicConfig(level=logging.INFO)
logging.getLogger("cotyper").setLevel(logging.DEBUG)  # only cotyper's debug output

If you want CoTyper's ready-made setup instead, call configure_logging() once from your application's entry point:

from cotyper import LogConfig, configure_logging

if __name__ == "__main__":
    configure_logging()  # settings from env vars / file
    # or: configure_logging(LogConfig(level="DEBUG", backend="plain"))
    app()

Without an argument, configure_logging() reads its settings from:

  • the environment variables LOG_LEVEL (for example DEBUG), LOG_BACKEND (rich, plain or loguru) and LOG_LEVEL_WARNING_MODULES
  • a cotyper_log.toml in the working directory, or a TOML file named by COTYPER_LOG_CONFIG

These are only read when configure_logging() is called.

cotyper_log.toml
[logging]
level = "INFO"
backend = "rich"          # rich | plain | loguru
format = "%(message)s"
warning_modules = ["boto", "boto3", "botocore", "mlflow"]

Environment variables override the file.

  • plain and rich: these configure the root logger with logging.basicConfig. rich also installs Rich's traceback handler, and works without extras.
  • loguru: this needs the extra cotyper[loguru]. It replaces loguru's sinks and forwards records from the cotyper logger to loguru.
  • Noisy libraries: the modules listed in warning_modules are set to WARNING.

When the cotyper logger is enabled for DEBUG, struct_command logs the generated function signatures.

Changed in the next release

Earlier versions configured logging on import when LOG_LEVEL, LOG_BACKEND or a cotyper_log.toml were present. Call configure_logging() to keep that behaviour.

Mixing with plain Typer

App is a typer.Typer. You can combine @app.command, @app.callback, app.add_typer(...) and @app.struct_command freely. Importing CoTyper does not change the help output of other Typer apps in the same process.