Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
How to Mock a Failing Dependency to Test Error Paths in Python
Inject a fake HTTP client that raises a connection error to test how code handles dependency failures without touching the network.
import requests
def fetch_user(user_id):
url = f"https://api.example.com/users/{user_id}"
response = requests.get(url, timeout=5)
response.raise_for_status()
return response.json()
def get_user_name(user_id, http_client):
try:
user_data = http_client(user_id)
return user_data["nam…
Retry an Operation on ConnectionError in Python
Retries an unreliable operation a fixed number of times when it raises a transient ConnectionError, with a small delay between attempts.
import time
import random
def unreliable_operation():
"""Simulates an operation that throws ConnectionError occasionally."""
if random.random() < 0.6:
raise ConnectionError("Transient network failure")
return "Operation succeeded"
def retry_operation(attempts=4, delay=0.2):
"""Retries the o…
Find Broken Image References Across a Website in Python
Crawl internal pages of a website, collect all image source URLs, then check each with HEAD requests to report any that return HTTP 4xx or connection errors.
import requests
from urllib.parse import urljoin, urlparse
from bs4 import BeautifulSoup
from concurrent.futures import ThreadPoolExecutor, as_completed
def find_all_links(base_url, max_pages=50):
visited, to_visit = set(), {base_url}
while to_visit and len(visited) < max_pages:
url = to_visit.pop()
…
How to Monitor USB Device Connections in Python
A Python utility that monitors USB device connections and disconnections by comparing output of the lsusb command at regular intervals.
import time
import subprocess
import os
def get_usb_devices():
"""Return list of currently connected USB devices (Linux)."""
try:
result = subprocess.run(['lsusb'], capture_output=True, text=True, check=True)
return result.stdout.strip().split('\n')
except (subprocess.CalledProcessError, F…
How to Write an IP Block List to hosts.deny in Python
This Python script validates a list of IP addresses and CIDR ranges, then writes them to a hosts.deny file to block connections at the TCP wrapper level.
from ipaddress import ip_network
def write_hosts_deny(ip_list, output_file="hosts.deny"):
with open(output_file, "w") as f:
for ip in ip_list:
try:
ip_network(ip)
f.write(f"ALL: {ip}\n")
except ValueError:
continue
print(f"Written…
How to Mock Fabric Connections in Python for Task Testing
Create a lightweight MockConnection class to replace fabric.Connection and test task functions without SSH.
from fabric import Connection
class MockConnection:
"""Minimal mock of fabric.Connection for task testing."""
def __init__(self):
self.commands = []
def run(self, command, **kwargs):
self.commands.append(command)
return f"OK: {command}"
def deploy(conn):
"""Deploy the app:…
How to Mock asyncio.open_connection in Python
Mock asyncio.open_connection with AsyncMock to test async code without a real network connection.
import asyncio
from unittest.mock import AsyncMock, patch
async def fetch_data(reader: asyncio.StreamReader) -> str:
data = await reader.readline()
return data.decode().strip()
async def main() -> None:
# Mock asyncio.open_connection to simulate a server response
mock_reader = AsyncMock()
mock_…
How to Send and Receive Messages Between Processes with multiprocessing.Pipe in Python
Use multiprocessing.Pipe to create a two-way connection between two processes, send a message from parent to child, and receive a reply back.
import multiprocessing
def child_process(conn):
"""Receive from parent and send back a response."""
message = conn.recv()
print(f"Child received: {message}")
conn.send("Hello from child!")
if __name__ == "__main__":
parent_conn, child_conn = multiprocessing.Pipe()
process = multiprocessing…
How to Test HTTPX Async Client Pool Reuse with Mocks in Python
Mock an httpx.AsyncClient to verify connection pool reuse by asserting GET calls share a single client instance across concurrent async requests.
import asyncio
import httpx
from unittest.mock import AsyncMock, patch, Mock
async def fetch_with_pool(client, url, n_reuses=3):
results = []
for i in range(n_reuses):
resp = await client.get(url)
results.append(resp.status_code)
await asyncio.sleep(0) # yield to loop to mimic real us…
Use pytest fixture to mock a database connection in Python
This code shows how to use a pytest fixture and unittest.mock to replace a database connection with a Mock, enabling isolated tests without a real database.
import pytest
import sqlite3
from unittest.mock import Mock
class Database:
def __init__(self, connection):
self.connection = connection
def get_user(self, user_id):
cursor = self.connection.cursor()
cursor.execute("SELECT * FROM users WHERE id = ?", (user_id,))
return cursor.…
Object Pool Pattern for Database Connections in Python
Implements a reusable connection pool with acquire/release and context manager support, mocking database connections with idle reuse and exhaustion handling.
import time
from contextlib import contextmanager
from collections import deque
class ConnectionPool:
def __init__(self, size=3, max_idle=5):
self._idle = deque(maxlen=max_idle)
self._active = set()
self.size = size
def _create(self):
return {"created_at": time.time(), "queri…
How to Build a WebSocket Echo Server in Python with asyncio
Create a simple WebSocket echo server using the websockets library and asyncio to handle concurrent connections.
import asyncio
import websockets
async def echo(websocket):
async for message in websocket:
await websocket.send(f"Echo: {message}")
async def main():
async with websockets.serve(echo, "localhost", 8765):
print("WebSocket server started on ws://localhost:8765")
await asyncio.Future() …
How to mock RabbitMQ queue binding with routing keys in Python
A mock demonstration of binding a queue to an exchange with multiple routing keys in RabbitMQ using Python and pika, without a real broker connection.
import pika
import sys
def bind_queue_with_routing(channel, queue_name, exchange_name, routing_keys):
"""
Mock RabbitMQ queue binding with routing keys.
Prints the binding configuration instead of connecting to a real broker.
"""
for routing_key in routing_keys:
binding = {
"q…
How to Create a TCP DNS Mock Server in Python
This code creates a mock TCP DNS server that listens on a specified port, accepts probe connections, and returns a fixed DNS response header to simulate a live DNS service for testing and observability.
import socket
import threading
def handle_client(client_socket, address):
print(f"[+] Connection from {address}")
try:
while True:
data = client_socket.recv(1024)
if not data:
break
print(f"[*] Received {len(data)} bytes (TCP DNS probe)")
…
How to Mock a Server-Side Load Balancer in Python
A simple Python class that mimics a server-side load balancer with round-robin, random, and least-connections selection strategies.
import itertools
import random
class LoadBalancer:
def __init__(self, servers=None):
self.servers = servers if servers else ["server1", "server2", "server3"]
self.counter = itertools.count(1)
def round_robin(self):
return next(self.counter) % len(self.servers)
def random_selectio…
How to Build a Connection Pool Reuse Mock in Python
Build a mock connection pool with context manager to track connection reuse, acquires, and releases in Python.
import time
from contextlib import contextmanager
class Connection:
def __init__(self, name):
self.name = name
self.in_use = False
self.busy_since = None
def fetch(self):
return f"data from {self.name}"
class ConnectionPool:
def __init__(self, size=3):
self.conn…
Enforce TLS 1.2 Minimum in Python
Create an SSL context with a minimum TLS version of 1.2 to enforce secure connections.
import ssl
def get_min_tls_version():
context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
context.minimum_version = ssl.TLSVersion.TLSv1_2
return context.minimum_version
if __name__ == "__main__":
min_version = get_min_tls_version()
print(f"Minimum TLS version set to: {min_version.name} (value: {mi…
How to Drain a Connection Pool Before Exit in Python
Gracefully close all pooled sockets using a thread-safe ConnectionPool that drains connections before program exit.
import socket
import threading
import time
import random
class ConnectionPool:
def __init__(self, size=5):
self.pool = []
self.lock = threading.Lock()
self.closed = False
for _ in range(size):
self.pool.append(self.create_connection())
def create_connection(sel…
How to Mock a Dependency for Readiness Probe in Python
Use unittest.mock.Mock to simulate a dependency's readiness check response for testing a service's is_ready method without hitting a real connection.
import time
import unittest
from unittest.mock import Mock
class Service:
def __init__(self, dependency):
self.dependency = dependency
def is_ready(self):
try:
result = self.dependency.check()
return result == "ready"
except Exception:
return False
…
Browse by section
Each section groups closely related Python snippets.
Guide: free Python code samples library
Copy-ready Python snippets for learners and developers
PythonSkillset code samples are short, focused examples organised by topic and difficulty. Every snippet is server-rendered HTML — readable by search engines and easy to copy. Open any sample, read the notes, copy the code, then press Try in editor to run it in the browser with Pyodide.
How to use this library
- Pick a topic section — strings, lists, files, functions, and more
- Open a sample, read How it works, and copy the code block
- Run it in the IDE, tweak values, then take a related quiz or tutorial lesson
Samples vs tutorials and challenges
Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.