IC Improve Code Recipes

Recipe 5.5 · Python

A Result Type for Expected Failures

The Python listings are conversions of the book's C# code to Python 3.12. Each file's header says what it needs to run. The explanations were written for the C# version, so some names in the text refer to .NET.

Problem

Some failures are part of normal business: insufficient funds, an expired coupon, a duplicate registration. Throwing exceptions for them is slow under load, hides the possible outcomes from the method signature, and turns ordinary control flow into try/catch. Returning null or false loses the reason.

The way it's often written

Anti-pattern: shown so you can recognize it. Don't copy this one.

Requirements: Python 3.12+. Standard library only, nothing to install.

Python Returning a bool and smuggling the failure reason through a string (p112_r5_5_bool_with_error_string_before.py)
"""Returning a bool and smuggling the failure reason through a string

Source: ImproveCode, Chapter 5, Recipe 5.5 "A Result Type for Expected Failures"
Section: The way it's often written
Book page: 112  -- original C# listing
Converted from C# to Python.
ANTI-PATTERN: kept deliberately faithful to the C# 'not to copy' example; do not use.
Python has no out parameters, so the out string becomes the second item of a tuple.
"""

from __future__ import annotations

from decimal import Decimal


class Account:
    def __init__(self, balance: Decimal) -> None:
        self.balance = balance

    # Not this: the reason is lost, or smuggled out through a string.
    def withdraw(self, amount: Decimal) -> tuple[bool, str | None]:
        error = None
        if amount > self.balance:
            error = "Insufficient funds"
            return False, error
        self.balance -= amount
        return True, error

The improved recipe

A small Result<T> carries either a value or an Error with a code and message. Implicit conversions keep call sites short.

A domain class that uses it, and an extension that turns a result into an HTTP response:

Usage in a minimal API endpoint:

Requirements: Python 3.12+. Standard library only, nothing to install.

Python A generic Result type for expected failures (p112_r5_5_generic_result_type.py)
"""A generic Result type for expected failures

Source: ImproveCode, Chapter 5, Recipe 5.5 "A Result Type for Expected Failures"
Section: The improved recipe
Book page: 112-113  -- original C# listing
Converted from C# to Python.
Uses PEP 695 generics (Python 3.12) and a frozen dataclass for Error; Python has no
implicit conversion operators, so callers use Result.success()/Result.failure().
"""

from __future__ import annotations

from dataclasses import dataclass
from typing import Callable, ClassVar


@dataclass(frozen=True)
class Error:
    code: str
    message: str

    NONE: ClassVar[Error]


Error.NONE = Error("", "")


class Result[T]:
    __slots__ = ("_value", "_is_success", "_error")

    def __init__(self, is_success: bool, value: T | None, error: Error) -> None:
        if error is None:
            raise ValueError("error must not be None")
        self._is_success = is_success
        self._value = value
        self._error = error

    @property
    def is_success(self) -> bool:
        return self._is_success

    @property
    def is_failure(self) -> bool:
        return not self._is_success

    @property
    def error(self) -> Error:
        return self._error

    @property
    def value(self) -> T:
        if not self._is_success:
            raise RuntimeError(
                f"Cannot read Value of a failed result ({self._error.code}).")
        return self._value  # type: ignore[return-value]

    @classmethod
    def success(cls, value: T) -> Result[T]:
        return cls(True, value, Error.NONE)

    @classmethod
    def failure(cls, error: Error) -> Result[T]:
        return cls(False, None, error)

    def match[TOut](
        self, on_success: Callable[[T], TOut], on_failure: Callable[[Error], TOut]
    ) -> TOut:
        return on_success(self._value) if self._is_success else on_failure(self._error)  # type: ignore[arg-type]

Requirements: Python 3.12+. Install: pip install fastapi

Python Account withdrawal returning a Result, and mapping it to an HTTP response (p113_r5_5_account_withdraw_result_http.py)
"""Account withdrawal returning a Result, and mapping it to an HTTP response

Source: ImproveCode, Chapter 5, Recipe 5.5 "A Result Type for Expected Failures"
Section: The improved recipe
Book page: 113-114  -- original C# listing
Converted from C# to Python.
FastAPI JSONResponse replaces Results.Ok/Results.Problem; Result and Error come from
p112_r5_5_generic_result_type.py (minimal copies here for a self-contained file).
"""

from __future__ import annotations

from dataclasses import dataclass
from decimal import Decimal
from typing import Any, Callable

from fastapi.responses import JSONResponse


@dataclass(frozen=True)
class Error:
    code: str
    message: str


class Result[T]:
    def __init__(self, ok: bool, value: T | None, error: Error | None) -> None:
        self.is_success, self._value, self.error = ok, value, error

    @classmethod
    def success(cls, value: T) -> Result[T]:
        return cls(True, value, None)

    @classmethod
    def failure(cls, error: Error) -> Result[T]:
        return cls(False, None, error)

    def match[TOut](self, on_success: Callable[[T], TOut],
                    on_failure: Callable[[Error], TOut]) -> TOut:
        return on_success(self._value) if self.is_success else on_failure(self.error)  # type: ignore[arg-type]


class AccountErrors:
    INSUFFICIENT_FUNDS = Error(
        "insufficient_funds", "The balance is too low.")

    INVALID_AMOUNT = Error(
        "invalid_amount", "The amount must be greater than zero.")


class Account:
    def __init__(self, opening_balance: Decimal) -> None:
        self._balance = opening_balance

    @property
    def balance(self) -> Decimal:
        return self._balance

    def withdraw(self, amount: Decimal) -> Result[Decimal]:
        if amount <= 0:
            return Result.failure(AccountErrors.INVALID_AMOUNT)

        if amount > self._balance:
            return Result.failure(AccountErrors.INSUFFICIENT_FUNDS)

        self._balance -= amount
        return Result.success(self._balance)  # new balance


def to_http_result(result: Result[Any]) -> JSONResponse:
    return result.match(
        lambda value: JSONResponse(content=str(value) if isinstance(value, Decimal) else value),
        lambda error: JSONResponse(
            status_code=422,
            media_type="application/problem+json",
            content={
                "status": 422,
                "title": error.message,
                "errorCode": error.code,
            }),
    )

Requirements: Python 3.12+. Install: pip install fastapi

Python Minimal API endpoint that withdraws and maps the Result to HTTP (p114_r5_5_withdraw_endpoint_mapping.py)
"""Minimal API endpoint that withdraws and maps the Result to HTTP

Source: ImproveCode, Chapter 5, Recipe 5.5 "A Result Type for Expected Failures"
Section: The improved recipe
Book page: 114  -- original C# listing
Converted from C# to Python.
A FastAPI route with Depends replaces app.MapPost with an injected AccountStore;
to_http_result is from p113_r5_5_account_withdraw_result_http.py.
"""

from __future__ import annotations

from decimal import Decimal
from typing import Any, Callable

from fastapi import Depends, FastAPI


def map_withdraw(
    app: FastAPI,
    get_account_store: Callable[[], Any],
    to_http_result: Callable[[Any], Any],
) -> None:
    @app.post("/accounts/{id}/withdraw")
    def withdraw(id: int, amount: Decimal, store: Any = Depends(get_account_store)) -> Any:
        return to_http_result(store.get(id).withdraw(amount))

How it works

The return type now tells the truth: Withdraw can succeed with a new balance or fail with one of the listed errors. A caller has to look at IsSuccess (or call Match) to get the value, and reading Value on a failure throws, so a forgotten check is loud rather than silently wrong.

The implicit conversions let the method return AccountErrors.InsufficientFunds; or return Balance; without ceremony. The errors are static instances with stable codes, which makes them easy to test (Assert.Equal(AccountErrors.InsufficientFunds, result.Error)) and easy to document for API clients. Because Error is a record, equality compares code and message.

Match forces both branches to be handled and is how the result leaves the domain. The HTTP extension maps every failure to a 422 ProblemDetails with the same errorCode field the global handler in Recipe 5.4 uses, so clients see one error shape whether the failure came from a Result or an exception.

My rule for choosing: if the caller is expected to handle the failure as part of normal flow, use a Result. If the failure means something is broken (database down, bug, misconfiguration), throw. Exceptions remain the right tool for the unexpected.

Variations and pitfalls

  • Add a non-generic Result for operations with no return value, using the same shape.
  • Don't wrap every method in Result. Using it for code that cannot fail in an expected way adds noise and teaches people to ignore it.
  • If T is itself Error or object, the implicit conversions become ambiguous. Use Success(...) and Failure(...) explicitly in that case.
  • Libraries such as FluentResults, ErrorOr and OneOf offer richer versions with chaining (Bind, Map) and multiple errors. They are fine choices; the version here is small enough to own and explain to a new team member in five minutes.
  • Don't mix styles inside one operation. A method that returns a Result and also throws for the same kind of failure makes callers handle both.