k98kurz icon

result.py

k98kurz | PRO | 01/27/26 04:56:20 PM UTC (Edited) | 0 ⭐ | 12760 👁️ | Never ⏰ | [Functional]
Python |

1.84 KB

|

Source Code

|

0 👍

/

0 👎

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."""

Comments

  •  icon
    01/01/70 12:00:00 AM UTC
    Plain Text |

    0 B

    |

    👍

    /

    👎

    
        
  •  icon
    01/01/70 12:00:00 AM UTC
    Plain Text |

    0 B

    |

    👍

    /

    👎