web3.py
web3.py is a Python library designed for interacting with the Ethereum blockchain. It enables developers to build decentralized applications (dApps), manage Ethereum accounts, send transactions, interact with smart contracts, and query blockchain data. Currently at version 7.15.0, the library follows Semantic Versioning, with major versions introducing significant breaking changes and frequent minor updates for new features and bug fixes.
Warnings
- breaking Strict bytes checking is enabled by default in v6. This means ABI arguments expecting a specific bytes length (e.g., bytes4) will only accept 0x-prefixed hex strings or bytes types of that exact length. Ambiguous values will be invalidated.
- breaking Most API methods and properties were converted from `camelCase` to `snake_case` in v6 to align with Pythonic conventions. Exceptions include contract methods/events (which follow ABI) and JSON-RPC parameters/returns (which follow RPC spec).
- breaking In v6, the `Web3` class was split into `Web3` (for synchronous operations) and `AsyncWeb3` (for asynchronous operations). Providers must match the instance type (e.g., `AsyncWeb3` requires `AsyncHTTPProvider` or `WebSocketProvider`).
- breaking The middleware model changed to a class-based system in v7, replacing the older functional middleware. Middleware logic is now separated into `request_processor` and `response_processor` functions.
- breaking The `EthPM` module, deprecated in v6 due to lack of use and functionality issues, was completely removed in v7.
- gotcha Python 3.7 support was dropped in v7. The library now requires Python 3.8 or newer.
- deprecated The `geth.miner` namespace and its methods were deprecated in v6 and completely removed in v7, reflecting Geth's transition away from mining (Proof-of-Work) to Proof-of-Stake.
Install
-
pip install web3 -
pip install "web3[tester]"
Imports
- Web3
from web3 import Web3
- AsyncWeb3
from web3 import AsyncWeb3
- HTTPProvider
from web3 import HTTPProvider
- IPCProvider
from web3 import IPCProvider
- WebSocketProvider
from web3 import WebSocketProvider
Quickstart
import os
from web3 import Web3, HTTPProvider
# Replace with your actual RPC URL, e.g., from Infura, Alchemy, or a local node.
# It's best practice to use environment variables for sensitive info.
INFURA_URL = os.environ.get('WEB3_PROVIDER_URL', 'http://127.0.0.1:8545')
# Initialize Web3 with an HTTPProvider
try:
w3 = Web3(HTTPProvider(INFURA_URL))
if w3.is_connected():
print(f"Successfully connected to Ethereum node at {INFURA_URL}")
# Get the latest block number
latest_block = w3.eth.block_number
print(f"Latest block number: {latest_block}")
else:
print(f"Failed to connect to Ethereum node at {INFURA_URL}")
except Exception as e:
print(f"An error occurred: {e}")