### Install HexBytes using pip Source: https://github.com/ethereum/hexbytes/blob/main/README.md This command installs the hexbytes package using pip, Python's package installer. Ensure you have Python and pip installed on your system. ```shell python -m pip install hexbytes ``` -------------------------------- ### Python: Initialize and Use HexBytes Source: https://github.com/ethereum/hexbytes/blob/main/docs/hexbytes.md Demonstrates various ways to initialize HexBytes objects, including from bytes and hex strings. It also shows how to access elements, slices, and convert back to bytes. HexBytes provides a more convenient console representation and a dedicated method for 0x-prefixed hex strings. ```python from hexbytes import HexBytes # convert from bytes to a prettier representation at the console print(HexBytes(b"\x03\x08wf\xbfh\xe7\x86q\xd1\xeaCj\xe0\x87\xdat\xa1'a\xda\xc0 \x01\x1a\x9e\xdd\xc4\x90\x0b\xf1;")) # HexBytes accepts the hex string representation as well, ignoring case and 0x prefixes hb = HexBytes('03087766BF68E78671D1EA436AE087DA74A12761DAC020011A9EDDC4900BF13B') print(hb) hb = HexBytes('0x03087766BF68E78671D1EA436AE087DA74A12761DAC020011A9EDDC4900BF13B') print(hb) # HexBytes does not override the .hex() or __str__ methods of the parent bytes type hb = HexBytes('03087766BF68E78671D1EA436AE087DA74A12761DAC020011A9EDDC4900BF13B') print(hb.hex()) print(hb) # Use the to_0x_hex method to get a 0x-prefixed hex string print(hb.to_0x_hex()) # get the first byte: print(hb[0]) # get the first 5 bytes: print(hb[:5]) # show how many bytes are in the value print(len(hb)) # cast back to the basic bytes type print(bytes(hb)) ``` -------------------------------- ### HexBytes Pickling Support for Optimized Serialization Source: https://context7.com/ethereum/hexbytes/llms.txt Illustrates HexBytes' optimized pickling support using the `__reduce__` method. This allows for efficient serialization and deserialization, bypassing input validation on unpickling as data is pre-validated. It shows how to pickle and unpickle single HexBytes objects and complex data structures containing HexBytes. ```python import pickle from hexbytes import HexBytes # Create original instance original = HexBytes("0x1234567890abcdef") print(repr(original)) # HexBytes('0x1234567890abcdef') # Serialize (pickle) pickled = pickle.dumps(original) print(f"Pickled size: {len(pickled)} bytes") # Deserialize (unpickle) restored = pickle.loads(pickled) print(repr(restored)) # HexBytes('0x1234567890abcdef') # Verify equality print(original == restored) # True print(type(restored)) # # Works with complex data structures data = { "tx_hash": HexBytes("0xabcd"), "block": HexBytes("0x1234"), "values": [HexBytes("0xff"), HexBytes("0x00")] } restored_data = pickle.loads(pickle.dumps(data)) print(repr(restored_data["tx_hash"])) ``` -------------------------------- ### HexBytes Basic Operations and Concatenation Source: https://context7.com/ethereum/hexbytes/llms.txt Demonstrates basic operations with HexBytes objects, including converting to hex string, string representation, list conversion, and concatenation with standard bytes. It also shows how HexBytes can be used in functions expecting bytes, like hashlib. ```python from hexbytes import HexBytes import hashlib hb = HexBytes("0xdeadbeef") print(hb.hex()) # deadbeef (inherited from bytes) print(str(hb)) # b'\xde\xad\xbe\xef' (inherited __str__) print(list(hb)) # [222, 173, 190, 239] # Concatenation with bytes combined = hb + b"\x00\x01" print(combined) # b'\xde\xad\xbe\xef\x00\x01' # Use in functions expecting bytes digest = hashlib.sha256(hb).hexdigest() print(digest) # 5f78c33274e43fa9de5659265c1d917e25c03722dcb0b8d27db8d5feaa813953 ``` -------------------------------- ### Create HexBytes from Various Input Types (Python) Source: https://context7.com/ethereum/hexbytes/llms.txt Demonstrates creating HexBytes objects from various input types including hex strings, raw bytes, integers, booleans, bytearrays, and memoryviews. It highlights the flexible parsing and the resulting HexBytes representation. Negative integers will raise a ValueError. ```python from hexbytes import HexBytes # Create from hex string (with or without 0x prefix, case-insensitive) hb1 = HexBytes("0x03087766bf68e78671d1ea436ae087da74a12761dac020011a9eddc4900bf13b") hb2 = HexBytes("03087766BF68E78671D1EA436AE087DA74A12761DAC020011A9EDDC4900BF13B") print(repr(hb1)) # HexBytes('0x03087766bf68e78671d1ea436ae087da74a12761dac020011a9eddc4900bf13b') print(hb1 == hb2) # True # Create from raw bytes hb3 = HexBytes(b"\x0f\x1a\x2b") print(repr(hb3)) # HexBytes('0x0f1a2b') # Create from integer (non-negative only) hb4 = HexBytes(255) print(repr(hb4)) # HexBytes('0xff') hb5 = HexBytes(65536) print(repr(hb5)) # HexBytes('0x10000') # Create from boolean hb_true = HexBytes(True) hb_false = HexBytes(False) print(repr(hb_true)) # HexBytes('0x01') print(repr(hb_false)) # HexBytes('0x00') # Create from bytearray hb6 = HexBytes(bytearray([15, 26, 43])) print(repr(hb6)) # HexBytes('0x0f1a2b') # Create from memoryview data = b"\xde\xad\xbe\xef" hb7 = HexBytes(memoryview(data)) print(repr(hb7)) # HexBytes('0xdeadbeef') # Error handling: negative integers raise ValueError try: HexBytes(-1) except ValueError as e: print(f"Error: {e}") # Error: Cannot convert negative integer -1 to bytes ``` -------------------------------- ### Convert HexBytes Back to Standard Bytes (Python) Source: https://context7.com/ethereum/hexbytes/llms.txt Demonstrates how to convert a HexBytes object back into a standard Python `bytes` object using the `bytes()` constructor. This is useful for interoperability with other libraries that expect plain bytes. ```python from hexbytes import HexBytes hb = HexBytes("0xdeadbeef") # Convert to standard bytes raw_bytes = bytes(hb) print(raw_bytes) # b'\xde\xad\xbe\xef' print(type(raw_bytes)) # ``` -------------------------------- ### Python: HexBytes Class Documentation Source: https://github.com/ethereum/hexbytes/blob/main/docs/hexbytes.md Documentation for the HexBytes class, which is a thin wrapper around Python's built-in bytes type. It extends bytes by accepting more initialization values and providing a 0x-prefixed representation for console output and a dedicated method `to_0x_hex()`. ```python class HexBytes(bytes): """ Thin wrapper around the python built-in bytes class. It has these changes: : 1. Accepts more initializing values: bool, bytearray, bytes, (non-negative) int, str, and memoryview 2. The representation at console (__repr__) is 0x-prefixed 3. to_0x_hex returns a 0x-prefixed hex string """ def to_0x_hex(self) -> str: """ Convert the bytes to a 0x-prefixed hex string """ pass ``` -------------------------------- ### Convert HexBytes to 0x-Prefixed Hex String (Python) Source: https://context7.com/ethereum/hexbytes/llms.txt Shows how to use the `to_0x_hex()` method to explicitly convert a HexBytes object into a 0x-prefixed hexadecimal string. This is contrasted with the inherited `hex()` method which returns a plain hex string. ```python from hexbytes import HexBytes hb = HexBytes(b"\x0f\x1a\x2b\x3c") # to_0x_hex() returns 0x-prefixed string prefixed = hb.to_0x_hex() print(prefixed) # 0x0f1a2b3c print(type(prefixed)) # # Compare with inherited hex() method (no prefix) plain = hb.hex() print(plain) # 0f1a2b3c # Useful for Ethereum transaction hashes, addresses, etc. tx_hash = HexBytes("0xabcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890") print(f"Transaction: {tx_hash.to_0x_hex()}") # Transaction: 0xabcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890 ``` -------------------------------- ### Slice and Index HexBytes Objects (Python) Source: https://context7.com/ethereum/hexbytes/llms.txt Illustrates Python's sequence operations on HexBytes objects. Slicing a HexBytes object returns another HexBytes object, preserving the type. Indexing a single byte returns an integer, consistent with standard Python bytes behavior. ```python from hexbytes import HexBytes hb = HexBytes("0x03087766bf68e78671d1ea436ae087da74a12761dac020011a9eddc4900bf13b") # Get single byte by index (returns int) first_byte = hb[0] print(first_byte) # 3 print(type(first_byte)) # last_byte = hb[-1] print(last_byte) # 59 (0x3b) # Slice returns HexBytes (preserves type) first_five = hb[:5] print(repr(first_five)) # HexBytes('0x03087766bf') print(type(first_five)) # # Negative slicing last_four = hb[-4:] print(repr(last_four)) # HexBytes('0x900bf13b') # Step slicing every_other = hb[::2] print(repr(every_other)) # HexBytes('0x0377f8710a6e7a41a002a9d40b1b') # Length print(len(hb)) # 32 ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.