Skip to content

Commit bc7bef8

Browse files
committed
Fix lint; add test
1 parent c401527 commit bc7bef8

File tree

2 files changed

+25
-12
lines changed

2 files changed

+25
-12
lines changed

hexbytes/main.py

Lines changed: 5 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33
Callable,
44
Tuple,
55
Type,
6-
TypeVar,
76
Union,
87
cast,
98
overload,
@@ -18,8 +17,6 @@
1817
SupportsIndex,
1918
)
2019

21-
_THexBytes = TypeVar("_THexBytes", bound="HexBytes")
22-
2320
BytesLike = Union[bool, bytearray, bytes, int, str, memoryview]
2421

2522

@@ -65,15 +62,11 @@ def to_0x_hex(self) -> str:
6562
return "0x" + self.hex()
6663

6764
def __reduce__(
68-
self
69-
) -> Tuple[
70-
Callable[[Type[_THexBytes], bytes], _THexBytes],
71-
Tuple[Type[_THexBytes], bytes],
72-
]:
65+
self,
66+
) -> Tuple[Callable[..., bytes], Tuple[Type["HexBytes"], bytes]]:
7367
"""
74-
An optimized `__reduce__` that bypasses the input validation in `HexBytes.__new__`
75-
since an existing HexBytes instance has already been validated when created.
76-
77-
This enables much faster unpickling of HexBytes objects.
68+
An optimized ``__reduce__`` that bypasses the input validation in
69+
``HexBytes.__new__`` since an existing HexBytes instance has already been
70+
validated when created.
7871
"""
7972
return bytes.__new__, (type(self), bytes(self))

tests/core/test_hexbytes.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import pytest
2+
import pickle
23

34
from eth_utils import (
45
decode_hex,
@@ -125,3 +126,22 @@ def test_slice_stepped(primitive, start, stop, step):
125126
step = None
126127
expected = HexBytes(primitive[start:stop:step])
127128
assert hexbytes[start:stop:step] == expected
129+
130+
131+
def test_reduce_consistency():
132+
obj = HexBytes(b"0x1234")
133+
134+
reduce_fn, reduce_args, *maybe_state = obj.__reduce__()
135+
136+
# recreate manually using reduce_fn
137+
recreated = reduce_fn(*reduce_args)
138+
if maybe_state:
139+
recreated.__setstate__(maybe_state[0])
140+
141+
# check recreated instance equals original
142+
assert recreated == obj # or compare fields manually
143+
144+
dumped = pickle.dumps(obj)
145+
loaded = pickle.loads(dumped)
146+
147+
assert loaded == obj

0 commit comments

Comments
 (0)