diff --git a/hexbytes/main.py b/hexbytes/main.py index b0c8f37..4d7ba94 100644 --- a/hexbytes/main.py +++ b/hexbytes/main.py @@ -30,6 +30,8 @@ class HexBytes(bytes): """ def __new__(cls, val: BytesLike) -> "HexBytes": + if isinstance(val, bytes): + return super().__new__(cls, val) bytesval = to_bytes(val) return super().__new__(cls, bytesval) diff --git a/tests/core/test_hexbytes.py b/tests/core/test_hexbytes.py index 36cf1f6..71f9cc2 100644 --- a/tests/core/test_hexbytes.py +++ b/tests/core/test_hexbytes.py @@ -36,6 +36,20 @@ def test_bytes_inputs(primitive): assert_equal(wrapped, primitive) +def test_hexbytes_input_creates_new_instance(): + wrapped = HexBytes(b"abc") + assert HexBytes(wrapped) is not wrapped + + +def test_bytes_input_preserves_subclass(): + class CustomHexBytes(HexBytes): + pass + + wrapped = CustomHexBytes(b"abc") + assert type(wrapped) is CustomHexBytes + assert type(CustomHexBytes(HexBytes(b"abc"))) is CustomHexBytes + + @given(st.binary()) def test_bytearray_inputs(primitive): byte_array_input = bytearray(primitive)