Python provides robust libraries for Ethereum development, suitable for both simple scripts and complex applications.
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)
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
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))
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
}