rezult 0.2.0__tar.gz → 0.2.2__tar.gz

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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: rezult
3
- Version: 0.2.0
3
+ Version: 0.2.2
4
4
  Summary: Rust-inspired `Result` and `Option` types for Python 3.12+.
5
5
  Keywords: rust,rs,exception,result,option,rusty
6
6
  Author: Sequence
@@ -19,260 +19,263 @@ Classifier: Typing :: Typed
19
19
  Requires-Python: >=3.12
20
20
  Description-Content-Type: text/markdown
21
21
 
22
- # rezult
23
-
24
- Rust-inspired `Result` and `Option` types for Python 3.12+.
25
-
26
- `rezult` makes failure and absence part of the type signature. Instead of
27
- throwing exceptions and hoping every caller remembers to catch them, a
28
- function returns `Ok(value)` or `Err(error)`, and callers handle both cases
29
- explicitly with pattern matching or the built-in combinators.
30
-
31
- `rezult` is independent, which means it have no extra dependencies. As a result, it is lightweight and fast.
32
-
33
- ## Why not `try` - `except`?
34
-
35
- Exceptions are invisible in a function signature. Nothing stops an error from
36
- escaping several layers up the stack, and the caller has no way to know which
37
- failures are expected without reading the implementation.
38
-
39
- ```python
40
- def parse_age(text: str) -> int:
41
- try:
42
- age = int(text)
43
- except ValueError as exc:
44
- raise RuntimeError("invalid age") from exc
45
- if age < 0:
46
- raise ValueError("age must be non-negative")
47
- return age
48
-
49
-
50
- try:
51
- age = parse_age("abc")
52
- except RuntimeError as exc:
53
- print(f"failed: {exc}")
54
- ```
55
-
56
- With `rezult`, the failure is part of the return type and the caller handles it
57
- in one place:
58
-
59
- ```python
60
- from rezult import Err, Ok, resulty
61
-
62
-
63
- @resulty(ValueError)
64
- def parse_age(text: str) -> int:
65
- age = int(text)
66
- if age < 0:
67
- raise ValueError("age must be non-negative")
68
- return age
69
-
70
-
71
- match parse_age("abc"):
72
- case Ok(age):
73
- print(f"age = {age}")
74
- case Err(error):
75
- print(f"failed: {error}")
76
- ```
77
-
78
- The main differences:
79
-
80
- | | `try` / `except` | `rezult` |
81
- | --- | --- | --- |
82
- | Failure visible in the signature | No | Yes |
83
- | Handling failures | Optional, easy to forget | Explicit `match` or `unwrap` |
84
- | Chaining fallible steps | Nested `try` blocks | `map`, `map_err`, `and_then_res`, `or_else_res` |
85
- | Distinguishing "no value" from "error" | `None` and exceptions get mixed up | Separate `Option` and `Result` types |
86
- | Testing | Must assert on exceptions | Compare values directly |
87
-
88
- Notice that `rezult` is designed for providing a pratical way to handle exceptions more tersely, but not taking the place for exceptions such as `KeyboardInterrupted` which contain a specified sematic meaning.
89
-
90
- ## Installation
91
-
92
- ```bash
93
- # pip
94
- pip install rezult
95
-
96
- # uv
97
- uv add rezult
98
-
99
- # uv pip
100
- uv pip install rezult
101
- ```
102
-
103
- or, from a checkout:
104
-
105
- ```bash
106
- pip install .
107
- ```
108
-
109
- Requires Python 3.12 or newer.
110
-
111
- ## Quick start
112
-
113
- ### Result
114
-
115
- ```python
116
- from rezult import Err, Ok, Result
117
-
118
-
119
- def divide(a: float, b: float) -> Result[float, str]:
120
- if b == 0:
121
- return Err("division by zero")
122
- return Ok(a / b)
123
-
124
-
125
- match divide(10, 2):
126
- case Ok(value):
127
- print(f"result: {value}") # result: 5.0
128
- case Err(error):
129
- print(f"error: {error}")
130
-
131
-
132
- match divide(1, 0):
133
- case Ok(value):
134
- print(f"result: {value}")
135
- case Err(error):
136
- print(f"error: {error}") # error: division by zero
137
- ```
138
-
139
- Results compose without nested `try` blocks:
140
-
141
- ```python
142
- def validate(age: int) -> Result[int, str]:
143
- return Ok(age) if age >= 18 else Err("too young")
144
-
145
-
146
- result = (
147
- divide(36, 2)
148
- .map(lambda value: int(value))
149
- .and_then_res(validate)
150
- )
151
- print(result) # Ok(18)
152
-
153
- print(divide(1, 0).map_err(str).unwrap_or(-1)) # -1
154
- ```
155
-
156
- Other useful methods include `is_ok()`, `is_err()`, `ok()`, `err()`,
157
- `map_or()`, `inspect()`, `unwrap()`, `expect()`, `or_res()`, and
158
- `or_else_res()`.
159
-
160
- ### Option
161
-
162
- `Option[T]` is either `Some(value)` or `Nothing()`. `Nothing()` is a
163
- singleton, so it can be checked with `is`.
164
-
165
- ```python
166
- from rezult import Nothing, Option, Some
167
-
168
-
169
- def find_user(user_id: int) -> Option[str]:
170
- users = {1: "alice", 2: "bob"}
171
- return Some(users[user_id]) if user_id in users else Nothing()
172
-
173
-
174
- match find_user(1):
175
- case Some(name):
176
- print(f"hello, {name}") # hello, alice
177
- case Nothing():
178
- print("user not found")
179
-
180
-
181
- print(find_user(3).unwrap_or("anonymous")) # anonymous
182
- ```
183
-
184
- Options chain in the same way:
185
-
186
- ```python
187
- find_user(1).map(str.upper) # Some('ALICE')
188
- find_user(1).filter(lambda name: name != "alice") # Nothing
189
- find_user(3).or_opt(Some("guest")) # Some('guest')
190
- ```
191
-
192
- Other useful methods include `is_some()`, `is_none()`, `ok_or()`,
193
- `map_or()`, `map_or_else()`, `and_then_opt()`, `or_else_opt()`, `xor()`,
194
- `zip()`, and `unwrap()`.
195
-
196
- ### Decorators
197
-
198
- `resulty` turns raised exceptions into `Err` values:
199
-
200
- ```python
201
- from pathlib import Path
202
-
203
- from rezult import resulty
204
-
205
-
206
- @resulty()
207
- def load(path: str) -> str:
208
- return Path(path).read_text()
209
-
210
-
211
- @resulty(ValueError, KeyError)
212
- def lookup(data: dict[str, int], key: str) -> int:
213
- return data[key]
214
-
215
-
216
- load("missing.txt") # Err(FileNotFoundError(...))
217
- lookup({"a": 1}, "b") # Err(KeyError('b'))
218
- ```
219
-
220
- `optionally` turns a `None` return value into `Nothing()`:
221
-
222
- ```python
223
- from rezult import optionally
224
-
225
-
226
- @optionally
227
- def first(items: list[int]) -> int | None:
228
- return items[0] if items else None
229
-
230
-
231
- first([1, 2]) # Some(1)
232
- first([]) # Nothing
233
- ```
234
-
235
- Both decorators preserve the wrapped function's metadata. They raise
236
- `TypeError` for async functions instead of silently returning an un-awaited
237
- coroutine.
238
-
239
- ### Evaluating expressions
240
-
241
- If you already have a zero-argument callable, use `result_eval` or
242
- `option_eval`:
243
-
244
- ```python
245
- from rezult import option_eval, result_eval
246
-
247
- result_eval(lambda: int("42")) # Ok(42)
248
- result_eval(lambda: 1 / 0) # Err(ZeroDivisionError('division by zero'))
249
- option_eval(lambda: None) # Nothing
250
- option_eval(lambda: "value") # Some('value')
251
- ```
252
-
253
- ## API at a glance
254
-
255
- | Export | Description |
256
- | --- | --- |
257
- | `Ok(value)` | Successful `Result` variant |
258
- | `Err(error)` | Failed `Result` variant |
259
- | `Some(value)` | Non-empty `Option` variant |
260
- | `Nothing()` | Empty `Option` variant (singleton) |
261
- | `Result` | Base class and combinators for fallible values |
262
- | `Option` | Base class and combinators for optional values |
263
- | `UnwrapError` | Raised by `unwrap`, `expect`, `unwrap_err`, and `expect_err` |
264
- | `resulty(...)` | Decorator: exceptions become `Err` |
265
- | `optionally` | Decorator: `None` becomes `Nothing()` |
266
- | `result_eval(thunk)` | Evaluate a callable, capturing exceptions as `Err` |
267
- | `option_eval(thunk)` | Evaluate a callable, converting `None` to `Nothing()` |
268
-
269
- Both types support structural pattern matching, equality by variant and
270
- contained value, and hashing.
271
-
272
- ## Contributing
273
-
274
- We allow all kinds of contributions, except for fully AI generated code and contributions that only contain a little human thinking.
275
-
276
- ## License
277
-
278
- MIT
22
+ # rezult
23
+
24
+ Rust-inspired `Result` and `Option` types for Python 3.12+.
25
+
26
+ `rezult` makes failure and absence part of the type signature. Instead of
27
+ throwing exceptions and hoping every caller remembers to catch them, a
28
+ function returns `Ok(value)` or `Err(error)`, and callers handle both cases
29
+ explicitly with pattern matching or the built-in combinators.
30
+
31
+ `rezult` is independent, which means it have no extra dependencies. As a result, it is lightweight and fast.
32
+
33
+ ## Why not `try` - `except`?
34
+
35
+ Exceptions are invisible in a function signature. Nothing stops an error from
36
+ escaping several layers up the stack, and the caller has no way to know which
37
+ failures are expected without reading the implementation.
38
+
39
+ ```python
40
+ def parse_age(text: str) -> int:
41
+ try:
42
+ age = int(text)
43
+ except ValueError as exc:
44
+ raise RuntimeError("invalid age") from exc
45
+ if age < 0:
46
+ raise ValueError("age must be non-negative")
47
+ return age
48
+
49
+
50
+ try:
51
+ age = parse_age("abc")
52
+ except RuntimeError as exc:
53
+ print(f"failed: {exc}")
54
+ ```
55
+
56
+ With `rezult`, the failure is part of the return type and the caller handles it
57
+ in one place:
58
+
59
+ ```python
60
+ from rezult import Err, Ok, resulty
61
+
62
+
63
+ @resulty(ValueError)
64
+ def parse_age(text: str) -> int:
65
+ age = int(text)
66
+ if age < 0:
67
+ raise ValueError("age must be non-negative")
68
+ return age
69
+
70
+
71
+ match parse_age("abc"):
72
+ case Ok(age):
73
+ print(f"age = {age}")
74
+ case Err(error):
75
+ print(f"failed: {error}")
76
+ ```
77
+
78
+ The main differences:
79
+
80
+ | | `try` / `except` | `rezult` |
81
+ | --- | --- | --- |
82
+ | Failure visible in the signature | No | Yes |
83
+ | Handling failures | Optional, easy to forget | Explicit `match` or `unwrap` |
84
+ | Chaining fallible steps | Nested `try` blocks | `map`, `map_err`, `and_then_res`, `or_else_res` |
85
+ | Distinguishing "no value" from "error" | `None` and exceptions get mixed up | Separate `Option` and `Result` types |
86
+ | Testing | Must assert on exceptions | Compare values directly |
87
+
88
+ Notice that `rezult` is designed for providing a pratical way to handle exceptions more tersely, but not taking the place for exceptions such as `KeyboardInterrupted` which contain a specified sematic meaning.
89
+
90
+ ## Installation
91
+
92
+ ```bash
93
+ # pip
94
+ pip install rezult
95
+
96
+ # uv
97
+ uv add rezult
98
+
99
+ # uv pip
100
+ uv pip install rezult
101
+ ```
102
+
103
+ or, from a checkout:
104
+
105
+ ```bash
106
+ pip install .
107
+ ```
108
+
109
+ Requires Python 3.12 or newer.
110
+
111
+ ## Quick start
112
+
113
+ ### Result
114
+
115
+ ```python
116
+ from rezult import Err, Ok, Result
117
+
118
+
119
+ def divide(a: float, b: float) -> Result[float, str]:
120
+ if b == 0:
121
+ return Err("division by zero")
122
+ return Ok(a / b)
123
+
124
+
125
+ match divide(10, 2):
126
+ case Ok(value):
127
+ print(f"result: {value}") # result: 5.0
128
+ case Err(error):
129
+ print(f"error: {error}")
130
+
131
+
132
+ match divide(1, 0):
133
+ case Ok(value):
134
+ print(f"result: {value}")
135
+ case Err(error):
136
+ print(f"error: {error}") # error: division by zero
137
+ ```
138
+
139
+ Results compose without nested `try` blocks:
140
+
141
+ ```python
142
+ def validate(age: int) -> Result[int, str]:
143
+ return Ok(age) if age >= 18 else Err("too young")
144
+
145
+
146
+ result = (
147
+ divide(36, 2)
148
+ .map(int)
149
+ .and_then_res(validate)
150
+ )
151
+ print(result) # Ok(18)
152
+
153
+ print(divide(1, 0).map_err(str).unwrap_or(-1)) # -1
154
+ ```
155
+
156
+ Other useful methods include `is_ok()`, `is_err()`, `ok()`, `err()`,
157
+ `map_or()`, `inspect()`, `unwrap()`, `expect()`, `or_res()`, and
158
+ `or_else_res()`.
159
+
160
+ ### Option
161
+
162
+ `Option[T]` is either `Some(value)` or `Nothing()`. `Nothing()` is a
163
+ singleton, so it can be checked with `is`.
164
+
165
+ ```python
166
+ from rezult import Nothing, Option, Some
167
+
168
+
169
+ def find_user(user_id: int) -> Option[str]:
170
+ users = {1: "alice", 2: "bob"}
171
+ return Some(users[user_id]) if user_id in users else Nothing()
172
+
173
+
174
+ match find_user(1):
175
+ case Some(name):
176
+ print(f"hello, {name}") # hello, alice
177
+ case Nothing():
178
+ print("user not found")
179
+
180
+
181
+ print(find_user(3).unwrap_or("anonymous")) # anonymous
182
+ ```
183
+
184
+ Options chain in the same way:
185
+
186
+ ```python
187
+ from functools import partial
188
+ from operator import ne
189
+
190
+ find_user(1).map(str.upper) # Some('ALICE')
191
+ find_user(1).filter(partial(ne, "alice")) # Nothing
192
+ find_user(3).or_opt(Some("guest")) # Some('guest')
193
+ ```
194
+
195
+ Other useful methods include `is_some()`, `is_none()`, `ok_or()`,
196
+ `map_or()`, `map_or_else()`, `and_then_opt()`, `or_else_opt()`, `xor()`,
197
+ `zip()`, and `unwrap()`.
198
+
199
+ ### Decorators
200
+
201
+ `resulty` turns raised exceptions into `Err` values:
202
+
203
+ ```python
204
+ from pathlib import Path
205
+
206
+ from rezult import resulty
207
+
208
+
209
+ @resulty()
210
+ def load(path: str) -> str:
211
+ return Path(path).read_text()
212
+
213
+
214
+ @resulty(ValueError, KeyError)
215
+ def lookup(data: dict[str, int], key: str) -> int:
216
+ return data[key]
217
+
218
+
219
+ load("missing.txt") # Err(FileNotFoundError(...))
220
+ lookup({"a": 1}, "b") # Err(KeyError('b'))
221
+ ```
222
+
223
+ `optionally` turns a `None` return value into `Nothing()`:
224
+
225
+ ```python
226
+ from rezult import optionally
227
+
228
+
229
+ @optionally
230
+ def first(items: list[int]) -> int | None:
231
+ return items[0] if items else None
232
+
233
+
234
+ first([1, 2]) # Some(1)
235
+ first([]) # Nothing
236
+ ```
237
+
238
+ Both decorators preserve the wrapped function's metadata. They raise
239
+ `TypeError` for async functions instead of silently returning an un-awaited
240
+ coroutine.
241
+
242
+ ### Evaluating expressions
243
+
244
+ If you already have a callable, use `result_eval` or
245
+ `option_eval`:
246
+
247
+ ```python
248
+ from rezult import option_eval, result_eval
249
+
250
+ result_eval(lambda: 1 / 0) # Err(ZeroDivisionError('division by zero'))
251
+ result_eval(int, "42") # Ok(42)
252
+ option_eval(lambda: None) # Nothing
253
+ option_eval(lambda: "value") # Some('value')
254
+ ```
255
+
256
+ ## API at a glance
257
+
258
+ | Export | Description |
259
+ | --- | --- |
260
+ | `Ok(value)` | Successful `Result` variant |
261
+ | `Err(error)` | Failed `Result` variant |
262
+ | `Some(value)` | Non-empty `Option` variant |
263
+ | `Nothing()` | Empty `Option` variant (singleton) |
264
+ | `Result` | Base class and combinators for fallible values |
265
+ | `Option` | Base class and combinators for optional values |
266
+ | `UnwrapError` | Raised by `unwrap`, `expect`, `unwrap_err`, and `expect_err` |
267
+ | `resulty(...)` | Decorator: exceptions become `Err` |
268
+ | `optionally` | Decorator: `None` becomes `Nothing()` |
269
+ | `result_eval(expr, *args, **kwargs)` | Evaluate a callable, capturing exceptions as `Err` |
270
+ | `option_eval(expr, *args, **kwargs)` | Evaluate a callable, converting `None` to `Nothing()` |
271
+
272
+ Both types support structural pattern matching, equality by variant and
273
+ contained value, and hashing.
274
+
275
+ ## Contributing
276
+
277
+ We allow all kinds of contributions, except for fully AI generated code and contributions that only contain a little human thinking.
278
+
279
+ ## License
280
+
281
+ MIT