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:
@safestops at the first failure, with noifafter 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+.
uv add errpath # or: pip install errpath
The problem
A Python signature can't say what a function raises:
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
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:
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:
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
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 isResult[T, A | B]. Anything else still raises, as a bug should.@safecatches anyException, bugs included: a typo'sKeyErrorcomes back as anErrinstead of crashing. Use it deliberately, as a catch-all at an outer boundary or around code you don't own. Prefer@safe_with.@safe_asyncand@safe_async_withdo the same forasync def. They never catchasyncio.CancelledError.
It also wraps existing code that raises:
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):
@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
errpath diagram examples/checkout.py place_order
prints this diagram, which GitHub draws for you in any README, issue or PR:
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), and tells you about anything it can't.
For an interactive version, errpath machine examples/checkout.py place_order prints an XState state machine you can open in autovisualizer.
Catch risky changes in pull requests
Say a PR changes one line:
- 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 fromsend_confirmationatshop/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
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:
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:
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:
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:
@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
- In a tool, turn an
ErrintoModelRetry. Don't returnOk/Errfrom a tool: pydantic-ai can't send them to the model. - Around
agent.run,@safe_async_withgives your caller a typedResultinstead of exceptions to remember.
The example runs offline with a scripted model. To try it with a local model:
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:
"""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))
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
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(...)(includingx if cond else y), andraiseif/elif/else,match,forandwhile(withbreak/continue),with, andawaittry/except/else/finally, includingexcept*: each error goes to the handler that would catch it, through anyfinally
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:
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. Useok(r)ormatch..unwrap()outside@saferaises. That's fine in a script, buterrpath reviewflags it as a new crash point.@safealso catches your bugs. AKeyErrorfrom a typo becomes anErrlike any expected failure. Name the errors you expect with@safe_with(...), and keep@safefor a deliberate catch-all..unwrap()is for exception errors. Python can't raise astror a model, so type checkers reject.unwrap()onResult[int, str]. (Unchecked code gets aRuntimeErrorsaying what to do.) Usematch,.unwrap_or(default), or.map_err(SomeError).unwrap().- Don't drop a result.
_ = charge(card)and a barecharge(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 asError. - 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
errpath's Result is deliberately small, and inspired by safe-result. What it adds is the analysis: diagrams and PR reviews of your error paths.
Development
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
Metadata
Release files for errpath 0.1.0
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 |
|---|---|---|---|---|
| errpath-0.1.0.tar.gz | 111.9 kB | With provenance | Details for errpath-0.1.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| errpath-0.1.0-py3-none-any.whl | Python 3 | none | any | Details for errpath-0.1.0-py3-none-any.whl |
Total release size: 149.5 kB
Release files / errpath-0.1.0.tar.gz
| Download URL | errpath-0.1.0.tar.gz |
|---|---|
| Size | 111.9 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
a34fdf639e5ad693c77c1747cb4acfbba8c9f40d95d3d6d510620b659cf23122
|
|
BLAKE2b-256 checksum How to use checksums |
c9e350022b8181ef674b862e9122d2b6b7ea8b00c0a881a3ff047261b4949304
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.14
|
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 15, 2026.
Transparency logRelease files / errpath-0.1.0-py3-none-any.whl
| Download URL | errpath-0.1.0-py3-none-any.whl |
|---|---|
| Size | 37.7 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
4515251e6acaaa1bf0691dff264221b4f648b1b8db3772491ac45a16173e96d9
|
|
BLAKE2b-256 checksum How to use checksums |
9e4e69fcd50470e45176f6a4d1fc269d852d17ca53486dc44de578afb7176138
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.14
|
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 15, 2026.
Transparency logSecurity for errpath 0.1.0
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 errpath-0.1.0.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 15, 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.