web3.py

7.15.0 · active · verified Thu Apr 09

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

Install

Imports

Quickstart

This quickstart demonstrates how to connect to an Ethereum node using `HTTPProvider` and retrieve the latest block number. For asynchronous operations, use `AsyncWeb3` and an asynchronous provider like `AsyncHTTPProvider` or `WebSocketProvider`.

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}")

view raw JSON →