Python Code
Samples
Easy snippets you can copy, study, and run 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…
Create a Simple HTTP File Server in Python
This code creates a simple HTTP file server that serves files from the current working directory on port 8000 using Python's built-in http.server module.
import http.server
import socketserver
import os
PORT = 8000
DIRECTORY = os.getcwd()
class CustomHandler(http.server.SimpleHTTPRequestHandler):
def __init__(self, *args, **kwargs):
super().__init__(*args, directory=DIRECTORY, **kwargs)
def log_message(self, format, *args):
print(f"[{self.log…
How to Map Network Drive Paths to Local Paths in Python
Convert mock SMB network drive paths (like 'S:\reports\q1.xlsx') to local placeholder paths and back using a simple mapping dictionary in Python.
"""Map mock SMB network drive paths to local placeholder paths."""
from dataclasses import dataclass
@dataclass(frozen=True)
class NetworkDrive:
letter: str
remote_path: str
DRIVES = {
"S:": NetworkDrive("S", r"\\server01\shares\sales"),
"M:": NetworkDrive("M", r"\\server02\media\movies"),
"X:": …
How to Perform a DNS Lookup for A Records in Python
Resolve a hostname to IPv4 A records using Python's built-in socket.getaddrinfo and return a sorted list of addresses.
import socket
def get_a_records(hostname):
"""Fetch A records (IPv4 addresses) for a given hostname."""
try:
# getaddrinfo with family AF_INET restricts to IPv4 (A records)
infos = socket.getaddrinfo(hostname, None, socket.AF_INET)
# Each info tuple: (family, type, proto, canonname, so…
How to Simulate a Traceroute in Python
This Python script simulates a network traceroute by generating mock hop IPs, random delays, and a destination reach condition, useful for testing network scripts.
import random
import time
def simulate_traceroute(destination, max_hops=30):
"""Simulate a traceroute to a destination with mock hop delays."""
print(f"Traceroute to {destination} ({max_hops} hops max):")
for hop in range(1, max_hops + 1):
# Mock IP address for the hop
mock_ip = f"10.0.{ra…
Port Scan Localhost Common Ports in Python
Scan common localhost ports (HTTP, HTTPS, SSH, FTP, and more) with a fast socket-based Python script that prints an open/closed status table.
import socket
from datetime import datetime
COMMON_PORTS = {
80: "HTTP",
443: "HTTPS",
22: "SSH",
21: "FTP",
25: "SMTP",
3306: "MySQL",
5432: "PostgreSQL"
}
def scan_port(port):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(0.1)
try:
resu…
Toggle VPN Mock Network Manager Script in Python
Simulate a VPN manager with connect, disconnect, toggle, and status methods for testing or demo workflows.
import time
class MockVPNManager:
def __init__(self):
self.is_connected = False
self.servers = ["us-west", "eu-central", "asia-east"]
self.active_server = None
def toggle(self):
if self.is_connected:
self.disconnect()
else:
self.connect()
d…
Create a Mock GitHub Release API in Python for Testing gh CLI
Build an in-memory GitHub Releases API mock that mimics create_release and list_releases for unit testing gh CLI stubs without network calls.
import json
from unittest.mock import patch, Mock
class GitHubReleaseAPI:
"""Mock GitHub Releases API for testing gh CLI stub behavior."""
def __init__(self):
self.releases = {}
self.counter = 1
def create_release(self, repo, tag, name=None, notes=None):
release_id = self…
How to Calculate VPC Subnet CIDR Details in Python
Compute network address, broadcast address, address count, prefix length, and netmask for any IPv4 CIDR using the Python standard library's ipaddress module.
import ipaddress
def subnet_details(cidr: str) -> dict:
network = ipaddress.ip_network(cidr, strict=False)
return {
"network_address": str(network.network_address),
"broadcast_address": str(network.broadcast_address),
"num_addresses": network.num_addresses,
"prefix_length": ne…
How to Evaluate Mock NACL Rules in Python
Simulate numbered AWS Network ACL rule evaluation with HMAC integrity checks on request payloads.
import base64
import json
import hmac
import hashlib
def evaluate_mock_rule(rule_number, request_data, secret):
"""
Simulates evaluating an NACL-like numbered rule by:
1. Checking if the rule number exists in the mock policy.
2. Computing an HMAC over the request payload for integrity.
"""
# M…
How to Mock Twine Upload to TestPyPI in Python
Simulate a twine upload to TestPyPI with a dry-run mock function that validates distribution files and prints the intended upload action without any network call.
import subprocess
import sys
# Mock twine upload to TestPyPI using subprocess dry-run
def mock_twine_upload(dist_file: str, repo_url: str = "https://test.pypi.org/legacy/") -> None:
"""Simulate twine upload by checking dist file and printing intended action."""
if not dist_file.endswith((".whl", ".tar.gz")):
…
How to Mock requests.get in Python
Mock requests.get with unittest.mock to test code that makes HTTP calls without hitting the network.
import requests
from unittest.mock import Mock, patch
def fetch_user_data(user_id):
response = requests.get(f"https://api.example.com/users/{user_id}")
return response.json()
def process_user(user_id):
mock_response = Mock()
mock_response.json.return_value = {"id": user_id, "name": "Alice", "age": 30…
How to Inject Random Latency for Chaos Testing in Python
Mock unreliable services by wrapping functions with a decorator that adds random network-like delays before execution.
import random
import time
from functools import wraps
def inject_latency(func):
@wraps(func)
def wrapper(*args, **kwargs):
latency = random.uniform(0.1, 0.5)
print(f"Injecting {latency:.3f}s latency...")
time.sleep(latency)
return func(*args, **kwargs)
return wrapper
@inje…
How to Mock a Timeout per HTTP Request in Python
Simulate a per-request HTTP timeout using unittest.mock to test timeout handling without network access.
import time
from unittest.mock import Mock, patch
# Simulate an HTTP client that might time out
def fetch_data(url, timeout=5):
time.sleep(0.5) # Simulate network delay
return f"Response from {url}"
# Mock to test timeout behavior without real network
def test_timeout():
mock_response = Mock(side_effect…
How to Check an External Gateway vs Use an Internal Mock in Python
This code checks whether an external network gateway is reachable using ping, then falls back to a deterministic internal mock for testing environments.
import subprocess
import sys
def check_external_gateway():
"""True if we can reach an external network target."""
try:
subprocess.run(
["ping", "-c", "1", "-W", "2", "8.8.8.8"],
capture_output=True,
timeout=3,
check=True,
)
return True
…
How to Mock a Socket Stream in Python
Simulate a streaming socket source with a generator to test stream-read and buffering logic without a real network.
import socket
import threading
import time
def mock_socket_stream(data_chunks, delay=0.1):
"""Generator that simulates a streaming socket source."""
for chunk in data_chunks:
time.sleep(delay)
yield chunk
def read_stream_socket(stream_gen):
"""Reads from mock stream and prints received ch…
How to Build a Simple Binary Protocol Parser Mock in Python
Defines a mock binary protocol with field definitions, encoding, and decoding to simulate network packet parsing for A/B testing and experiment setup.
class SimpleProtocol:
def __init__(self, name, version):
self.name = name
self.version = version
self.fields = []
def add_field(self, field_name, field_size):
self.fields.append((field_name, field_size))
def parse(self, data):
if len(data) != sum(size for _, size i…
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.