HexBytes: Python `bytes` subclass for hex representation
HexBytes is a thin wrapper around the Python built-in `bytes` class (version 1.3.1). It extends `bytes` by accepting a wider range of initialization types including `bool`, `int`, `str`, `bytearray`, and `memoryview`. Key features include a 0x-prefixed console representation (`__repr__`) and a `to_0x_hex()` method for consistent 0x-prefixed hexadecimal string output. The library is actively maintained with regular releases.
Warnings
- breaking HexBytes has dropped support for older Python versions. Versions prior to 0.2.0 dropped Python 3.5, versions prior to 0.3.0 dropped Python 3.6, and current 1.x series (since 1.0.0) requires Python >= 3.8. Attempting to install on unsupported versions will fail or lead to unexpected behavior.
- gotcha While HexBytes' `__repr__` method provides a convenient 0x-prefixed hex string for console output, it does not override the standard `bytes.hex()` or `__str__` methods. Calling `str(my_hexbytes)` or `my_hexbytes.hex()` will revert to the default `bytes` behavior (e.g., `b'\x01\x02'` or `'0102'`).
Install
-
pip install hexbytes
Imports
- HexBytes
from hexbytes import HexBytes
Quickstart
from hexbytes import HexBytes
# Convert from bytes to a prettier representation
hb_from_bytes = HexBytes(b"\x03\x08wf\xbfh\xe7\x86q\xd1\xeaCj\xe0\x87\xdat\xa1'a\xda\xc0 \x01\x1a\x9e\xdd\xc4\x90\x0b\xf1;")
print(f"From bytes: {hb_from_bytes}")
# HexBytes accepts hex string representation (ignoring case and 0x prefixes)
hb_from_hex_str = HexBytes('03087766BF68E78671D1EA436AE087DA74A12761DAC020011A9EDDC4900BF13B')
print(f"From hex string: {hb_from_hex_str}")
# Get the 0x-prefixed hex string
hex_string_output = hb_from_hex_str.to_0x_hex()
print(f"Using to_0x_hex(): {hex_string_output}")
# Cast back to basic bytes type
original_bytes = bytes(hb_from_hex_str)
print(f"Cast back to bytes: {original_bytes}")