Python

Result / Either with Generics

admin by @admin ADMIN
Jun 16, 2026
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Encode "this might fail" in the type signature instead of throwing. Python 3.12+ generics syntax keeps it compact. Forces the caller to handle the failure branch.
Python
Raw
from dataclasses import dataclass

@dataclass(frozen=True, slots=True)
class Ok[T]:
    value: T

@dataclass(frozen=True, slots=True)
class Err[E]:
    error: E

type Result[T, E] = Ok[T] | Err[E]

def parse_int(s: str) -> Result[int, str]:
    try:
        return Ok(int(s))
    except ValueError:
        return Err(f"Not an integer: {s!r}")

match parse_int("42"):
    case Ok(value):  print("got", value)
    case Err(error): print("failed:", error)
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.