eth-utils
eth-utils provides a collection of common utility functions for Python code that interacts with Ethereum. It includes functionalities for ABI manipulation, address checksumming, type conversions, cryptographic hashing, and hexadecimal encoding/decoding. The library is currently at version 6.0.0 and maintains a frequent release cadence, often introducing minor and patch updates, with major versions released approximately annually.
Warnings
- breaking The `ethereum-utils` PyPI package was renamed to `eth-utils` in November 2017. Projects still depending on `ethereum-utils` will not receive updates and should migrate to `eth-utils`.
- breaking With the release of `eth-utils` v6.0.0, support for Python 3.8 and 3.9 has been dropped. Ensure your project is running on Python 3.10 or newer.
- gotcha When using conversion utilities like `to_bytes` or `to_hex` with string inputs, you must explicitly specify whether the string is `text` (e.g., UTF-8 encoded) or a `hexstr` (hex-encoded bytestring). The library cannot reliably auto-detect this, leading to incorrect conversions if not specified.
- gotcha The `apply_formatter_to_array` function in `eth-utils` returns a generator, which must be consumed (e.g., by converting to a `list`) to access all formatted elements. This differs from some other libraries (e.g., `web3.py`'s historical `apply_formatter_to_array`) which might return a concrete list or array directly.
Install
-
pip install eth-utils
Imports
- to_checksum_address
from eth_utils import to_checksum_address
- to_bytes
from eth_utils import to_bytes
- is_address
from eth_utils import is_address
- hexstr_if_str
from eth_utils.curried import hexstr_if_str
- abi_to_signature
from eth_utils.abi import abi_to_signature
Quickstart
from eth_utils import to_checksum_address, is_address, to_bytes, decode_hex
# Example 1: Checksumming an Ethereum address
address_raw = '0xd3cda913deb6f67967b99d67acdfa1712c293601'
checksum_address = to_checksum_address(address_raw)
print(f"Raw address: {address_raw}")
print(f"Checksummed address: {checksum_address}")
# Example 2: Validating an address
is_valid = is_address(checksum_address)
print(f"Is '{checksum_address}' a valid address? {is_valid}")
# Example 3: Converting string to bytes, explicitly specifying type
hex_string = '0x123456'
bytes_data = to_bytes(hexstr=hex_string)
print(f"Hex string '{hex_string}' to bytes: {bytes_data}")
# Example 4: Decoding a hexadecimal string to bytes
decoded_bytes = decode_hex('0xabcdef')
print(f"Decoded '0xabcdef' to bytes: {decoded_bytes}")