Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from __future__ import annotations
- from dataclasses import dataclass
- from typing import Any, Callable, Generic, TypeVar
- T = TypeVar('T')
- U = TypeVar('U')
- @dataclass
- class Ok(Generic[T]):
- data: T
- success: bool = True
- def map(self, fn: Callable[[T], U]) -> Result[U]:
- return try_except(fn, self.data)
- @dataclass
- class Err:
- error: Exception
- success: bool = False
- def map(self, fn: Callable[..., object]) -> Err:
- return self
- Result = Ok[T] | Err
- def success(data: T) -> Ok[T]:
- return Ok(data)
- def failure(error: Exception) -> Err:
- return Err(error)
- def try_except(fn: Callable[[...], T], *args, **kwargs) -> Result[T]: # type: ignore
- try:
- return success(fn(*args, **kwargs))
- except Exception as e:
- return failure(e) # type: ignore
- def pipe(
- initial: Any,
- *fns: Callable[[Result[T]], Result[T]]
- ) -> Result[T]:
- result = initial if isinstance(initial, (Ok, Err)) else success(initial)
- 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."""
Advertisement