Skip to content

core.result

src.core.result

Result types for railway-oriented programming.

This module implements the Result pattern to handle operations that can fail without using exceptions. This approach makes error handling explicit and testable.

Usage

def divide(a: float, b: float) -> Result[float, str]: if b == 0: return Failure("Division by zero") return Success(a / b)

result = divide(10, 2) match result: case Success(value): print(f"Result: {value}") case Failure(error): print(f"Error: {error}")

Classes

Success dataclass

Bases: Generic[T]

Represents a successful operation result.

Attributes:

Name Type Description
value T

The successful result value.

Note

Uses kw_only=True for explicit construction. Pattern matching must use keyword syntax: case Success(value=v): # Correct case Success(v): # Error!

Source code in src/core/result.py
@dataclass(frozen=True, slots=True, kw_only=True)
class Success(Generic[T]):
    """Represents a successful operation result.

    Attributes:
        value: The successful result value.

    Note:
        Uses kw_only=True for explicit construction.
        Pattern matching must use keyword syntax:
            case Success(value=v):  # Correct
            case Success(v):        # Error!
    """

    value: T

Failure dataclass

Bases: Generic[E]

Represents a failed operation result.

Attributes:

Name Type Description
error E

The error that occurred.

Note

Uses kw_only=True for explicit construction. Pattern matching must use keyword syntax: case Failure(error=e): # Correct case Failure(e): # Error!

Source code in src/core/result.py
@dataclass(frozen=True, slots=True, kw_only=True)
class Failure(Generic[E]):
    """Represents a failed operation result.

    Attributes:
        error: The error that occurred.

    Note:
        Uses kw_only=True for explicit construction.
        Pattern matching must use keyword syntax:
            case Failure(error=e):  # Correct
            case Failure(e):        # Error!
    """

    error: E