diff --git a/hexbytes/main.py b/hexbytes/main.py index b0c8f37..e36df5e 100644 --- a/hexbytes/main.py +++ b/hexbytes/main.py @@ -44,11 +44,14 @@ def __getitem__(self, key: slice) -> "HexBytes": # noqa: F811 def __getitem__( # noqa: F811 self, key: "SupportsIndex | slice" ) -> "int | bytes | HexBytes": - result = super().__getitem__(key) - if hasattr(result, "hex"): - return type(self)(result) - else: + result = bytes.__getitem__(self, key) + if isinstance(result, int): return result + cls = type(self) + if cls is HexBytes: + return bytes.__new__(HexBytes, result) + else: + return cls(result) def __repr__(self) -> str: return f"HexBytes({'0x' + self.hex()!r})" diff --git a/tests/core/test_hexbytes.py b/tests/core/test_hexbytes.py index 36cf1f6..451737b 100644 --- a/tests/core/test_hexbytes.py +++ b/tests/core/test_hexbytes.py @@ -116,6 +116,10 @@ def test_hexbytes_index(primitive, index): assert hexbytes[index] == primitive[index] +def test_hexbytes_index_type(): + assert isinstance(HexBytes(b"abc")[0], int) + + @given(st.binary(), st.integers(), st.integers()) def test_slice(primitive, start, stop): hexbytes = HexBytes(primitive) @@ -123,6 +127,17 @@ def test_slice(primitive, start, stop): assert hexbytes[start:stop] == expected +def test_slice_type(): + assert type(HexBytes(b"abc")[:2]) is HexBytes + + +def test_slice_preserves_subclass(): + class CustomHexBytes(HexBytes): + pass + + assert type(CustomHexBytes(b"abc")[:2]) is CustomHexBytes + + @given(st.binary(), st.integers(), st.integers(), st.integers()) def test_slice_stepped(primitive, start, stop, step): hexbytes = HexBytes(primitive)