Skip to content

Commit c401527

Browse files
BobTheBuidlerfselmo
authored andcommitted
performance: bypass input validation for faster unpickling
We can do this because an existing HexBytes instance has already had its input validated when __new__ was called.
1 parent 1ab0342 commit c401527

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

hexbytes/main.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
from typing import (
22
TYPE_CHECKING,
3+
Callable,
4+
Tuple,
35
Type,
6+
TypeVar,
47
Union,
58
cast,
69
overload,
@@ -15,6 +18,8 @@
1518
SupportsIndex,
1619
)
1720

21+
_THexBytes = TypeVar("_THexBytes", bound="HexBytes")
22+
1823
BytesLike = Union[bool, bytearray, bytes, int, str, memoryview]
1924

2025

@@ -58,3 +63,17 @@ def to_0x_hex(self) -> str:
5863
Convert the bytes to a 0x-prefixed hex string
5964
"""
6065
return "0x" + self.hex()
66+
67+
def __reduce__(
68+
self
69+
) -> Tuple[
70+
Callable[[Type[_THexBytes], bytes], _THexBytes],
71+
Tuple[Type[_THexBytes], bytes],
72+
]:
73+
"""
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.
78+
"""
79+
return bytes.__new__, (type(self), bytes(self))

0 commit comments

Comments
 (0)