CoTyper
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
🧑🔬 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.11.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| cotyper-0.11.0.tar.gz | 25.0 MB | Without provenance | Details for cotyper-0.11.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| cotyper-0.11.0-py3-none-any.whl | Python 3 | none | any | Details for cotyper-0.11.0-py3-none-any.whl |
Total release size: 25.0 MB
Release files / cotyper-0.11.0.tar.gz
| Download URL | cotyper-0.11.0.tar.gz |
|---|---|
| Size | 25.0 MB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
061c4993863339cb9c393cbe2fdc59cd9ddf1526a9e05ab0be2a61ed0ca8637e
|
|
BLAKE2b-256 checksum How to use checksums |
ad757b9380cf6cf98772fdc79fbf776691887bbfe0a5079bacf3fd4bf8ff70f8
|
| 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.11.0-py3-none-any.whl
| Download URL | cotyper-0.11.0-py3-none-any.whl |
|---|---|
| Size | 40.1 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
9b58704a5fbee1984e948a79271262fb0719bb7cb029837dcd03a1484468cdb5
|
|
BLAKE2b-256 checksum How to use checksums |
e931a2460a11ed360457cbf7e4d077f4e06d41ec19ede8e8d6328e363cff6227
|
| 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.11.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.