from __future__ import annotations
from dataclasses import dataclass
from typing import Callable, Generic, TypeVar
T = TypeVar('T')
U = TypeVar('U')
E = TypeVar('E')
@dataclass
class Ok(Generic[T]):
data: T
success: bool = True
def map(self, fn: Callable[[T], U]) -> Result[U, E]:
return try_except(fn, self.data)
@dataclass
class Err(Generic[E]):
error: E
success: bool = False
def map(self, fn: Callable[..., object]) -> Err[E]:
return self
Result = Ok[T] | Err[E]
def success(data: T) -> Ok[T]:
return Ok(data)
def failure(error: E) -> Err[E]:
return Err(error)
def try_except(fn: Callable[[...], T], *args, **kwargs) -> Result[T, E]:
try:
return success(fn(*args, **kwargs))
except Exception as e:
return failure(e)
def pipe(
result: Result[T, E],
*fns: tuple[Callable[[Result[T, E]], Result[T, E]], ...]
) -> Result[T, E]:
for fn in fns:
if result.success:
result = fn(result)
return result
"""Copyright (c) 2026 Jonathan Voss (k98kurz)
Permission to use, copy, modify, and/or distribute this software
for any purpose with or without fee is hereby granted, provided
that the above copyright notice and this permission notice appear in
all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR
CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE."""