m7md

Untitled 337

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