Skip to content
Luna
Esc
↑↓navigate↵open⌘Jpreview
On this page

Python SDK

How each name of the TypeScript SDK maps to the Python SDK, how type hints declare a handler's arguments, and what Python lacks or adds.

The Python SDK, the luna package, declares luna types and handlers in Python, with the same parts as the TypeScript SDK under snake_case names.

from typing import Annotated, Literal, TypedDict

from luna import Ctx, define_luna, t, table

Wallet = define_luna(
    "Wallet",
    key={"id": t.string()},
    schema={
        "balance": table({"cents": t.int()}, single_row=True),
        "moves": table({"id": t.id(), "cents": t.int(), "kind": t.enum(["charge", "credit"])}),
    },
    idle_timeout="1m",
)


class Note(TypedDict):
    text: str
    pinned: bool


@Wallet.hook
def on_create(ctx: Ctx) -> None:
    ctx.db.balance.set({"cents": 0})


@Wallet.handler(errors={"Short": t.object({"have": t.int()})})
def charge(ctx: Ctx, amount: Annotated[int, "Cents to take"], note: Note | None = None) -> int:
    have = ctx.db.balance.get()["cents"]
    if have < amount:
        ctx.fail("Short", {"have": have})
    ctx.db.balance.update({"cents": have - amount})
    ctx.db.moves.insert({"cents": amount, "kind": "charge"})
    return have - amount


@Wallet.handler(query=True)
def history(ctx: Ctx, kind: Literal["charge", "credit"], limit: int = 20) -> list:
    return ctx.db.moves.find(where={"kind": kind}, order_by={"id": "desc"}, limit=limit)

Reference

Names

Every name of the TypeScript SDK has a Python counterpart: functions, methods, fields and options in snake_case, and classes under the same name.

TypeScript Python
defineLuna({ name: "Wallet", ... }) define_luna("Wallet", ...)
idleTimeout, primaryKey, singleRow idle_timeout, primary_key, single_row
handlers: (h) => ({ charge: h(spec, run) }) @Wallet.handler or @Wallet.handler(...) on a function
hooks: { onCreate } @Wallet.hook on a function named on_create
t.blobRef(), t.string({ maxLength }) t.blob_ref(), t.string(max_length=...)
args: t.request() @Wallet.handler(request=True)
definePackage(name, { A, B }) define_package(name, A, B)
ctx.callId, ctx.isReplica, ctx.runId ctx.call_id, ctx.is_replica, ctx.run_id
ctx.abortSignal ctx.cancelled
ctx.sql`... ${x}` ctx.sql("... ?", x)
ctx.call(Wallet, key).charge(args, { timeout }) await ctx.call(Wallet, key, timeout=...).charge(**args)
ctx.send(Wallet, key).credit(args, { maxAttempts }) ctx.send(Wallet, key, max_attempts=...).credit(**args)
ctx.schedule({ handler, args, after }) ctx.schedule(handler, args, after=...)
ctx.fail(code, data, { keep: true }) ctx.fail(code, data, keep=True)
find({ where, orderBy, startAfter }) find(where=..., order_by=..., start_after=...)
update({ where, set }), delete({ where }) update(set=..., where=...), delete(where=...)

A name that is a Python keyword or built-in in use takes a trailing underscore: from_ in stream.read, ctx.subscribe and path, and except_ in ctx.broadcast.

@Luna.handler options

PropType
query?bool

As query in Handler spec.

Typebool
DefaultFalse
shared?bool

As shared in Handler spec.

Typebool
DefaultFalse
errors?dict[str, Ty]

The errors the handler may fail with, by code.

Typedict[str, Ty]
exclusive?bool

As exclusive in Handler spec.

Typebool
DefaultFalse
requires?"exists"

As requires in Handler spec.

Type"exists"
durable?bool

As durable in Handler spec.

Typebool
DefaultFalse
route?str | dict

As route in Handler spec, with rate_limit for rateLimit.

Typestr | dict
request?bool

The handler takes the raw HTTP request as its one argument after ctx.

Typebool
DefaultFalse
name?str

The handler's name.

Typestr
Defaultthe function's name
description?str

What the handler does.

Typestr
Defaultthe docstring

Type hints

A handler’s parameters after ctx are its arguments, and the return hint is its result type.

Hint Luna type
str, int, float, bool, bytes t.string(), t.int(), t.float(), t.bool(), t.bytes()
X | None X.optional()
Literal["a", "b"], or an Enum of strings t.enum(["a", "b"])
list[X] t.array(X)
a TypedDict or a dataclass t.object(...) with its fields
Annotated[X, "text"] X described with text
Annotated[X, t.uuid()] the t builder given
anything else, dict included t.json()

A parameter with a default value is optional. A key field named as a parameter receives the key’s value.

Ctx

Ctx has every member of the TypeScript ctx, in snake_case. These differ:

PropType
cancelledasyncio.Event | None

Set when the caller goes away, in place of abortSignal.

Typeasyncio.Event | None
sql(sql, *params)(sql: str, *params) -> list[dict]

Runs SQL with ? parameters given after it, in place of a tagged template.

Type(sql: str, *params) -> list[dict]
list(luna, prefix=, cursor=, limit=)async -> dict

The keys of lunas of a type, as a dict with keys and cursor. Await it.

Typeasync -> dict
wait_for(name, timeout=)async -> Any | None

Waits for a signal, and gives None after timeout.

Typeasync -> Any | None

Rows are dicts, so read a column with row["cents"]. StatelessCtx has the members of the TypeScript one, with cancelled in place of abortSignal, and its key is an empty dict.

What Python lacks

  • defineConfig. luna.config.ts stays a TypeScript file, and its lunas list names your .py files.
  • connect, LunaSocket and ConnectionError of the TypeScript client.

What Python adds

  • Request, the raw HTTP request, also named LunaRequest.
  • Response, to answer a route, with Response.json(body) and Response.redirect(location).
  • luna.client, a client for Python apps, with create_client, LunaClient and SyncClient.

Good to know

  • Deploying Python lunas needs CPython 3.12 or later on your machine. The CLI runs python3, or the interpreter LUNA_PYTHON names, to read your types.
  • @Wallet.handler returns the function as it was, so code in the same file can call it.
  • A TypedDict or dataclass argument arrives as a dict.
  • step takes attempts, backoff, timeout and compensate as keyword arguments, and backoff may be a duration such as "2s".

Examples

Send a message

@Wallet.handler
def give(ctx: Ctx, to: str, amount: int) -> str:
    ctx.db.balance.update({"cents": ctx.db.balance.get()["cents"] - amount})
    return ctx.send(Wallet, {"id": to}, max_attempts=3, dedupe_key=f"give-{ctx.call_id}").credit(amount=amount)

Call another luna and run SQL

@Wallet.handler
async def total(ctx: Ctx, other: str) -> int:
    theirs = await ctx.call(Wallet, {"id": other}, timeout="5s").history(kind="credit")
    return len(theirs) + len(ctx.sql("SELECT id FROM moves WHERE cents > ?", 100))

Run durable steps

@Wallet.handler(durable=True)
async def payout(ctx: Ctx, amount: int) -> None:
    await ctx.step("charge", lambda: charge(ctx, amount), attempts=5, backoff="2s")
    await ctx.sleep("1d")
    ctx.schedule("credit", {"amount": amount}, after="1h", id="refund")

Was this page helpful?