Pythonic Ethereum development · web3.py v7+
Essential Web3.py patterns for connecting, reading, writing, events, and accounts. Each snippet is production-ready for web3.py v7+.
from web3 import Web3
# HTTP provider
w3 = Web3(Web3.HTTPProvider('https://eth.llamarpc.com'))
# WebSocket provider
# w3 = Web3(Web3.WebsocketProvider('wss://eth.llamarpc.com'))
assert w3.is_connected(), "not connected"
def get_balance(address: str) -> int:
wei = w3.eth.get_balance(address)
return w3.from_wei(wei, 'ether')
# float: 1.234...
print(get_balance('vitalik.eth'))
tx = {
'to': '0xRecipient...',
'value': w3.to_wei(0.01, 'ether'),
'gas': 21000,
'nonce': w3.eth.get_transaction_count(sender),
'maxFeePerGas': w3.eth.gas_price,
'maxPriorityFeePerGas': w3.to_wei(1, 'gwei'),
'chainId': 1,
}
signed = w3.eth.account.sign_transaction(tx, private_key)
tx_hash = w3.eth.send_raw_transaction(signed.raw_transaction)
receipt = w3.eth.wait_for_transaction_receipt(tx_hash)
abi = [...] # minimal ABI
contract = w3.eth.contract(
address='0xContract...',
abi=abi
)
# Read-only call — no gas
symbol = contract.functions.symbol().call()
total = contract.functions.totalSupply().call()
print(symbol, total)
w3_account = w3.eth.account.from_key(private_key)
tx = contract.functions.transfer(
'0xRecipient...',
amount_in_wei
).build_transaction({
'from': w3_account.address,
'nonce': w3.eth.get_transaction_count(w3_account.address),
'maxFeePerGas': w3.eth.gas_price,
'maxPriorityFeePerGas': w3.to_wei(1, 'gwei'),
'chainId': 1,
})
signed_tx = w3_account.sign_transaction(tx)
tx_hash = w3.eth.send_raw_transaction(signed_tx.raw_transaction)
receipt = w3.eth.wait_for_transaction_receipt(tx_hash)
event_filter = contract.events.Transfer().create_filter(
from_block='latest'
)
for event in event_filter.get_new_entries():
print(event['args'])
# {'from': ..., 'to': ..., 'value': ...}
# Resolve ENS → address
addr = w3.ens.address('vitalik.eth')
# Reverse resolve → ENS name
name = w3.ens.name('0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045')
gas_estimate = contract.functions.transfer(
'0xRecipient...', amount
).estimate_gas({
'from': sender
})
# Add 10% buffer
safe_gas = int(gas_estimate * 1.1)
from web3 import Web3
# Encode function call
data = Web3.keccak(text="transfer(address,uint256)")[:4]
# Decode raw log topics/ data
decoded = contract.events.Transfer().process_log(log_entry)
# ABI encode function params
encoded = Web3.abi.encode_abi(['address', 'uint256'], [addr, val])
What you get — PDF with 20+ copy-paste Python snippets covering all the patterns above, plus account management, token transfers, multi-call, contract deployment helpers, and error handling.
Send exactly $1 in ETH or USDC (ERC-20) to the address below. The PDF is delivered automatically within 5 minutes.
Include your email in the transaction note if you want it sent off-chain.