Skip to main content
CodeSpeedTest
Languages
Start TypingJump into a test — pick any languageAdaptive TrainingUnlock chars as you master themPractice DrillsFocused sessions targeting weak spotsDaily ChallengesNew coding challenges every dayRace ModeCompete against others in real timeAI OpponentRace against an AI at your WPM levelTournamentsLive coding speed tournamentsArcade GamesZType, Overkill Survival, Glyphica & moreGamificationXP, coins, badges & quests
LeaderboardGlobal rankings for every languageCertificatesEarn verifiable Bronze / Silver / Gold certsActivityDaily streaks & historical analyticsProfileYour stats, badges & achievements
Browse Languages500+ languages with real code examplesBlogTips, guides & deep divesFree ToolsWPM calculator, typing speed report & moreFAQCommon questions answeredGetting StartedNew to CodeSpeedTest?AboutOur story & missionSupportGet help — Pro users get priorityContactGet in touch with the team
Pricing
  1. Home
  2. /
  3. Learn
  4. /
  5. Web3py

Learn Web3py - 10 Code Examples & CST Typing Practice Test

Web3.py is a Python library for interacting with the Ethereum blockchain. It allows developers to deploy, interact with, and query smart contracts, manage accounts, and handle blockchain transactions programmatically.

View all 10 Web3py code examples →
Python Web3.py Simple Smart Contract InteractionWeb3.py Check Ether BalanceWeb3.py Deploy Simple ContractWeb3.py Listen to Contract EventsWeb3.py Send Ether TransactionWeb3.py Interact with ERC20 TokenWeb3.py Estimate GasWeb3.py Check Transaction ReceiptWeb3.py Call Contract View FunctionWeb3.py Deploy Contract with Constructor Args

Learn WEB3PY with Real Code Examples

Updated Nov 25, 2025

Explain

Web3.py provides Python bindings to Ethereum nodes via JSON-RPC, IPC, or WebSocket.

It allows developers to interact with smart contracts written in Solidity, Vyper, or other EVM-compatible languages.

Supports Ethereum mainnet, testnets (Goerli, Sepolia), and private chains.

Enables sending transactions, reading contract state, and listening to events.

Widely used in DeFi, NFT apps, and automation scripts in Python.

Core Features

eth.account for wallet management

eth.contract for smart contract interaction

eth.get_transaction_receipt to monitor transactions

eth.filter for event subscriptions

Middleware for provider customization

Basic Concepts Overview

Provider - connection to Ethereum node

Account - wallet for signing transactions

Contract - interface to smart contract via ABI

Transaction - value or method call sent to chain

Event - logs emitted by contracts

Project Structure

scripts/ - Web3.py scripts and automation

contracts/ - Solidity/Vyper source code

tests/ - integration and unit tests

config.py - node and account settings

README.md - documentation

Building Workflow

Connect Web3.py to Ethereum node

Load or deploy smart contract

Interact with contract functions

Sign and send transactions

Monitor events and transaction receipts

Difficulty Use Cases

Beginner: read account balance

Intermediate: interact with token contract

Advanced: automate DeFi trades

Expert: build NFT minting backend

Auditor: monitor blockchain events and logs

Comparisons

Web3.py vs Web3.js: Python vs JavaScript; backend-focused vs full-stack

Web3.py vs ethers.js: lower-level Python control vs modern JS library

Web3.py vs Solana Rust: Python/EVM vs Rust/BPF for Solana

Web3.py vs Clarity: Turing-complete EVM interactions vs decidable Stacks contracts

Web3.py vs Brownie: Brownie is a framework; Web3.py is the underlying library

Versioning Timeline

2016 - Web3.py initial release

2017-2018 - Added contract interaction features

2019 - Event filters and middleware support

2020-2022 - Python 3.8+ compatibility and async support

2023-2025 - Continuous updates and improved documentation

Glossary

JSON-RPC: protocol to interact with Ethereum nodes

ABI: Application Binary Interface for contracts

EVM: Ethereum Virtual Machine

Nonce: transaction counter for accounts

Gas: fee for executing transactions

Installation Setup

Install Python 3.8+

Install Web3.py via pip (`pip install web3`)

Set up an Ethereum node (Infura, Alchemy, or local Geth/Hardhat node)

Verify connection using Web3 provider

Test sending a simple transaction

Environment Setup

Install Python 3.8+

Set up virtual environment

Install Web3.py and dependencies

Connect to Ethereum node (Infura, Alchemy, or local)

Test sample script to query balance

Config Files

config.py - provider URLs and private keys

requirements.txt - dependencies

scripts/ - Web3.py scripts

tests/ - unit/integration tests

.env - environment variables for secrets

README.md - documentation

Cli Commands

python script.py - run Web3.py script

pip install web3 - install library

pytest - run tests

ganache-cli - local test node

solc - compile Solidity contracts

Internationalization

Documentation primarily in English

Supports Unicode for addresses and metadata

Community translations available

Used globally in blockchain projects

Compatible with multi-language Python apps

Accessibility

Accessible to Python developers

Clear documentation and tutorials

Community support for questions

Supports multiple OS platforms

Easy integration with scripts and apps

Ui Styling

Not applicable in Python library itself

Can integrate with web frontends via Flask/Django

Serve dashboards or analytics

Render event data or transaction history

Python handles backend logic only

State Management

Blockchain state managed via contract functions

Read-only state via eth.call

Write operations via signed transactions

Event subscriptions for state changes

No on-chain state stored in Python itself

Data Management

Contract storage accessed via Web3.py calls

Local caching optional for performance

Serialized data using JSON or web3 encoding

Historical logs via filters

Transactions tracked for confirmation

Architecture

Python library interfacing with Ethereum nodes

JSON-RPC, IPC, or WebSocket protocols

Contracts represented via ABI and bytecode

Events captured via filters and logs

Transactions signed via local or remote accounts

Rendering Model

Python code -> JSON-RPC calls to node

Node executes transactions on EVM

Contract interactions via ABI encoding/decoding

Events fetched via filters and logs

Transactions signed locally or via external providers

Architectural Patterns

Backend script-based architecture

Event-driven monitoring

Contract interaction via ABI

Middleware for provider customization

Integration with Python data pipelines

Real World Architectures

Backend for DeFi bots

NFT marketplace automation

Transaction monitoring and alerting

Analytics pipeline for token activity

Automated staking/reward scripts

Design Principles

Pythonic API design

Compatibility with Ethereum and EVM chains

Secure account and transaction handling

Flexible node connectivity

Event-driven architecture support

Scalability Guide

Batch queries using multicall patterns

Use async providers for multiple requests

Cache data locally if repeated reads

Limit event polling interval

Distribute scripts for heavy workloads

Migration Guide

Rewrite Node.js Web3 scripts in Python using Web3.py

Adjust async code to Python async/await

Map JavaScript ABI calls to Python contract methods

Use Python environment for keys and secrets

Test thoroughly on testnets before mainnet

Performance Notes

Dependent on node response and network latency

Best for backend scripts, not high-frequency on-chain operations

Batch queries via multicall can optimize performance

Async providers improve responsiveness

Event polling interval affects timeliness

Security Notes

Never expose private keys in code

Use environment variables or secure vaults

Validate contract addresses and ABI

Monitor transactions for errors

Use checksum addresses to prevent mistakes

Monitoring Analytics

Monitor transaction status

Track events and logs

Analyze contract state

Generate automated reports

Integrate with dashboards or notifications

Code Quality

Follow Python best practices

Write modular scripts

Document account and contract interactions

Handle exceptions and errors

Use unit tests for blockchain operations

Practical Examples

Send ETH or ERC20 token transaction

Read smart contract state

Subscribe to events for DeFi protocols

Automate NFT minting script

Fetch historical transaction logs

Troubleshooting

Check node connectivity

Verify correct ABI and contract address

Ensure account has sufficient funds

Handle gas estimation errors

Monitor RPC rate limits and timeouts

Testing Guide

Run local Ganache node for testing

Deploy contracts on testnet

Use pytest for script automation tests

Simulate transactions before sending to mainnet

Monitor logs for correct event emission

Deployment Options

Local development node (Ganache/Hardhat)

Testnet deployment (Goerli, Sepolia)

Mainnet deployment via Web3.py scripts

CI/CD integration for automated deployment

Environment-specific configuration management

Tools Ecosystem

Web3.py

Infura or Alchemy node providers

Ganache or Hardhat local node

Python testing frameworks (pytest)

eth-account and eth-utils libraries

Integrations

Ethereum mainnet and testnets

EVM-compatible chains (Polygon, BSC, Avalanche)

Python backend apps

DeFi bots and analytics scripts

NFT marketplaces backend

Productivity Tips

Use virtual environments for dependency management

Store secrets in environment variables

Test scripts on local or testnet nodes

Use async Web3 providers for efficiency

Document scripts and workflows clearly

Challenges

Handling RPC node failures

Gas management and transaction errors

Understanding contract ABI structure

Async handling for event polling

Debugging blockchain network issues

Learning Path

Learn Python basics

Understand Ethereum accounts, gas, and transactions

Practice connecting to nodes via Web3.py

Interact with smart contracts

Automate backend workflows and DeFi scripts

Skill Improvement Plan

Week 1: Python and JSON-RPC basics

Week 2: Account management and sending ETH

Week 3: Contract interaction via ABI

Week 4: Event subscription and filters

Week 5: Build full Python backend integration

Interview Questions

What is Web3.py used for?

How do you send a transaction using Web3.py?

How do you interact with a deployed smart contract?

Difference between mainnet and testnet connections?

How do you listen to contract events?

Cheat Sheet

Web3 -> connection to Ethereum node

Account -> wallet object

Contract -> smart contract object via ABI

Transaction -> signed and sent to chain

Event -> logs filtered from contract

Books

Mastering Ethereum with Python

Building DeFi Bots with Web3.py

Python for Blockchain Developers

Automating NFT Workflows with Web3.py

Web3.py Cookbook

Tutorials

Getting started with Web3.py

Send ETH and ERC20 transactions

Interact with deployed smart contracts

Event listening and logging

Automate DeFi or NFT backend tasks

Official Docs

https://web3py.readthedocs.io/en/stable/

https://github.com/ethereum/web3.py

Community Links

Web3.py GitHub Discussions

Ethereum StackExchange

Reddit r/ethdev

Python Ethereum community Discord

YouTube Web3.py tutorials

Community Support

Web3.py GitHub

Ethereum StackExchange

Python Ethereum Community

Reddit r/ethdev

YouTube tutorials for Web3.py

Monetization

DeFi trading bots

NFT automation services

Subscription-based monitoring scripts

Analytics dashboards

Backend solutions for blockchain apps

Future Roadmap

Async provider improvements

Expanded support for L2s and sidechains

Better event subscription mechanisms

Integration with Python web frameworks

Community-driven documentation and examples

When Not To Use

Non-EVM blockchains

High-frequency, low-latency on-chain programs

Frontend-heavy DApps requiring JS frameworks

Projects needing large-scale Rust/Solana performance

Smart contract development frameworks like Brownie preferred for deployment automation

Final Summary

Web3.py is a Python library for Ethereum blockchain interaction.

Used for smart contract deployment, interaction, and event monitoring.

Backend-focused and Pythonic, ideal for automation and analytics.

Supports mainnet, testnets, and private chains.

Easily integrates into Python projects for DeFi, NFTs, and scripts.

Faq

Can Web3.py interact with testnets?

Yes - supports Goerli, Sepolia, and private nodes.

Is Web3.py compatible with Python 3.8+?

Yes, Python 3.8+ is recommended.

Can Web3.py deploy smart contracts?

Yes - deploy contracts with compiled ABI and bytecode.

Can Web3.py be used for NFTs?

Yes - mint, transfer, and interact with NFT contracts.

Is Web3.py suitable for DeFi bots?

Yes - widely used for automated scripts and backend integrations.

Code Sample Descriptions

1

Python Web3.py Simple Smart Contract Interaction

from web3 import Web3

# Connect to local Ethereum node
w3 = Web3(Web3.HTTPProvider('http://127.0.0.1:8545'))

# Contract ABI and address (example)
abi = '[...]'
address = '0xYourContractAddress'
contract = w3.eth.contract(address=address, abi=abi)

# Read value from contract
value = contract.functions.getValue().call()
print('Contract value:', value)

# Send transaction to contract
tx_hash = contract.functions.setValue(42).transact({'from': w3.eth.accounts[0]})
w3.eth.wait_for_transaction_receipt(tx_hash)

A minimal example showing how to connect to Ethereum and interact with a deployed smart contract using Web3.py.

Let’s Try →
2

Web3.py Check Ether Balance

from web3 import Web3

w3 = Web3(Web3.HTTPProvider('http://127.0.0.1:8545'))
account = '0xYourAccountAddress'
balance = w3.eth.get_balance(account)
print('Balance:', w3.fromWei(balance, 'ether'), 'ETH')

Check the Ether balance of an account using Web3.py.

Let’s Try →
3

Web3.py Deploy Simple Contract

from web3 import Web3
from solcx import compile_source

w3 = Web3(Web3.HTTPProvider('http://127.0.0.1:8545'))

source_code = 'contract Simple { uint public x; function set(uint val) public { x = val; } }'
compiled = compile_source(source_code)
contract_interface = compiled['<stdin>:Simple']
Simple = w3.eth.contract(abi=contract_interface['abi'], bytecode=contract_interface['bin'])
tx_hash = Simple.constructor().transact({'from': w3.eth.accounts[0]})
tx_receipt = w3.eth.wait_for_transaction_receipt(tx_hash)
print('Contract deployed at:', tx_receipt.contractAddress)

Deploy a simple Solidity contract using Web3.py.

Let’s Try →
4

Web3.py Listen to Contract Events

from web3 import Web3

w3 = Web3(Web3.HTTPProvider('http://127.0.0.1:8545'))
abi = '[...]'
address = '0xYourContractAddress'
contract = w3.eth.contract(address=address, abi=abi)

event_filter = contract.events.YourEvent.createFilter(fromBlock='latest')
for event in event_filter.get_new_entries():
    print(event)

Subscribe to events emitted by a smart contract.

Let’s Try →
5

Web3.py Send Ether Transaction

from web3 import Web3

w3 = Web3(Web3.HTTPProvider('http://127.0.0.1:8545'))
from_account = w3.eth.accounts[0]
to_account = w3.eth.accounts[1]

tx = {
    'from': from_account,
    'to': to_account,
    'value': w3.toWei(0.1, 'ether'),
    'gas': 21000,
    'gasPrice': w3.toWei('50', 'gwei')
}
tx_hash = w3.eth.send_transaction(tx)
w3.eth.wait_for_transaction_receipt(tx_hash)

Send Ether from one account to another using Web3.py.

Let’s Try →
6

Web3.py Interact with ERC20 Token

from web3 import Web3

w3 = Web3(Web3.HTTPProvider('http://127.0.0.1:8545'))
abi = '[...]'
address = '0xTokenContractAddress'
contract = w3.eth.contract(address=address, abi=abi)

# Check token balance
balance = contract.functions.balanceOf(w3.eth.accounts[0]).call()
print('Token Balance:', balance)

# Transfer tokens
tx_hash = contract.functions.transfer(w3.eth.accounts[1], 100).transact({'from': w3.eth.accounts[0]})
w3.eth.wait_for_transaction_receipt(tx_hash)

Read balance and transfer ERC20 tokens.

Let’s Try →
7

Web3.py Estimate Gas

from web3 import Web3

w3 = Web3(Web3.HTTPProvider('http://127.0.0.1:8545'))
abi = '[...]'
address = '0xYourContractAddress'
contract = w3.eth.contract(address=address, abi=abi)

gas_estimate = contract.functions.setValue(42).estimateGas({'from': w3.eth.accounts[0]})
print('Estimated Gas:', gas_estimate)

Estimate gas required for a contract function call.

Let’s Try →
8

Web3.py Check Transaction Receipt

from web3 import Web3

w3 = Web3(Web3.HTTPProvider('http://127.0.0.1:8545'))
tx_hash = '0xYourTransactionHash'
receipt = w3.eth.get_transaction_receipt(tx_hash)
print(receipt)

Fetch and inspect a transaction receipt.

Let’s Try →
9

Web3.py Call Contract View Function

from web3 import Web3

w3 = Web3(Web3.HTTPProvider('http://127.0.0.1:8545'))
abi = '[...]'
address = '0xYourContractAddress'
contract = w3.eth.contract(address=address, abi=abi)

result = contract.functions.getValue().call()
print('Value:', result)

Call a read-only function from a deployed smart contract.

Let’s Try →
10

Web3.py Deploy Contract with Constructor Args

from web3 import Web3
from solcx import compile_source

w3 = Web3(Web3.HTTPProvider('http://127.0.0.1:8545'))
source = 'contract Greeter { string public greeting; constructor(string memory _g) { greeting = _g; } }'
compiled = compile_source(source)
contract_interface = compiled['<stdin>:Greeter']
Greeter = w3.eth.contract(abi=contract_interface['abi'], bytecode=contract_interface['bin'])
tx_hash = Greeter.constructor('Hello Web3').transact({'from': w3.eth.accounts[0]})
tx_receipt = w3.eth.wait_for_transaction_receipt(tx_hash)
print('Deployed at:', tx_receipt.contractAddress)

Deploy a Solidity contract providing constructor parameters.

Let’s Try →

Frequently Asked Questions about Web3py

What is Web3py?

Web3.py is a Python library for interacting with the Ethereum blockchain. It allows developers to deploy, interact with, and query smart contracts, manage accounts, and handle blockchain transactions programmatically.

What are the primary use cases for Web3py?

Deploying and interacting with smart contracts. Reading blockchain data and logs. Automating DeFi and trading operations. NFT minting and marketplaces. Backend blockchain integrations in Python

What are the strengths of Web3py?

Pythonic syntax easy for Python developers. Supports multiple Ethereum node connections. Flexible event and contract interaction. Easy to integrate with Python data pipelines. Strong community support and tutorials

What are the limitations of Web3py?

Limited to Ethereum and EVM-compatible chains. Performance bound by Python execution and node RPC. Not suitable for high-frequency on-chain computation. No native GUI; backend-focused. Dependent on node availability and sync status

How can I practice Web3py typing speed?

CodeSpeedTest offers 10+ real Web3py code examples for typing practice. You can measure your WPM, track accuracy, and improve your coding speed with guided exercises.

Learn Other Programming Languages

CReactPythonC++RustTypeScriptKotlinPHPJavaC#RubyMqlCqlN1qlCypherGremlinPartiqlHaskellElixirFsharpView all languages →
CodeSpeedTest

Improve your coding speed, code accuracy, and programming syntax WPM with practice sessions across 500+ programming languages.

Quick Links

HomeAboutFeaturesGetting StartedLanguages

Legal & Support

Pro ⚡ PricingContactPrivacy PolicyTerms of Service

Connect

CodeSpeedTest on GitHubCodeSpeedTest on TwitterEmail CodeSpeedTest

© 2026 CodeSpeedTest. All rights reserved.