k98kurz

result.py

Jan 26th, 2026 (edited)
2,979
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.84 KB | Source Code | 0 0
  1. from __future__ import annotations
  2. from dataclasses import dataclass
  3. from typing import Any, Callable, Generic, TypeVar
  4.  
  5.  
  6. T = TypeVar('T')
  7. U = TypeVar('U')
  8.  
  9. @dataclass
  10. class Ok(Generic[T]):
  11.     data: T
  12.     success: bool = True
  13.     def map(self, fn: Callable[[T], U]) -> Result[U]:
  14.         return try_except(fn, self.data)
  15.  
  16. @dataclass
  17. class Err:
  18.     error: Exception
  19.     success: bool = False
  20.     def map(self, fn: Callable[..., object]) -> Err:
  21.         return self
  22.  
  23. Result = Ok[T] | Err
  24.  
  25. def success(data: T) -> Ok[T]:
  26.     return Ok(data)
  27.  
  28. def failure(error: Exception) -> Err:
  29.     return Err(error)
  30.  
  31. def try_except(fn: Callable[[...], T], *args, **kwargs) -> Result[T]: # type: ignore
  32.     try:
  33.         return success(fn(*args, **kwargs))
  34.     except Exception as e:
  35.         return failure(e) # type: ignore
  36.  
  37. def pipe(
  38.         initial: Any,
  39.         *fns: Callable[[Result[T]], Result[T]]
  40.     ) -> Result[T]:
  41.     result = initial if isinstance(initial, (Ok, Err)) else success(initial)
  42.     for fn in fns:
  43.         if result.success:
  44.             result = fn(result)
  45.     return result
  46.  
  47. """Copyright (c) 2026 Jonathan Voss (k98kurz)
  48.  
  49. Permission to use, copy, modify, and/or distribute this software
  50. for any purpose with or without fee is hereby granted, provided
  51. that the above copyright notice and this permission notice appear in
  52. all copies.
  53.  
  54. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
  55. WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
  56. WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
  57. AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR
  58. CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  59. OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
  60. NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
  61. CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE."""
Tags: Functional
Advertisement