Skip to content

Commit e635d12

Browse files
proboscispre-commit-ci[bot]sobolevn
authored
Fix: Add pickle support for UnwrapFailedError (#2048) (#2049)
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: sobolevn <[email protected]>
1 parent 39e31fb commit e635d12

File tree

3 files changed

+46
-0
lines changed

3 files changed

+46
-0
lines changed

CHANGELOG.md

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,13 @@ See [0Ver](https://0ver.org/).
2222
which provides a default error value for `Failure`
2323

2424

25+
## 0.24.1
26+
27+
### Bugfixes
28+
29+
- Add pickling support for `UnwrapFailedError` exception
30+
31+
2532
## 0.23.0
2633

2734
### Features

returns/primitives/exceptions.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,16 @@ def __init__(self, container: Unwrappable) -> None:
2121
super().__init__()
2222
self.halted_container = container
2323

24+
def __reduce__(self): # noqa: WPS603
25+
"""Custom reduce method for pickle protocol.
26+
27+
This helps properly reconstruct the exception during unpickling.
28+
"""
29+
return (
30+
self.__class__, # callable
31+
(self.halted_container,), # args to callable
32+
)
33+
2434

2535
class ImmutableStateError(AttributeError):
2636
"""
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
import pickle # noqa: S403
2+
3+
from returns.maybe import Nothing
4+
from returns.primitives.exceptions import UnwrapFailedError
5+
from returns.result import Failure
6+
7+
8+
def test_pickle_unwrap_failed_error_from_maybe():
9+
"""Ensures that UnwrapFailedError with Maybe can be pickled."""
10+
serialized = None
11+
try:
12+
Nothing.unwrap() # This will raise UnwrapFailedError
13+
except UnwrapFailedError as error:
14+
serialized = pickle.dumps(error)
15+
16+
deserialized_error = pickle.loads(serialized) # noqa: S301
17+
assert deserialized_error.halted_container == Nothing
18+
19+
20+
def test_pickle_unwrap_failed_error_from_result():
21+
"""Ensures that UnwrapFailedError with Result can be pickled."""
22+
serialized = None
23+
try:
24+
Failure('error').unwrap() # This will raise UnwrapFailedError
25+
except UnwrapFailedError as error:
26+
serialized = pickle.dumps(error)
27+
28+
deserialized_error = pickle.loads(serialized) # noqa: S301
29+
assert deserialized_error.halted_container == Failure('error')

0 commit comments

Comments
 (0)