Last active
January 27, 2026 17:56
-
-
Save k98kurz/20c77ca0adc79c81f8126ba8fefffae0 to your computer and use it in GitHub Desktop.
result.py: try_catch, Result type, and a pipe function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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.""" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment