Skip to main content

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 .comat files, get types, validation, a client and a server in eight 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).

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-Cookie are cached. cache in defaults.comat or init.comat is ignored with a warning.
c.clear_cache()   # drop the client cache, for example on logout

More

Metadata

Release files for comatype 0.0.3

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

Source distribution (sdist)

Source distribution for comatype 0.0.3
File Size Uploaded Provenance Actions
comatype-0.0.3.tar.gz 29.8 kB With provenance Details for comatype-0.0.3.tar.gz

Built distribution (wheel)

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

Total release size: 54.5 kB

Release files / comatype-0.0.3.tar.gz

Download URL comatype-0.0.3.tar.gz
Size 29.8 kB
Tags Source
SHA-256 checksum
How to use checksums
06eb6a2c628ca4a0c306cb2407bbe45179f8763e87786b7eda7476a05430a3e9
BLAKE2b-256 checksum
How to use checksums
0d7286f371e348b70890add7277be8478dd9eb5a50798abfa5048ec3858c1986
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 log

Release files / comatype-0.0.3-py3-none-any.whl

Download URL comatype-0.0.3-py3-none-any.whl
Size 24.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
c6e043b0aaf94d18ceb52452f94ab344fe3238bc9a4e42d66dea6c5b13095bf4
BLAKE2b-256 checksum
How to use checksums
a93ce658e4810844673868bf795841263831013b8c06ab4c2f576847f34fd74f
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 log

Security for comatype 0.0.3

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.

Select from 2 files

Attestation for comatype-0.0.3.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 log

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