CoTyper¶
CoTyper turns functions that take (nested) Pydantic models into Typer command line interfaces.
Typer maps function arguments to CLI options, but only for simple types. CoTyper
also accepts BaseModel arguments: it recursively unfolds every model field
into its own option, and before calling your function it folds the parsed values
back into validated model instances.
from pydantic import BaseModel
from cotyper import App
app = App()
class Database(BaseModel):
host: str = "localhost"
port: int = 5432
@app.struct_command("connect")
def connect(db: Database):
print(f"Connecting to {db.host}:{db.port}")
if __name__ == "__main__":
app()
$ python app.py --db-host example.org --db-port 6543
Connecting to example.org:6543
Note
CoTyper is in early development. The API may still change between minor versions.
Features¶
- Nested models become prefixed options (
--db-host), grouped into help panels. - Supports
list,set,tuple,Literal,Enum,Union,dict,datetime,date,timedelta,Path,DecimalandOptionalfields, and any other type Pydantic can validate from a string (SecretStr,HttpUrl, ...). See Supported types. - Field descriptions are taken from the model's Google-style docstring.
- Load all arguments from a JSON, TOML or YAML file with
add_config_file_option, discover a default config file, and print the effective configuration withadd_print_config_option. - Set any option through an environment variable with
App(env_prefix=...). - Drop the prefix of a model with
unfold_cls. Appsubclassestyper.Typer, so plain Typer commands keep working.
Next: install CoTyper and follow the tutorial.