Getting started with TheRPC

Python Tools

Python provides robust libraries for Ethereum development, suitable for both simple scripts and complex applications.

Pay attention!
Hey there! Just a friendly heads-up: this page is meant to give you a solid overview of working with Python requests. For hands-on code examples, check out our API Methods documentation where you'll find ready-to-use examples in all supported languages!

# Web3.py

Official Python Ethereum library.

from web3 import Web3
from eth_account import Account
import json

# Initialize web3
web3 = Web3(Web3.HTTPProvider('YOUR_ETHEREUM_NODE_URL'))

# Get balance
def get_balance(address):
    balance_wei = web3.eth.get_balance(address)
    balance_eth = web3.from_wei(balance_wei, 'ether')
    return balance_eth

# Send transaction
def send_transaction(private_key, to_address, value_eth):
    account = Account.from_key(private_key)
    transaction = {
        'nonce': web3.eth.get_transaction_count(account.address),
        'to': to_address,
        'value': web3.to_wei(value_eth, 'ether'),
        'gas': 21000,
        'gasPrice': web3.eth.gas_price
    }
    signed_txn = account.sign_transaction(transaction)
    tx_hash = web3.eth.send_raw_transaction(signed_txn.rawTransaction)
    return web3.eth.wait_for_transaction_receipt(tx_hash)
  • GitHub: web3.py
  • Documentation: web3py.readthedocs.io
  • Features:
    • Full Ethereum API support
    • Sync and async interfaces
    • Type hints
    • Middleware support
    • ENS support

# Eth-brownie

Python framework for Ethereum development.

from brownie import *

# Deploy contract
def deploy_contract():
    account = accounts[0]
    return MyContract.deploy({'from': account})

# Interact with contract
def interact_with_contract(contract_address):
    contract = MyContract.at(contract_address)
    return contract.myFunction({'from': accounts[0]})

# Test contract
def test_contract(Contract):
    account = accounts[0]
    contract = account.deploy(Contract)
    assert contract.myFunction() == expected_value

# Async Support

Web3.py provides async support for better performance:

from web3.auto import w3
import asyncio

async def get_latest_blocks(count):
    latest = await w3.eth.get_block_number()
    blocks = []
    for i in range(count):
        block = await w3.eth.get_block(latest - i)
        blocks.append(block)
    return blocks

# Usage
blocks = asyncio.run(get_latest_blocks(10))

# Type Hints

Web3.py includes comprehensive type hints for better IDE support:

from web3.types import TxParams, Wei, Address
from typing import Optional

def prepare_transaction(
    to: Address,
    value: Wei,
    gas_price: Optional[Wei] = None
) -> TxParams:
    return {
        'to': to,
        'value': value,
        'gasPrice': gas_price or web3.eth.gas_price
    }

See also

Help Us Get Better!
Share this page and help us create an even better product for you.