> ## Documentation Index
> Fetch the complete documentation index at: https://docs.sei.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Python Quickstart (web3.py)

> Connect to Sei from Python using web3.py — read chain data, then sign and broadcast transactions against the Sei EVM JSON-RPC.

export const RunSnippet = props => {
  const {method = 'eth_blockNumber', params = [], network = 'testnet', endpoint, label, title, description, decode = 'auto'} = props || ({});
  const ENDPOINTS = {
    testnet: 'https://evm-rpc-testnet.sei-apis.com',
    mainnet: 'https://evm-rpc.sei-apis.com'
  };
  const rpcUrl = endpoint || ENDPOINTS[network] || ENDPOINTS.testnet;
  const networkLabel = network === 'mainnet' ? 'pacific-1 · mainnet' : network === 'testnet' ? 'atlantic-2 · testnet' : network;
  const requestBody = {
    jsonrpc: '2.0',
    id: 1,
    method,
    params
  };
  const requestJson = JSON.stringify(requestBody, null, 2);
  const [phase, setPhase] = useState('idle');
  const [result, setResult] = useState(null);
  const [errorMsg, setErrorMsg] = useState(null);
  const [elapsed, setElapsed] = useState(null);
  const [copied, setCopied] = useState(false);
  const [btnHover, setBtnHover] = useState(false);
  const groupThousands = s => s.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
  const hexToDecimal = value => {
    if (typeof value !== 'string' || !(/^0x[0-9a-fA-F]+$/).test(value)) return null;
    if (value.length > 66) return null;
    try {
      return groupThousands(BigInt(value).toString(10));
    } catch (e) {
      return null;
    }
  };
  const run = async () => {
    setPhase('loading');
    setErrorMsg(null);
    setResult(null);
    setElapsed(null);
    const startedAt = typeof performance !== 'undefined' ? performance.now() : null;
    try {
      const response = await fetch(rpcUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(requestBody)
      });
      const data = await response.json();
      if (startedAt != null && typeof performance !== 'undefined') {
        setElapsed(Math.round(performance.now() - startedAt));
      }
      if (data && data.error) {
        setErrorMsg(data.error.message || 'RPC returned an error');
        setPhase('error');
        return;
      }
      setResult(data ? data.result : undefined);
      setPhase('success');
    } catch (err) {
      setErrorMsg(err && err.message ? err.message : 'Request failed');
      setPhase('error');
    }
  };
  const resultString = result === undefined ? 'undefined' : JSON.stringify(result, null, 2);
  const decoded = decode !== 'off' && typeof result === 'string' ? hexToDecimal(result) : null;
  const copyResult = () => {
    const flashCopied = () => {
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    };
    if (typeof navigator !== 'undefined' && navigator.clipboard && navigator.clipboard.writeText) {
      navigator.clipboard.writeText(resultString).then(flashCopied, () => {});
      return;
    }
    if (typeof document !== 'undefined') {
      try {
        const ta = document.createElement('textarea');
        ta.value = resultString;
        ta.style.position = 'fixed';
        ta.style.opacity = '0';
        document.body.appendChild(ta);
        ta.select();
        document.execCommand('copy');
        document.body.removeChild(ta);
        flashCopied();
      } catch (e) {}
    }
  };
  const HAIRLINE = 'rgba(128, 128, 128, 0.25)';
  const surfaceStyle = {
    backgroundColor: 'rgba(128, 128, 128, 0.08)'
  };
  const monoStyle = {
    fontFamily: 'var(--sei-font-mono)'
  };
  const codeStyle = {
    backgroundColor: 'rgba(128, 128, 128, 0.05)',
    fontFamily: 'var(--sei-font-mono)'
  };
  const cardClass = 'not-prose w-full rounded-lg border overflow-hidden my-4';
  const headerClass = 'flex items-center justify-between gap-3 px-4 py-2.5 border-b';
  const labelClass = 'text-xs uppercase tracking-wide text-neutral-500 dark:text-neutral-500';
  const preClass = 'm-0 px-4 py-3 text-sm overflow-x-auto text-neutral-700 dark:text-neutral-300';
  const buttonStyle = {
    backgroundColor: btnHover ? 'var(--sei-maroon-200)' : 'var(--sei-maroon-100)',
    color: '#ffffff',
    fontFamily: 'var(--sei-font-mono)',
    textTransform: 'uppercase',
    letterSpacing: '0.04em',
    fontSize: '10px',
    opacity: phase === 'loading' ? 0.7 : 1,
    cursor: phase === 'loading' ? 'default' : 'pointer'
  };
  return <div className={cardClass} style={{
    borderColor: HAIRLINE
  }}>
			<div className={headerClass} style={{
    ...surfaceStyle,
    borderBottomColor: HAIRLINE
  }}>
				<div className="flex flex-col min-w-0">
					<span className="text-sm font-medium text-neutral-900 dark:text-white truncate" style={monoStyle}>
						{title || method}
					</span>
					<span className="text-xs text-neutral-500 dark:text-neutral-500">{networkLabel}</span>
				</div>
				<button type="button" onClick={run} disabled={phase === 'loading'} onMouseEnter={() => setBtnHover(true)} onMouseLeave={() => setBtnHover(false)} className="inline-flex items-center gap-1.5 px-3 py-1.5 shrink-0 transition-colors" style={buttonStyle}>
					{phase === 'loading' ? <svg className="animate-spin h-4 w-4" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
								<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
								<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 0 1 8-8v4a4 4 0 0 0-4 4H4z" />
							</svg> : <svg aria-hidden="true" xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="currentColor">
								<path d="M8 5v14l11-7z" />
							</svg>}
					{phase === 'loading' ? 'Running…' : label || 'Run'}
				</button>
			</div>

			{description ? <div className="px-4 pt-3 text-sm text-neutral-600 dark:text-neutral-400">{description}</div> : null}

			<div className="px-4 pt-3 pb-1">
				<span className={labelClass}>Request</span>
			</div>
			<pre className={preClass} style={codeStyle}>
				{requestJson}
			</pre>

			{phase === 'success' ? <div className="border-t" style={{
    borderTopColor: HAIRLINE
  }}>
					<div className="flex items-center justify-between px-4 pt-3 pb-1">
						<span className={labelClass}>Response{elapsed != null ? ` · ${elapsed} ms` : ''}</span>
						<button type="button" onClick={copyResult} className="text-xs text-neutral-500 hover:text-neutral-800 dark:text-neutral-400 dark:hover:text-neutral-200 transition-colors">
							{copied ? 'Copied' : 'Copy'}
						</button>
					</div>
					<pre className={preClass} style={codeStyle}>
						{resultString}
					</pre>
					{decoded ? <div className="px-4 pb-3 text-xs text-neutral-500 dark:text-neutral-500" style={monoStyle}>
							= {decoded} (decimal)
						</div> : null}
				</div> : null}

			{phase === 'error' ? <div className="border-t" style={{
    borderTopColor: HAIRLINE
  }}>
					<div className="px-4 pt-3 pb-1">
						<span className={labelClass}>Error</span>
					</div>
					<pre className={`${preClass} text-red-600 dark:text-red-400`} style={codeStyle}>
						{errorMsg}
					</pre>
				</div> : null}
		</div>;
};

Sei is fully EVM-compatible, so any standard Ethereum client works — including Python's [web3.py](https://web3py.readthedocs.io). This guide connects to Sei from a Python script, reads chain data with no credentials, then signs and broadcasts a transaction.

## Install

We recommend an isolated virtual environment:

```bash theme={"dark"}
python3 -m venv venv
source venv/bin/activate          # Windows: venv\Scripts\activate
pip install web3
```

## Reading Chain Data

This is the first milestone — it needs no private key.

```python theme={"dark"}
from web3 import Web3

w3 = Web3(Web3.HTTPProvider("https://evm-rpc.sei-apis.com"))

# Any valid Sei EVM address — swap in your own
address = "0x0000000000000000000000000000000000000000"

print("Connected:", w3.is_connected())
print("Chain ID:", w3.eth.chain_id)                                  # 1329 on mainnet
print("Latest block:", w3.eth.block_number)
print("Balance (SEI):", w3.from_wei(w3.eth.get_balance(address), "ether"))
print("Nonce:", w3.eth.get_transaction_count(address))
```

**You're done when you see:**

```text theme={"dark"}
Connected: True
Chain ID: 1329
Latest block: 148203117
Balance (SEI): 12.5
Nonce: 7
```

Values are illustrative — your block number, and the queried address's balance and nonce, will differ. The chain ID is always `1329` on mainnet (`1328` on the atlantic-2 testnet).

## Try it live

`web3.py` issues plain JSON-RPC under the hood — here are the same reads against Sei mainnet, no Python required.

<RunSnippet method="eth_chainId" network="mainnet" title="w3.eth.chain_id" description="The mainnet chain ID — decodes to 1329." />

<RunSnippet method="eth_blockNumber" network="mainnet" title="w3.eth.block_number" description="Latest committed block on pacific-1." />

<RunSnippet method="eth_getBalance" params={['0x0000000000000000000000000000000000000000', 'latest']} network="mainnet" title="w3.eth.get_balance(address)" description="Wei balance of the example address — swap in your own. w3.from_wei(…, 'ether') converts it to SEI." />

## Sending a Transaction

Next step — this requires a funded account. Get testnet SEI from the [faucet](/learn/faucet), then build, **sign locally**, and broadcast with `eth_sendRawTransaction`. Public RPC endpoints don't manage accounts, so you sign the transaction yourself rather than relying on node-managed accounts.

```python theme={"dark"}
import os
from web3 import Web3

# atlantic-2 testnet
w3 = Web3(Web3.HTTPProvider("https://evm-rpc-testnet.sei-apis.com"))

account = w3.eth.account.from_key(os.environ["SEI_PRIVATE_KEY"])

tx = {
    "to": "0xRecipient",
    "value": w3.to_wei(0.001, "ether"),
    "nonce": w3.eth.get_transaction_count(account.address),
    "chainId": w3.eth.chain_id,
    "type": 2,  # EIP-1559
    "maxPriorityFeePerGas": w3.to_wei(1, "gwei"),
    "maxFeePerGas": w3.eth.gas_price * 2 + w3.to_wei(1, "gwei"),
}
tx["gas"] = w3.eth.estimate_gas(tx)  # always estimate rather than hard-coding

signed = w3.eth.account.sign_transaction(tx, account.key)
tx_hash = w3.eth.send_raw_transaction(signed.raw_transaction)

receipt = w3.eth.wait_for_transaction_receipt(tx_hash)
print("Mined in block:", receipt.blockNumber)  # final immediately — Sei has instant finality
```

<Warning>Never hard-code or commit a private key. Load it from an environment variable or a secrets manager, and use a dedicated throwaway key funded with only what you need.</Warning>

<Note>`signed.raw_transaction` is the attribute name in web3.py v7+. On web3.py v6 it is `signed.rawTransaction`.</Note>

## Reading a Contract

```python theme={"dark"}
abi = [{
    "constant": True,
    "inputs": [{"name": "owner", "type": "address"}],
    "name": "balanceOf",
    "outputs": [{"name": "", "type": "uint256"}],
    "stateMutability": "view",
    "type": "function",
}]

token = w3.eth.contract(address="0xTokenAddress", abi=abi)
print(token.functions.balanceOf(address).call())
```

## Next Steps

* [viem Quickstart](/evm/evm-parity/examples/viem-quickstart) — the TypeScript/Node.js equivalent
* [ethers v6 Quickstart](/evm/evm-parity/examples/ethers-quickstart) — TypeScript with ethers
* [Network information](/evm/networks) — RPC endpoints, chain IDs, and explorers
* [Faucet](/learn/faucet) — get testnet SEI
