Metadata-Version: 2.5
Name: errpath
Version: 0.1.0
Summary: Result types for Python. See every error path.
Project-URL: Homepage, https://github.com/jagreehal/errpath-python
Project-URL: Documentation, https://github.com/jagreehal/errpath-python#readme
Project-URL: Repository, https://github.com/jagreehal/errpath-python
Project-URL: Issues, https://github.com/jagreehal/errpath-python/issues
Author-email: Jag Reehal <jag@jagreehal.com>
License: MIT
License-File: LICENSE
Keywords: error-handling,machinejson,railway,result,static-analysis,xstate
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Python: >=3.11
Description-Content-Type: text/markdown

# errpath

**Result types for Python. See every error path.**

errpath lets you:

- return errors as values (`Ok` / `Err`), so your type checker knows every way a function can fail
- keep the happy path readable: `@safe` stops at the first failure, with no `if` after every call
- draw every error path of a function as a diagram, straight from your code
- catch risky changes in pull requests: new crash points, ignored errors, changed error paths

No dependencies. Python 3.11+.

```bash
uv add errpath    # or: pip install errpath
```

---

## The problem

A Python signature can't say what a function raises:

```python
def get_user(user_id: str) -> User: ...  # raises UserNotFound? DbError? Nothing says.


try:
    user = get_user("u-2")
except Exception as e:  # which errors? the signature doesn't say
    ...
```

Your type checker can't see a `raise`, so callers guess, catch everything, or forget.

errpath puts the failure in the signature.

---

## Return errors as values

```python
from dataclasses import dataclass

from errpath import Err, Ok, Result, ok


@dataclass
class User:
    id: str
    name: str


class UserNotFound(Exception):
    pass


def get_user(user_id: str) -> Result[User, UserNotFound]:
    if user_id == "u-1":
        return Ok(User(user_id, "Alice"))
    return Err(UserNotFound(user_id))


result = get_user("u-2")
if ok(result):
    print(result.value.name)  # your editor knows this is a User
else:
    print(f"no such user: {result.error}")  # ...and this is a UserNotFound
```

The failure is part of the return type, so you can't use the value without checking first.

`match` works too:

```python
match get_user("u-1"):
    case Ok(user):
        print(user.name)
    case Err(error):
        print(f"no such user: {error}")
```

---

## Many steps: an `if` after every call

Real work is several steps that can each fail. Checking every result by hand gets noisy:

```python
def place_order(cart: Cart, card: Card) -> Result[Receipt, PriceError | CardDeclined | DbError]:
    total = price(cart)
    if not ok(total):
        return total
    payment = charge(card, total.value)
    if not ok(payment):
        return payment
    return save_order(cart, payment.value)
```

Ten steps would mean ten checks. That's what `@safe` is for.

---

## `@safe`: write the happy path, stop at the first failure

```python
from errpath import safe_with


@safe_with(PriceError, CardDeclined, DbError)
def place_order(cart: Cart, card: Card) -> Receipt:
    total = price(cart).unwrap()  # an Err stops here...
    payment = charge(card, total).unwrap()  # ...or here...
    return save_order(cart, payment).unwrap()  # ...or here


result = place_order(cart, card)  # Result[Receipt, PriceError | CardDeclined | DbError]
```

`.unwrap()` gives you the value of an `Ok`, and raises the error of an `Err`. The decorator catches it and returns it as `Err`, so the function reads top to bottom and still returns a `Result`.

- `@safe_with(A, B)` catches only those errors, and your editor knows the result is `Result[T, A | B]`. Anything else still raises, as a bug should.
- `@safe` catches any `Exception`, bugs included: a typo's `KeyError` comes back as an `Err` instead of crashing. Use it deliberately, as a catch-all at an outer boundary or around code you don't own. Prefer `@safe_with`.
- `@safe_async` and `@safe_async_with` do the same for `async def`. They never catch `asyncio.CancelledError`.

It also wraps existing code that raises:

```python
import json

from errpath import safe_with


@safe_with(json.JSONDecodeError)
def parse(text: str) -> dict:
    return json.loads(text)


parse("{oops")  # Err(JSONDecodeError(...)), not a crash
```

---

## See every way it can fail

Here's a fuller checkout ([examples/checkout.py](examples/checkout.py)):

```python
@safe
def place_order(cart: Cart, card: Card) -> Receipt:
    total = price(cart).unwrap()
    if cart.has_coupon:
        validate_coupon(cart).unwrap()
    payment = charge(card, total).unwrap()
    receipt = save_order(cart, payment).unwrap()
    send_confirmation(receipt).unwrap()
    return receipt
```

```bash
errpath diagram examples/checkout.py place_order
```

prints this diagram, which GitHub draws for you in any README, issue or PR:

```mermaid
flowchart LR
  Start(["place_order"])
  Done((Success))
  S1["send_confirmation"]
  S1 -->|ok| Done
  E2[/"EmailError"/]
  S1 -->|err| E2
  S3["save_order"]
  S3 -->|ok| S1
  E4[/"DbError"/]
  S3 -->|err| E4
  S5["charge"]
  S5 -->|ok| S3
  E6[/"CardDeclined"/]
  S5 -->|err| E6
  D7{"if cart.has_coupon"}
  S8["validate_coupon"]
  S8 -->|ok| S5
  E9[/"CouponError"/]
  S8 -->|err| E9
  D7 -->|yes| S8
  D7 -->|no| S5
  S10["price"]
  S10 -->|ok| D7
  E11[/"PriceError"/]
  S10 -->|err| E11
  Start --> S10
  classDef error fill:#fdecea,stroke:#d93025,color:#a50e0e
  class E2,E4,E6,E9,E11 error
```

Every red box is a way `place_order` can fail. errpath reads them from the `-> Result[T, E]` annotations of the functions it calls.

It follows branches, loops, `try` / `except` / `finally` and `raise` (see [what the analyzer follows](#what-the-analyzer-follows)), and tells you about anything it can't.

For an interactive version, `errpath machine examples/checkout.py place_order` prints an [XState](https://stately.ai/docs/xstate) state machine you can open in [autovisualizer](https://auto-visualizer.vercel.app).

---

## Catch risky changes in pull requests

Say a PR changes one line:

```diff
-    send_confirmation(receipt).unwrap()
+    _ = send_confirmation(receipt)
```

The tests still pass. But a failed confirmation email now disappears without a trace. `errpath review` compares the error paths before and after, and posts:

> ## Error path review: high risk
>
> 1 function(s) changed, 1 new finding(s), risk=high
>
> ### New findings
>
> - `no-swallow` `_ =` drops the error from `send_confirmation` at `shop/checkout.py:72`
>
> ### `shop.checkout.place_order`
>
> - added swallow `send_confirmation`
> - removed step `send_confirmation`
>
> ▶ Diagram

What it flags:

| Finding | Example | Why it matters |
| --- | --- | --- |
| New crash point (`no-panic`) | `.unwrap()` outside `@safe` | raises instead of returning `Err` |
| Ignored error (`no-swallow`) | `_ = charge(card)`, or `charge(card)` on its own line | the failure vanishes |
| Changed error path | a step added, removed or moved out of a `try` | callers can now see different errors |

Risk is `low`, `moderate` or `high`.

### GitHub Action

```yaml
name: errpath
on: pull_request

permissions:
  contents: read
  pull-requests: write # to post the review comment

jobs:
  review:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
      - uses: jagreehal/errpath-python@v0
        with:
          fail-on: high # never, moderate or high
```

It keeps one comment up to date per PR, annotates new findings inline, and writes the report to the job summary. Run it locally with `errpath review --base main`.

---

## Turn errors into your own at the boundary

Low-level errors (`KeyError`, `DbError`) shouldn't leak out of your module. `map_err` changes the error and leaves a success alone:

```python
order = find_item(sku).map_err(lambda e: OrderError(f"unknown item {sku}"))
```

---

## With Pydantic and pydantic-ai

### Validation

Pydantic raises `ValidationError` for bad input. `@safe_with` turns that into a value, with Pydantic's field errors intact:

```python
from pydantic import BaseModel, ValidationError

from errpath import safe_with


class User(BaseModel):
    name: str


@safe_with(ValidationError)
def parse_user(data: object) -> User:
    return User.model_validate(data)


parse_user({"name": "Ada"})  # Ok(User(name='Ada'))
parse_user({})  # Err(ValidationError(...)): "name: Field required"
```

Then chain it with other steps that can fail: `parse_user(data).and_then(save_user)`.

### Results inside models

A `Result` can be a field of a Pydantic model. Both sides are validated, and the JSON says which one it is:

```python
class Response(BaseModel):
    result: Result[User, str]


Response(result=Ok(User(name="Ada"))).model_dump_json()
# {"result": {"ok": true, "value": {"name": "Ada"}}}

Response.model_validate_json('{"result": {"ok": false, "error": "not found"}}')
# Response(result=Err('not found'))

Response(result=Ok("not a User"))  # ValidationError
```

It also appears in `model_json_schema()`, so FastAPI and other API tools document it.

For results that travel through APIs, use a model, `str` or enum as the error type. An exception error is written as `{"type": "KeyError", "message": "..."}` but can't be read back, because an exception isn't data.

A `str` or model error can't be raised, so `.unwrap()` isn't available on `Result[User, str]`: your type checker flags it. Use `match`, `.unwrap_or(default)`, or turn the error into an exception first with `.map_err(NotFound).unwrap()`.

### pydantic-ai

Two patterns, both in [examples/pydantic_ai_agent.py](examples/pydantic_ai_agent.py):

```python
@agent.tool_plain(retries=2)
def price_of(sku: str) -> int:
    result = find_price(sku)  # your code: Result[int, UnknownItem]
    if not ok(result):
        raise ModelRetry(f"unknown item {sku}")  # the model reads this and tries again
    return result.value


@safe_async_with(UsageLimitExceeded, UnexpectedModelBehavior)
async def ask(prompt: str) -> str:  # Result[str, UsageLimitExceeded | UnexpectedModelBehavior]
    return (await agent.run(prompt)).output
```

1. **In a tool**, turn an `Err` into `ModelRetry`. Don't return `Ok`/`Err` from a tool: pydantic-ai can't send them to the model.
2. **Around `agent.run`**, `@safe_async_with` gives your caller a typed `Result` instead of exceptions to remember.

The example runs offline with a scripted model. To try it with a local model:

```bash
OLLAMA_BASE_URL=http://localhost:11434/v1 ERRPATH_MODEL=ollama:qwen3.5:4b \
  uv run python examples/pydantic_ai_agent.py
```

---

## Putting it together

One file: validate input, run domain steps, handle every error, see the paths. Copy it, or run it from [examples/signup.py](examples/signup.py):

```python
"""errpath end to end: validate input, run domain steps, handle every error, see the paths.

Run it:          uv run python examples/signup.py
See every path:  uv run errpath diagram examples/signup.py register
"""

from collections.abc import Mapping
from dataclasses import dataclass

from pydantic import BaseModel, Field, ValidationError

from errpath import Err, Ok, Result, safe_with

# 1. Validate input. Pydantic's ValidationError becomes an Err, with its field errors.


class SignupForm(BaseModel):
    email: str = Field(pattern=r"^[^@\s]+@[^@\s]+$")
    password: str = Field(min_length=8)


@safe_with(ValidationError)
def parse_form(data: Mapping[str, object]) -> SignupForm:
    return SignupForm.model_validate(data)


# 2. Domain steps return Results: how each one can fail is in its signature.


class EmailTaken(Exception):
    pass


class MailerDown(Exception):
    pass


@dataclass
class Account:
    id: int
    email: str


registered = {"taken@example.com"}


def reserve_email(email: str) -> Result[str, EmailTaken]:
    if email in registered:
        return Err(EmailTaken(email))
    registered.add(email)
    return Ok(email)


def send_welcome(account: Account) -> Result[None, MailerDown]:
    if account.email.endswith("@offline.example"):
        return Err(MailerDown("mail server unreachable"))
    return Ok(None)


# 3. Compose: the happy path reads top to bottom; the first Err stops it.


@safe_with(ValidationError, EmailTaken, MailerDown)
def register(data: Mapping[str, object]) -> Account:
    form = parse_form(data).unwrap()
    email = reserve_email(form.email).unwrap()
    account = Account(id=len(registered), email=email)
    send_welcome(account).unwrap()
    return account


# 4. Handle every error at the boundary, e.g. as an HTTP response.


def handle(data: Mapping[str, object]) -> tuple[int, object]:
    match register(data):
        case Ok(account):
            return 201, {"id": account.id}
        case Err(ValidationError() as error):
            return 422, [e["msg"] for e in error.errors()]
        case Err(EmailTaken()):
            return 409, "email already registered"
        case Err(MailerDown()):
            return 503, "try again later"
        case Err(error):
            raise AssertionError(f"unhandled error: {error!r}")


if __name__ == "__main__":
    for data in [
        {"email": "ada@example.com", "password": "correct horse"},
        {"email": "not-an-email", "password": "short"},
        {"email": "taken@example.com", "password": "correct horse"},
        {"email": "bob@offline.example", "password": "correct horse"},
    ]:
        print(data["email"], "->", *handle(data))
```

```bash
uv run python examples/signup.py
# ada@example.com -> 201 {'id': 2}
# not-an-email -> 422 [...Pydantic's field errors...]
# taken@example.com -> 409 email already registered
# bob@offline.example -> 503 try again later

uv run errpath diagram examples/signup.py register
```

```mermaid
flowchart LR
  Start(["register"])
  Done((Success))
  S1["send_welcome"]
  S1 -->|ok| Done
  E2[/"MailerDown"/]
  S1 -->|err| E2
  S3["reserve_email"]
  S3 -->|ok| S1
  E4[/"EmailTaken"/]
  S3 -->|err| E4
  S5["parse_form"]
  S5 -->|ok| S3
  E6[/"ValidationError"/]
  S5 -->|err| E6
  Start --> S5
  classDef error fill:#fdecea,stroke:#d93025,color:#a50e0e
  class E2,E4,E6 error
```

Every error in `register`'s signature has a box, and `handle` has a `case` for each one.

---

## What the analyzer follows

errpath reads your code without running it. It draws:

- calls to functions that return `Result`, whether annotated `-> Result[T, E]` or decorated with `@safe` / `@safe_with(...)`
- `.unwrap()`, `return Ok(...)` / `return Err(...)` (including `x if cond else y`), and `raise`
- `if` / `elif` / `else`, `match`, `for` and `while` (with `break` / `continue`), `with`, and `await`
- `try` / `except` / `else` / `finally`, including `except*`: each error goes to the handler that would catch it, through any `finally`

When it sees a `Result` it can't place on the diagram, such as one inside a condition, a comprehension or another call's arguments, it says so instead of quietly drawing less:

```text
errpath: note: shop.py:14: Result used inside an expression; its error path isn't drawn: check(email)
```

`errpath diagram` and `errpath machine` print these notes, `errpath review` lists them (marking new ones), and `errpath ir` includes them. An `.unwrap()` in such a spot outside `@safe` is still flagged as a crash point, unless it's inside a lambda: errpath can't tell if or when a lambda runs, so that gets a note only.

It doesn't see calls made through a variable or callback (`step = check; step(x)`), or a module function called as a method on a local object (`client.charge()`).

---

## Quick reference

### Methods

| Method | On `Ok(value)` | On `Err(error)` |
| --- | --- | --- |
| `.unwrap()` | returns `value` | raises `error` |
| `.unwrap_or(default)` | returns `value` | returns `default` |
| `.map(f)` | `Ok(f(value))` | unchanged |
| `.map_err(f)` | unchanged | `Err(f(error))` |
| `.and_then(f)` | `f(value)`, a step that can fail | unchanged |

### Helpers

| Helper | Does |
| --- | --- |
| `ok(r)` | `True` for `Ok`; your editor then knows the types of `r.value` and `r.error` |
| `err_type(r, KeyError)` | `True` if `r` failed with a `KeyError` (or a subclass) |
| `traceback_of(r)` | the error's stack trace as text, for logging |

### Decorators

| Decorator | Catches | Returns |
| --- | --- | --- |
| `@safe` | any `Exception` | `Result[T, Exception]` |
| `@safe_with(A, B)` | only `A` and `B` | `Result[T, A \| B]` |
| `@safe_async`, `@safe_async_with(A, B)` | the same, for `async def` | the same, awaited |

### CLI

| Command | Prints |
| --- | --- |
| `errpath diagram <path> <function>` | Mermaid diagram |
| `errpath machine <path> <function>` | XState state machine (JSON) |
| `errpath review --base <ref>` | PR review (Markdown, or JSON with `--format json`) |
| `errpath ir [path]` | everything errpath found, as JSON |

---

## Common pitfalls

- **`r.is_ok()` doesn't tell your editor the types.** Python's type checkers can't narrow through a method. Use `ok(r)` or `match`.
- **`.unwrap()` outside `@safe` raises.** That's fine in a script, but `errpath review` flags it as a new crash point.
- **`@safe` also catches your bugs.** A `KeyError` from a typo becomes an `Err` like any expected failure. Name the errors you expect with `@safe_with(...)`, and keep `@safe` for a deliberate catch-all.
- **`.unwrap()` is for exception errors.** Python can't raise a `str` or a model, so type checkers reject `.unwrap()` on `Result[int, str]`. (Unchecked code gets a `RuntimeError` saying what to do.) Use `match`, `.unwrap_or(default)`, or `.map_err(SomeError).unwrap()`.
- **Don't drop a result.** `_ = charge(card)` and a bare `charge(card)` both throw the error away.
- **Annotate what can fail.** errpath names errors from `-> Result[T, E]` annotations. Without one, a step's error shows as `Error`.
- **Results can't be changed.** Build a new one instead: `Ok(new_value)`.

---

## When to use errpath

**Use it when:**

- you want the ways a function can fail to be part of its signature
- you want to see, and review, how errors flow through your code

**Skip it when:**

- exceptions are fine for you, as in most small scripts
- you want a full functional-programming toolkit (`Maybe`, `IO`, pipelines): look at [returns](https://github.com/dry-python/returns)

errpath's `Result` is deliberately small, and inspired by [safe-result](https://github.com/overflowy/safe-result). What it adds is the analysis: diagrams and PR reviews of your error paths.

---

## Development

Uses [uv](https://docs.astral.sh/uv/), [ruff](https://docs.astral.sh/ruff/) and [ty](https://docs.astral.sh/ty/).

```bash
uv sync             # install
uv run pytest       # test
uv run ruff check   # lint
uv run ruff format  # format
uv run ty check     # type check
```

## License

MIT
