comatype for Python
Comatype runtime for Python: the async client c (httpx) and the ASGI server s, with pydantic v2 models.
PyPI · Documentation · GitHub
Comatype: write an API once in
.comatfiles, get types, validation, a client and a server in ten languages. This package is the Python runtime that the generated code depends on.
How to use
Install
pip install comatype # or: uv add comatype / poetry add comatype
Python 3.10 or later; depends on pydantic>=2.7 and httpx>=0.27. Generated code goes to <root>/comatype_gen/ by default.
The comatype command (parser, checker and generators) is separate from the runtime:
curl -fsSL https://raw.githubusercontent.com/oldsheeep3/comatype/main/install.sh | sh
This downloads the prebuilt comatype command (and its short alias comat) for macOS (arm64, x64) and Linux (x64, arm64) from the latest release; no Rust toolchain needed. On Windows, download comatype-x86_64-pc-windows-msvc.zip from the release page. To build it from source instead: cargo install --git https://github.com/oldsheeep3/comatype comatype-cli.
Import
from comatype import c, s # client and server
from comatype import ComatypeWrap, Cookie # wrappers and cookies
# generated: one module per .comat file (`[id]` becomes `__id`)
from comatype_gen.user.put__id import path, S200, S404, Request, Params, Body
from comatype_gen.comatype_init import Wrappers, AuthCtx, S401
The generated imports are relative to the package, so the name and location of comatype_gen do not matter.
Format / Lint
Every generated file starts with # Code generated by comatype generate. DO NOT EDIT. Exclude the directory and keep type checking on:
# pyproject.toml
[tool.ruff]
extend-exclude = ["comatype_gen"]
[tool.mypy]
strict = true
plugins = ["pydantic.mypy"]
[tool.pydantic-mypy]
init_typed = true
init_forbid_extra = true
With the pydantic.mypy plugin, S200(data=1) or assigning a field declared empty is a type error.
Check
comatype check # check every .comat file; prints [error] / [warn] / [info] lines, exits 1 on errors
comatype check cache # only one topic: cache, path, wrap, cookie, status, import, type
comatype endpoints -g # list the endpoints, grouped by wrapper chain
comatype generate --lang python # generate the code (python only)
Run comatype check in CI so that a broken .comat never reaches the generated code.
init.comat
init.comat holds the settings of the whole project. Put exactly one directly under comatDir.
// comatfiles/init.comat
import UserData from ../types/UserData.comat
import ApiError from ../types/common.comat
// The base url of every endpoint. Override it at run time with the COMATYPE_BASE_URL environment variable
baseUrl https://api.example.com
// The cookie the server issues (for `cookie on` endpoints)
cookie session {
httpOnly: true,
secure: true,
sameSite: lax,
}
// A wrapper: what it adds to `ctx`, and the statuses it can return. You implement it in Python
wrapper auth {
ctx {
user: UserData,
}
s401 ApiError
}
comatfiles
A .comat file is one endpoint. Its method and path come from where the file is and what it is called.
comatfiles/
├─ init.comat baseUrl, cookie, wrapper declarations (exactly one)
├─ defaults.comat defaults for this directory and below: wrap, headers, shared statuses
├─ post_user.comat POST /user
└─ user/
├─ [id]/put.comat PUT /user/:id ([id] is a dynamic segment)
├─ (noauth)/ a group: not part of the path
│ ├─ defaults.comat wrap auth off
│ ├─ post_login.comat POST /user/login
│ └─ get_ping.comat GET /user/ping
└─ get.comat GET /user
types/ types shared by endpoints (outside comatDir)
comatype.config.json says where comatfiles is and what to generate:
{
"$schema": "https://raw.githubusercontent.com/oldsheeep3/comatype/main/schema/comatype.config.schema.json",
"services": {
"api": {
"comatDir": "./comatfiles",
"targets": [{ "lang": "python", "role": "client", "root": "./server" }]
}
}
}
See the syntax reference for params, search, body, headers, status codes and path.
Example
ComatFiles
// types/UserData.comat
UserData {
name: string,
email: email,
phone: phone,
uid: uuidv4,
}
// comatfiles/user/[id]/put.comat -> PUT /user/:id
import UserData from ../../../types/UserData.comat
import ApiError from ../../../types/common.comat
params {
id: uuidv4,
}
body UserData
s200 UserData
s404 ApiError
// comatfiles/defaults.comat: applies to every endpoint below
import ApiError from ../types/common.comat
wrap auth // the wrapper declared in init.comat
cookie on // send and receive the session cookie
s500 ApiError // every endpoint can answer 500
// comatfiles/user/(noauth)/defaults.comat: this group needs no login
wrap auth off
// comatfiles/user/(noauth)/post_login.comat -> POST /user/login
import ApiError from ../../../types/common.comat
body {
email: email,
password: string,
}
s200 {
uid: uuidv4,
}
// the auth wrapper is off in this group, so declare the 401 yourself
s401 ApiError
Generate the Python code with comatype generate --lang python.
Client
from uuid import UUID
from comatype import c
from comatype_gen.user.put__id import path, S200, S404, Request, Params, Body
async def put_user(id: str, user: Body) -> None:
res = await c.put(path, Request(params=Params(id=UUID(id)), body=user), S200, S404)
match res.status:
case 200:
res.data # UserData
case 404:
res.error # ApiError
The client is async only. A status you did not pass raises UnexpectedStatusError; invalid input raises a validation error before any network call.
Server
from comatype import s
from comatype_gen.user.put__id import path, S200, S404, Request
@s.put(path)
async def put_user(req: Request):
user = await db.user.update(req.params.id, req.body)
if user is None:
return S404(error=S404.Res(code="not_found", message="user not found"))
return S200(data=user)
s is an ASGI app: uvicorn.run(s), and in tests httpx.ASGITransport(app=s).
Wrapper & Cookie
A wrapper wraps the request and the response: authentication, headers, logging. Declare it in init.comat, enable it with wrap auth in a defaults.comat or in an endpoint, and implement it in Python.
# client: add a header to every request
from comatype import c, ComatypeWrap
from comatype_gen.comatype_init import Wrappers
async def _auth(req, next):
req.headers["Authorization"] = f"Bearer {token}"
return await next(req)
c.init(wrappers=Wrappers(auth=ComatypeWrap(_auth)), cookies=True) # cookies=True keeps a jar
# server: authenticate and add ctx.user (typed from `ctx { user: UserData }` in init.comat)
from comatype import s, ComatypeWrap
from comatype_gen.comatype_init import AuthCtx, S401, Wrappers
async def _auth(req, next):
user = await verify_session(req.cookies.get("session"))
if user is None:
return S401(error=S401.Res(code="unauthorized", message="login required"))
req.ctx = AuthCtx(user=user)
return await next(req)
s.init(wrappers=Wrappers(auth=ComatypeWrap[AuthCtx](_auth)))
# server: issue the session cookie (declared in init.comat; the endpoint has `cookie on`)
from comatype import Cookie
return S200(data=S200.Res(uid=user.uid), cookie=Cookie(token, max_age=3600)) # delete: Cookie.clear()
mypy tells you when a wrapper declared in init.comat is missing.
Cache
Caching is declared in the .comat file, once, for the client and the server (GET and QUERY endpoints only):
// comatfiles/user/(noauth)/get_ping.comat -> GET /user/ping
s200 {
ok: bool,
}
cache 60000 // cache the response in memory for 60 seconds
| Declaration | Meaning |
|---|---|
| (none) | no caching |
cache off |
never cache |
cache 5000 |
in memory for 5000 ms (client and server) |
cache 5000 cookie |
in a cookie for 5000 ms (client only) |
- The server looks the cache up before the wrappers, with the exact request (method, path, query, all headers, body) as the key.
- The client looks it up just before the network call, with the method, URL, body and the request headers declared in the
.comat. - Only 2xx responses without
Set-Cookieare cached.cacheindefaults.comatorinit.comatis ignored with a warning.
c.clear_cache() # drop the client cache, for example on logout
More
- Documentation: https://comatype.sheeplab.net
- Source and issues: https://github.com/oldsheeep3/comatype
- License: MIT
Metadata
Release files for comatype 0.0.4
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 |
|---|---|---|---|---|
| comatype-0.0.4.tar.gz | 30.0 kB | With provenance | Details for comatype-0.0.4.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| comatype-0.0.4-py3-none-any.whl | Python 3 | none | any | Details for comatype-0.0.4-py3-none-any.whl |
Total release size: 54.9 kB
Release files / comatype-0.0.4.tar.gz
| Download URL | comatype-0.0.4.tar.gz |
|---|---|
| Size | 30.0 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
9a56b372809e1d0d82df974f99ff495a1b2783e7ed206db69bf4ab8d99eadd5b
|
|
BLAKE2b-256 checksum How to use checksums |
9c73966e46091383e24f7879e930d264ae415d7808150bd623e91780732151ef
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
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.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 9, 2026.
Transparency logRelease files / comatype-0.0.4-py3-none-any.whl
| Download URL | comatype-0.0.4-py3-none-any.whl |
|---|---|
| Size | 24.9 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
de94feba20208c322d7d1ab6e4570836f332a64ea5edf6fa6b22d97c65720df1
|
|
BLAKE2b-256 checksum How to use checksums |
35c0f095835df2f4cad7b03f9092a8de5e4e60336fad4fad7c51ccf3f174f2e2
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
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.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 9, 2026.
Transparency logSecurity for comatype 0.0.4
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.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for comatype-0.0.4.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 9, 2026.
Transparency logA 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.