crashbytes-result 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- crashbytes_result/__init__.py +5 -0
- crashbytes_result/_core.py +182 -0
- crashbytes_result/py.typed +0 -0
- crashbytes_result-1.0.0.dist-info/METADATA +87 -0
- crashbytes_result-1.0.0.dist-info/RECORD +7 -0
- crashbytes_result-1.0.0.dist-info/WHEEL +4 -0
- crashbytes_result-1.0.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
"""Result type for explicit error handling — Ok[T] | Err[E]."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import functools
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
from typing import TYPE_CHECKING, Any, Generic, NoReturn, TypeVar
|
|
8
|
+
|
|
9
|
+
if TYPE_CHECKING:
|
|
10
|
+
from collections.abc import Callable
|
|
11
|
+
|
|
12
|
+
T = TypeVar("T")
|
|
13
|
+
U = TypeVar("U")
|
|
14
|
+
E = TypeVar("E")
|
|
15
|
+
F = TypeVar("F")
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass(frozen=True, slots=True)
|
|
19
|
+
class Ok(Generic[T]):
|
|
20
|
+
"""Represents a successful result containing a value."""
|
|
21
|
+
|
|
22
|
+
_value: T
|
|
23
|
+
|
|
24
|
+
@property
|
|
25
|
+
def value(self) -> T:
|
|
26
|
+
return self._value
|
|
27
|
+
|
|
28
|
+
@property
|
|
29
|
+
def is_ok(self) -> bool:
|
|
30
|
+
return True
|
|
31
|
+
|
|
32
|
+
@property
|
|
33
|
+
def is_err(self) -> bool:
|
|
34
|
+
return False
|
|
35
|
+
|
|
36
|
+
def unwrap(self) -> T:
|
|
37
|
+
"""Return the contained value."""
|
|
38
|
+
return self._value
|
|
39
|
+
|
|
40
|
+
def unwrap_or(self, default: object) -> T:
|
|
41
|
+
"""Return the contained value (ignores default)."""
|
|
42
|
+
return self._value
|
|
43
|
+
|
|
44
|
+
def unwrap_err(self) -> NoReturn:
|
|
45
|
+
"""Raise because this is Ok, not Err."""
|
|
46
|
+
raise UnwrapError(f"Called unwrap_err on Ok({self._value!r})")
|
|
47
|
+
|
|
48
|
+
def map(self, fn: Callable[[T], U]) -> Ok[U]:
|
|
49
|
+
"""Apply *fn* to the contained value."""
|
|
50
|
+
return Ok(fn(self._value))
|
|
51
|
+
|
|
52
|
+
def map_err(self, fn: Callable[[Any], Any]) -> Ok[T]:
|
|
53
|
+
"""No-op for Ok — return self."""
|
|
54
|
+
return self
|
|
55
|
+
|
|
56
|
+
def bind(self, fn: Callable[[T], Result[U, Any]]) -> Result[U, Any]:
|
|
57
|
+
"""Apply *fn* that returns a Result."""
|
|
58
|
+
return fn(self._value)
|
|
59
|
+
|
|
60
|
+
def match(
|
|
61
|
+
self,
|
|
62
|
+
ok: Callable[[T], U],
|
|
63
|
+
err: Callable[[Any], U],
|
|
64
|
+
) -> U:
|
|
65
|
+
"""Pattern match — calls *ok* branch."""
|
|
66
|
+
return ok(self._value)
|
|
67
|
+
|
|
68
|
+
def __repr__(self) -> str:
|
|
69
|
+
return f"Ok({self._value!r})"
|
|
70
|
+
|
|
71
|
+
# Support Python 3.10+ structural pattern matching
|
|
72
|
+
__match_args__ = ("_value",)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
@dataclass(frozen=True, slots=True)
|
|
76
|
+
class Err(Generic[E]):
|
|
77
|
+
"""Represents a failed result containing an error."""
|
|
78
|
+
|
|
79
|
+
_error: E
|
|
80
|
+
|
|
81
|
+
@property
|
|
82
|
+
def error(self) -> E:
|
|
83
|
+
return self._error
|
|
84
|
+
|
|
85
|
+
@property
|
|
86
|
+
def is_ok(self) -> bool:
|
|
87
|
+
return False
|
|
88
|
+
|
|
89
|
+
@property
|
|
90
|
+
def is_err(self) -> bool:
|
|
91
|
+
return True
|
|
92
|
+
|
|
93
|
+
def unwrap(self) -> NoReturn:
|
|
94
|
+
"""Raise because this is Err."""
|
|
95
|
+
raise UnwrapError(f"Called unwrap on Err({self._error!r})")
|
|
96
|
+
|
|
97
|
+
def unwrap_or(self, default: T) -> T:
|
|
98
|
+
"""Return *default* because this is Err."""
|
|
99
|
+
return default
|
|
100
|
+
|
|
101
|
+
def unwrap_err(self) -> E:
|
|
102
|
+
"""Return the contained error."""
|
|
103
|
+
return self._error
|
|
104
|
+
|
|
105
|
+
def map(self, fn: Callable[[Any], Any]) -> Err[E]:
|
|
106
|
+
"""No-op for Err — return self."""
|
|
107
|
+
return self
|
|
108
|
+
|
|
109
|
+
def map_err(self, fn: Callable[[E], F]) -> Err[F]:
|
|
110
|
+
"""Apply *fn* to the contained error."""
|
|
111
|
+
return Err(fn(self._error))
|
|
112
|
+
|
|
113
|
+
def bind(self, fn: Callable[[Any], Any]) -> Err[E]:
|
|
114
|
+
"""No-op for Err — return self."""
|
|
115
|
+
return self
|
|
116
|
+
|
|
117
|
+
def match(
|
|
118
|
+
self,
|
|
119
|
+
ok: Callable[[Any], U],
|
|
120
|
+
err: Callable[[E], U],
|
|
121
|
+
) -> U:
|
|
122
|
+
"""Pattern match — calls *err* branch."""
|
|
123
|
+
return err(self._error)
|
|
124
|
+
|
|
125
|
+
def __repr__(self) -> str:
|
|
126
|
+
return f"Err({self._error!r})"
|
|
127
|
+
|
|
128
|
+
__match_args__ = ("_error",)
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
Result = Ok[T] | Err[E]
|
|
132
|
+
"""Type alias: a value is either ``Ok[T]`` or ``Err[E]``."""
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
class UnwrapError(Exception):
|
|
136
|
+
"""Raised when unwrapping a Result incorrectly."""
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def safe(
|
|
140
|
+
*args: Any,
|
|
141
|
+
) -> Any:
|
|
142
|
+
"""Decorator that wraps a function to return ``Ok`` or ``Err``.
|
|
143
|
+
|
|
144
|
+
Usage::
|
|
145
|
+
|
|
146
|
+
@safe
|
|
147
|
+
def parse_int(s: str) -> int:
|
|
148
|
+
return int(s)
|
|
149
|
+
|
|
150
|
+
@safe(ValueError, KeyError)
|
|
151
|
+
def lookup(data: dict, key: str) -> str:
|
|
152
|
+
return data[key]
|
|
153
|
+
"""
|
|
154
|
+
if len(args) == 1 and callable(args[0]) and not (
|
|
155
|
+
isinstance(args[0], type) and issubclass(args[0], BaseException)
|
|
156
|
+
):
|
|
157
|
+
fn = args[0]
|
|
158
|
+
|
|
159
|
+
@functools.wraps(fn)
|
|
160
|
+
def wrapper(*a: Any, **kw: Any) -> Any:
|
|
161
|
+
try:
|
|
162
|
+
return Ok(fn(*a, **kw))
|
|
163
|
+
except Exception as exc:
|
|
164
|
+
return Err(exc)
|
|
165
|
+
|
|
166
|
+
return wrapper
|
|
167
|
+
|
|
168
|
+
exceptions = tuple(args)
|
|
169
|
+
if not exceptions:
|
|
170
|
+
exceptions = (Exception,)
|
|
171
|
+
|
|
172
|
+
def decorator(fn: Callable[..., Any]) -> Callable[..., Any]:
|
|
173
|
+
@functools.wraps(fn)
|
|
174
|
+
def wrapper(*a: Any, **kw: Any) -> Any:
|
|
175
|
+
try:
|
|
176
|
+
return Ok(fn(*a, **kw))
|
|
177
|
+
except exceptions as exc:
|
|
178
|
+
return Err(exc)
|
|
179
|
+
|
|
180
|
+
return wrapper
|
|
181
|
+
|
|
182
|
+
return decorator
|
|
File without changes
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: crashbytes-result
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: A practical Result type for Python — Ok, Err, and pattern matching.
|
|
5
|
+
Project-URL: Homepage, https://github.com/CrashBytes/crashbytes-result
|
|
6
|
+
Project-URL: Repository, https://github.com/CrashBytes/crashbytes-result
|
|
7
|
+
Project-URL: Issues, https://github.com/CrashBytes/crashbytes-result/issues
|
|
8
|
+
Author-email: CrashBytes <crashbytes@users.noreply.github.com>
|
|
9
|
+
License-Expression: MIT
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Keywords: err,error-handling,monad,ok,pattern-matching,result
|
|
12
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
20
|
+
Classifier: Typing :: Typed
|
|
21
|
+
Requires-Python: >=3.10
|
|
22
|
+
Provides-Extra: dev
|
|
23
|
+
Requires-Dist: mypy; extra == 'dev'
|
|
24
|
+
Requires-Dist: pytest; extra == 'dev'
|
|
25
|
+
Requires-Dist: pytest-cov; extra == 'dev'
|
|
26
|
+
Requires-Dist: ruff; extra == 'dev'
|
|
27
|
+
Description-Content-Type: text/markdown
|
|
28
|
+
|
|
29
|
+
# crashbytes-result
|
|
30
|
+
|
|
31
|
+
A practical Result type for Python — `Ok`, `Err`, and pattern matching.
|
|
32
|
+
|
|
33
|
+
## Install
|
|
34
|
+
|
|
35
|
+
```bash
|
|
36
|
+
pip install crashbytes-result
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
## Usage
|
|
40
|
+
|
|
41
|
+
```python
|
|
42
|
+
from crashbytes_result import Ok, Err, Result, safe
|
|
43
|
+
|
|
44
|
+
def divide(a: float, b: float) -> Result[float, str]:
|
|
45
|
+
if b == 0:
|
|
46
|
+
return Err("division by zero")
|
|
47
|
+
return Ok(a / b)
|
|
48
|
+
|
|
49
|
+
result = divide(10, 3)
|
|
50
|
+
match result:
|
|
51
|
+
case Ok(value):
|
|
52
|
+
print(f"Result: {value}")
|
|
53
|
+
case Err(error):
|
|
54
|
+
print(f"Error: {error}")
|
|
55
|
+
|
|
56
|
+
# Or use .match()
|
|
57
|
+
msg = result.match(
|
|
58
|
+
ok=lambda v: f"Got {v:.2f}",
|
|
59
|
+
err=lambda e: f"Failed: {e}",
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
# @safe decorator
|
|
63
|
+
@safe
|
|
64
|
+
def parse_int(s: str) -> int:
|
|
65
|
+
return int(s)
|
|
66
|
+
|
|
67
|
+
parse_int("42") # Ok(42)
|
|
68
|
+
parse_int("abc") # Err(ValueError(...))
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
## API
|
|
72
|
+
|
|
73
|
+
| Method | Ok | Err |
|
|
74
|
+
|--------|-----|------|
|
|
75
|
+
| `.unwrap()` | Returns value | Raises `UnwrapError` |
|
|
76
|
+
| `.unwrap_or(default)` | Returns value | Returns default |
|
|
77
|
+
| `.unwrap_err()` | Raises `UnwrapError` | Returns error |
|
|
78
|
+
| `.map(fn)` | `Ok(fn(value))` | `self` |
|
|
79
|
+
| `.map_err(fn)` | `self` | `Err(fn(error))` |
|
|
80
|
+
| `.bind(fn)` | `fn(value)` | `self` |
|
|
81
|
+
| `.match(ok, err)` | `ok(value)` | `err(error)` |
|
|
82
|
+
| `.is_ok` | `True` | `False` |
|
|
83
|
+
| `.is_err` | `False` | `True` |
|
|
84
|
+
|
|
85
|
+
## License
|
|
86
|
+
|
|
87
|
+
MIT
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
crashbytes_result/__init__.py,sha256=eCSZRj2dZIUShSOLrgnPvFj99dclgGEAtZDt6j7QD-I,194
|
|
2
|
+
crashbytes_result/_core.py,sha256=-RESJQCIbsDgQeQCGT15KJV_xNlIKfq2MIi0ubQKP_Y,4485
|
|
3
|
+
crashbytes_result/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
4
|
+
crashbytes_result-1.0.0.dist-info/METADATA,sha256=XyoyFIQXIwZ-zGUhH7o-1-Nsekbq_4XH-Y3ZeAjCDgQ,2442
|
|
5
|
+
crashbytes_result-1.0.0.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
|
|
6
|
+
crashbytes_result-1.0.0.dist-info/licenses/LICENSE,sha256=Ic61HOO4EsyXXAGNY-D-1nG62feh_IBbipY1v_QcYcY,1067
|
|
7
|
+
crashbytes_result-1.0.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 CrashBytes
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|