> ## Documentation Index
> Fetch the complete documentation index at: https://docs.bijection.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Python

> Connect to an app from Python, call its functions through the generated typed client, watch queries and read every result

`bijection.client` is the Python client: the same verbs, frames and results as
[the TypeScript client](https://docs.bijection.com/clients/javascript.md), with Python's standard types.
It needs Python 3.12 or newer.

## Install

```sh theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
pip install bijection
```

Watches use HTTP event streams.

## Generate a client

```sh theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
bijection client python --out orders-client --name acme-orders
```

`bijection client python` writes a distribution of the app's exposed tree,
built on `bijection.client`. It needs a committed `bijection.lock` whose
`contract` line matches the source (run `bijection check --write-lock`). The
package holds:

* `app`, the exposed tree: `app.orders.place` is the ref of `place` in the
  `orders` module of `app({ orders })`. A segment is written in snake case
  (`listRecent` is `list_recent`);
* a `TypedDict` per argument and value object in `acme_orders.types`, named
  by tree path (`OrdersPlaceArgs`, `OrdersPlaceValue`);
* `connect`, which pins the app contract;
* each function's types as validator JSON, which the runtime encodes and
  decodes by.

Install it beside your code, or publish it to your package index. Generate it
again when the lock changes.

## Connect

```python theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import os
from acme_orders import app, connect

client = connect("https://acme.bijection.app", token=os.environ["BIJECTION_TOKEN"])
```

`token` is a fixed bearer token. For a token that changes, pass
`token_source`, any object with `token(refresh=False)` such as a
`bijection.credentials.ServiceCredential`. With neither, the client calls as
anonymous.

The generated `connect` pins the contract the package was written against.
When the installation runs another contract, every call answers
`Refusal(code="Conflict")`, its message starting `ContractStale:`. Generate
the package again from the deployed app's lock. The verbs take only the
generated package's refs: there is no call by tree path string.

`connect_async` answers an `AsyncClient` with the same verbs as coroutines.
Close a client with `client.close()`, or use it as a context manager.

For a dynamic tool, the raw connector uses `contract="discover"`. A pinned client refuses a path absent from its contract map before sending it.

## Calls

```python theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
listed = client.query(app.orders.recent, {"customer": "c-1"})
placed = client.mutate(app.orders.place, {"sku": "A-1", "quantity": 2})
```

`client.query(fn, args)` runs a query once. `client.mutate(fn, args)` runs a
mutation as one transaction. Leave out `args` for a function that declares
none.

A mutation has one identity, `once`. The same `once` with the same arguments
answers the original result and runs nothing again; the same `once` with other
arguments refuses `Invalid`. Without `once` the client mints one for the call.
Give your own when the identity belongs to something outside the process,
such as a job you may run again after a restart.

`Unknown` means the mutation may have committed, for example when the reply
was lost. Call again with the same `once`:
An uncertain mutation carries its original request key in `Refusal.once`.

```python theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
def place_once(order_id: str, sku: str):
    for _ in range(3):
        placed = client.mutate(app.orders.place, {"sku": sku, "quantity": 1}, once=order_id)
        if placed.ok or placed.code != "Unknown":
            return placed
    return placed
```

## Frames

A frame is who acts, under which label, in which world and at which valid
instant. Each method answers a new client with that field set:

```python theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
from datetime import datetime, timezone
from bijection.client import Label, World

finance = client.under(Label.tag("access.finance"))
acme = client.under(Label.member("access.tenant", "acme"))
plan = client.in_(World.branch("plan-2027"))
then = client.at(datetime(2026, 1, 1, tzinfo=timezone.utc))
alice = client.as_("person:alice")  # an operator credential only
```

`as_` and `in_` carry a trailing underscore because `as` and `in` are Python
keywords. `a.and_(b)` is the conjunction of two labels and
`Label.any_of(a, b)` the disjunction. `World.version(v)` reads at a version.

A committed mutation's result carries its commit `version`. Pass it as `seen`
to read your own write:

```python theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
placed = client.mutate(app.orders.place, {"sku": "A-1", "quantity": 2})
if placed.ok:
    recent = client.query(app.orders.recent, {"customer": "c-1"}, seen=placed.version)
```

`seen` answers from state at least that new. `query`, `watch`, `mutate` and
`trial` all take it.

## Results

Every verb answers a result and never raises for how the call ended. A result
is `Ok(value, version)` or `Refusal(code, message, guard)`; both have `.ok`.

```python theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
from bijection.client import Ok, Refusal

match client.mutate(app.orders.place, {"sku": "A-1", "quantity": 2}):
    case Ok(value=order):
        print("placed", order)
    case Refusal(code="OutOfStock", message=message):
        print(message)
    case Refusal(code="Forbidden", guard=guard):
        print("refused by", guard)
    case Refusal(code=code, message=message):
        print(code, message)
```

`code` is one of the twelve host codes in `bijection.client.HOST_CODES`
(`Unknown`, `Disallowed`, `Forbidden`, `Invalid`, `Absent`, `Exists`,
`Conflict`, `Erased`, `Expired`, `Withdrawn`, `Limit`, `Failed`) or one of the
codes the function declares in `refuses`. A generated ref knows its function's
codes: a declared code arrives as written, and any other kernel code is folded
into its host code with the kernel code as `reason`. A host code's `reason` is
its precise cause (`BudgetExhausted` under `Limit`), or `None`, and `message`
never starts with it. On
`Forbidden`, `guard` is the tree path of the guard that refused. `message` is
the sentence the caller may read.

## Watch

`client.watch(fn, args)` runs a query and keeps its result current. Iterate it;
it yields a new result each time the answer changes:

```python theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
with client.watch(app.orders.recent, {"customer": "c-1"}) as live:
    for result in live:
        if result.ok:
            print([order["sku"] for order in result.value])
        else:
            print(result.code, result.message)
```

Leaving the `with` block, or calling `live.stop()`, ends the watch. One live
connection serves every watch of a frame, and reconnects on its own. An
`AsyncClient` watch is iterated with `async for`:

```python theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
async with connect_async(url, token=token) as client:
    async with client.watch(app.orders.recent, {"customer": "c-1"}) as live:
        async for result in live:
            ...
```

A watch in a world or at a valid instant (`in_`, `at`) answers once and ends:
only the head moves.

## Trial

`client.trial(fn, args)` runs a call in a discarded world and commits nothing:

```python theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
tried = client.trial(app.orders.cancel, {"order": "o-1"})
print(tried.result)
for write in tried.writes:
    print(write.verb, write.table, write.key)
for task in tried.tasks:
    print(task.target, task.due)
```

`result` is how the call would have ended, with the refusing guard in
`result.guard`. `writes` are the `{ verb, table, key, before, after }` it would
have written and `tasks` the `{ target, args, due }` it would have submitted.
`valid_until` is the instant the answer is valid until (a call at the same version
committed before it is decided the same way), or `None` when nothing
time-dependent bounds it.

## Values

| Bijection | Python |
| - | - |
| `t.string()` | `str` |
| `t.number()` | `float` |
| `t.int()` | `int` (int64) |
| `t.boolean()` | `bool` |
| `t.bytes()` | `bytes` |
| `t.decimal()` | `decimal.Decimal` |
| `t.date()` | `datetime.date` |
| `t.instant()` | `datetime.datetime`, timezone-aware, to the microsecond |
| `t.duration()` | `datetime.timedelta` |
| `t.key(table)` | `str` |
| `t.maybe(x)` | `x \| None` |
| `t.array(x)` | `list` |
| `t.map(x)` | `dict[str, x]` |
| an object | a `TypedDict` |

A naive `datetime` is refused: give it a time zone. A duration in years or
months has no fixed length and does not decode as a `timedelta`. An `int`
outside the int64 range is refused.

## Change entries

A query that answers `selection.changes` answers change entries.
`bijection.client.Change` holds one: `key`, `before` (`None` on an insert),
`after` (`None` on a delete) and the change's `version`.

```python theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
changes = client.query(app.orders.changes, {"since": version})
if changes.ok:
    for change in changes.value:
        if change.before is None:
            print("inserted", change.key, change.after)
```


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.