Result types for Python. See every error path.
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.
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 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.
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.
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.
- 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:
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.
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).
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().
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 Err into ModelRetry. Don't return Ok/Err from a tool: pydantic-ai can't send them to the model. 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:
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.
errpath reads your code without running it. It draws:
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()).
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.
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
Both files in this release have provenance metadata.
error-handling machinejson railway result static-analysis xstate
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
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 verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 15, 2026.
Both files in this release have been uploaded with provenance metadata.
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.




