Skip to main content

CoTyper

CI Status Coverage PyPI Downloads Release

Inspired by Typer and Pydantic. CoTyper since you add a lot of co in category theory.

CoTyper is a wrapper around Typer but with support for (nested) pydantic models as function arguments.

❗ Note this project is in early development

Install

Install the package via pip:

pip install cotyper

Or install the package via uv:

uv add cotyper # cotyper[rich] | cotyper[loguru] for optional logging dependencies

Build from Source

Clone the repository and build the package as wheel file

git clone https://gitlab.opencode.de/lgln/cotyper
cd cotyper
python -m build --wheel # or pip install .

🧑‍💻 Examples

For the examples it is recommended to use the uv command line tool, but feel free to build the environment with pip or poetry as well.

import datetime

from pydantic import BaseModel

from cotyper import App, unfold_cls

app = App()


class MetaData(BaseModel):
    date: datetime.datetime = "2023-10-01T00:00:00"


class Config(BaseModel):
    user_name: str
    url: str
    meta: MetaData = MetaData()


class Foo(BaseModel):
    bar: str = "baz"


@app.struct_command("example")
@unfold_cls(
    Config
)  # this will unfold the Config model into command line options, hence, exposing the fields of the model itself
def example_command(config: Config, foo: Foo = Foo()):
    """
    Example command that takes a nested pydantic model as argument.

    Args:
        config (Config): Configuration model with user_name, url, and meta data.
        foo (Foo): Another model with a bar attribute.
    """
    print(f"User: {config.user_name}, URL: {config.url}, Meta Date: {config.meta.date}")
    print(f"Foo Bar: {foo.bar}")


if __name__ == "__main__":
    app()

And requesting help will show the nested models as options:

uv run examples/readme.py --help
                                                                               
Usage: readme.py [OPTIONS]                                                                           
                                                                                                      
╭─ Options ──────────────────────────────────────────────────────────────────────────────────────────╮
│ *  --url                       TEXT  [default: None] [required]                                    │
│    --install-completion              Install completion for the current shell.                     │
│    --show-completion                 Show completion for the current shell, to copy it or          │
│                                      customize the installation.                                   │
│    --help                            Show this message and exit.                                   │
╰────────────────────────────────────────────────────────────────────────────────────────────────────╯
╭─ User ─────────────────────────────────────────────────────────────────────────────────────────────╮
│ *  --user-name        TEXT  [default: None] [required]                                             │
╰────────────────────────────────────────────────────────────────────────────────────────────────────╯
╭─ Meta ─────────────────────────────────────────────────────────────────────────────────────────────╮
│ --meta-date        [%Y-%m-%d|%Y-%m-%dT%H:%M:%S|%Y-%m-%d    [default: 2023-10-01 00:00:00]          │
│                    %H:%M:%S]                                                                       │
╰────────────────────────────────────────────────────────────────────────────────────────────────────╯
╭─ Foo ──────────────────────────────────────────────────────────────────────────────────────────────╮
│ --foo-bar        TEXT  [default: baz]                                                              │
╰────────────────────────────────────────────────────────────────────────────────────────────────────╯```

🗒️ Note, that the @unfold_cls(Config) decorator is used to unfold the Config model into the fields of the model directly.

And running the command with the toy information provides

uv run examples/readme.py --url "pydantic.dev" --user-name "Monty Python"
User: Monty Python, URL: pydantic.dev, Meta Date: 2023-10-01 00:00:00
Foo Bar: baz

Define logging backend via LOG_BACKEND

LOG_BACKEND=loguru uv run examples/readme.py --url "pydantic.dev" --user-name "Monty Python"

LOG_BACKEND=rich uv run examples/readme.py --url "pydantic.dev" --user-name "Monty Python"

Define a logging config toml and provide the path via COTYPER_LOG_CONFIG=/path/to/config.toml"

[logging]
level = "INFO"
backend = "rich"
format = "%(message)s"
warning_modules = ["boto", "boto3", "botocore", "mlflow"]

Optional Nested Models

A nested model keeps the same command line shape when it becomes optional. Optional[Bar] is flattened into --*-bar-* options just like a required Bar would be, and leaving all of them out keeps the field None:

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


class Foo(BaseModel):
    bar: Optional[Bar] = None


@app.struct_command("nested-optional")
def nested_optional_command(foo: Foo):
    if foo.bar is not None:
        print(f"Bar Baz: {foo.bar.baz}, Count: {foo.bar.count}")
    else:
        print("Bar is None")
uv run examples/nested_optional.py nested-optional --foo-bar-baz hallo
# Bar Baz: hallo, Count: 1

uv run examples/nested_optional.py nested-optional
# Bar is None

Because the whole group is optional, none of its options can be required - so they all show [default: None] and the model's own defaults are applied once any option of the group is given. Passing only part of a group whose model has other required fields is reported as a usage error naming what is missing:

uv run examples/nested_optional.py nested-optional --foo-bar-count 5
# Error: incomplete `bar`: missing required field(s) 'baz'. Pass the option(s) ending
#        in '-bar-baz', or omit every `bar` option to leave it unset.

Opting into a json string

Decorate the enclosing model with parse_json_fields to keep the field as a single json option instead:

@parse_json_fields("bar", Bar)
class JsonFoo(BaseModel):
    bar: Optional[Bar] = None
uv run examples/nested_optional.py nested-optional-json --foo-bar '{"baz": "hallo"}'
# Bar Baz: hallo, Count: 1

parse_json_fields is also how a List[Bar] field is passed, as comma separated json objects - see the dict-model command in examples/extensive.py.

🗒️ Under @unfold_cls(...) the opt-out is not visible to the flattener, so an optional model field is always flattened there.

Extensive Examples

See examples/ for more examples. For example

uv run examples/extensive.py --help

examples/new_types.py has a command for each group of the extended field types (enums, paths, sets, dates, durations, Decimal, SecretStr, HttpUrl, unions, ...):

uv run examples/new_types.py --help
uv run examples/new_types.py schedule --day 2024-01-31 --timeout PT1H30M

🧑‍🔬 Tests

Run

uv run pytest

📋 ToDo

-[ ] documentation

🐍 Contributing

See CONTRIBUTING.md for details on how to contribute to this project.

🗝️ License

MIT License

Metadata

Release files for cotyper 0.13.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for cotyper 0.13.0
File Size Uploaded Provenance Actions
cotyper-0.13.0.tar.gz 29.8 MB Without provenance Details for cotyper-0.13.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for cotyper 0.13.0
File Interpreter ABI Platform Actions
cotyper-0.13.0-py3-none-any.whl Python 3 none any Details for cotyper-0.13.0-py3-none-any.whl

Total release size: 29.8 MB

Release files / cotyper-0.13.0.tar.gz

Download URL cotyper-0.13.0.tar.gz
Size 29.8 MB
Tags Source
SHA-256 checksum
How to use checksums
449ee11baf1a5f13a407715d7c4a094b6ccabd7068546b32f0cce71fb383f590
BLAKE2b-256 checksum
How to use checksums
2fa3f8783b56a6b60fb5e44c37751da98d0b849c1a5bcb58b9499f4da69133cf
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.12

Release files / cotyper-0.13.0-py3-none-any.whl

Download URL cotyper-0.13.0-py3-none-any.whl
Size 43.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
53f1b8261d710ca38c1911d29aa4c116e9250db3c70ae213467a8d43749f7453
BLAKE2b-256 checksum
How to use checksums
3000c8b0c7e8b90a2acc94a8247ba5cf8ce97a9f20be2fb22f4b9788b010b723
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.12

Security for cotyper 0.13.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page