A Python library for interacting with Ethereum and EVM-compatible blockchains.
python -m pip install web3
# You may need additional tools like geth or Infura for full functionality.
- Mainnet (via Infura)
from web3 import Web3
infura_url = "https://mainnet.infura.io/v3/YOUR_INFURA_PROJECT_ID"
w3 = Web3(Web3.HTTPProvider(infura_url))
print("Connected:", w3.is_connected()) # Check connection
- Testnet (Sepolia)
sepolia_url = "https://sepolia.infura.io/v3/YOUR_INFURA_PROJECT_ID" # TESTNET
w3 = Web3(Web3.HTTPProvider(sepolia_url))
- Local Node (Ganache)
w3 = Web3(Web3.HTTPProvider("http://127.0.0.1:7545"))
Get Balance
balance = w3.eth.get_balance("0xAddress")
print("Balance:", w3.from_wei(balance, 'ether'), "ETH")
Send Transaction
tx = {
'nonce': w3.eth.get_transaction_count("0xSender"),
'to': "0xReceiver",
'value': w3.to_wei(0.01, 'ether'),
'gas': 21000,
'gasPrice': w3.eth.gas_price,
}
signed_tx = w3.eth.account.sign_transaction(tx, "YOUR_PRIVATE_KEY")
tx_hash = w3.eth.send_raw_transaction(signed_tx.rawTransaction)
print("TX Hash:", tx_hash.hex())
- Setup Contract
contract_address = "0xContractAddress"
contract_abi = '[{"inputs":[], "name":"getValue", "outputs":[{"internalType":"uint256","name":"","type":"uint256"}], "type":"function"}]'
contract = w3.eth.contract(address=contract_address, abi=contract_abi)
- Call & Transact
Read (Call)
value = contract.functions.getValue().call()
print("Value:", value)
Write (Transact)
tx = contract.functions.setValue(123).build_transaction({
'nonce': w3.eth.get_transaction_count("0xSender"),
'gas': 200000,
})
signed_tx = w3.eth.account.sign_transaction(tx, "YOUR_PRIVATE_KEY")
w3.eth.send_raw_transaction(signed_tx.rawTransaction)
Check Latest Block
print("Latest Block:", w3.eth.get_block('latest').number)
Listen to Events
event_filter = contract.events.ValueChanged.create_filter(fromBlock='latest')
for event in event_filter.get_new_entries():
print("Event:", event)
- Never hardcode private keys! Use environment variables.
- Test on testnets before mainnet.
- Use Web3.py v6+.
Get started in 5 minutes or take a tour of the library.
View the change log.
For additional guides, examples, and APIs, see the documentation.
Want to file a bug, contribute some code, or improve documentation? Excellent! Read up on our guidelines for contributing, then check out issues that are labeled Good First Issue.
Join the conversation in the Ethereum Python Community Discord.