Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
Find Unused Python Packages Automatically
Scan a Python project's source files for imports and list installed packages not imported anywhere.
import pkg_resources
import ast
import os
import sys
from pathlib import Path
def find_imports_in_project(project_dir="."):
imports = set()
for py_file in Path(project_dir).rglob("*.py"):
try:
with open(py_file, "r") as f:
tree = ast.parse(f.read())
for node in …
Generate Beautiful Project Documentation from Python Source Code Automatically
Automatically generate a markdown summary of function docstrings from any Python source file using the AST module.
import ast
import inspect
from pathlib import Path
def extract_docstrings_from_file(filepath):
"""Parse a Python file and collect function docstrings."""
source = Path(filepath).read_text()
tree = ast.parse(source)
docs = []
for node in ast.walk(tree):
if isinstance(node, (ast.FunctionDef…
How to Build a Python Tool That Finds Trending Open Source Projects Daily
A Python script that queries the GitHub Search API to fetch the top 5 trending repositories created in the last day, sorted by stars, with optional language filtering.
import requests
import json
import datetime
def fetch_trending_projects(language: str = "", since: str = "daily"):
url = "https://api.github.com/search/repositories"
date_limit = (datetime.date.today() - datetime.timedelta(days=1)).isoformat()
query = f"created:>{date_limit} language:{language}" if langua…
How to Generate a Dependency Graph for Python Projects
This script walks through a Python project directory, parses each .py file's imports, and prints a dependency graph showing which modules depend on which other modules.
import os
import ast
from pathlib import Path
from collections import defaultdict
def get_imports(filepath):
with open(filepath) as f:
try:
tree = ast.parse(f.read())
except SyntaxError:
return []
imports = []
for node in ast.walk(tree):
if isinstance(node, …
How to Monitor Website Content Changes in Python
This script fetches a webpage's content, computes its SHA-256 hash, and compares it with the last stored hash to detect and alert on changes.
import time
import hashlib
import requests
from pathlib import Path
def fetch_content_hash(url: str) -> str:
response = requests.get(url, timeout=10)
response.raise_for_status()
return hashlib.sha256(response.text.encode()).hexdigest()
def monitor_website(url: str, check_interval: int = 60):
hash_fil…
How to Tail and Colorize Error Lines in Python
Reads the last N lines of a log file and prints error lines in red using ANSI color codes.
import sys
import time
from pathlib import Path
def tail_colorize(filename: str, lines: int = 20) -> None:
"""Read last N lines of a file, printing errors in red."""
path = Path(filename)
if not path.exists():
print(f"File '{filename}' not found.", file=sys.stderr)
return
# Read last …
How to check Python files for common coding mistakes
Walks a directory tree parsing each .py file with ast, reporting empty functions, bare try blocks, too many parameters, and empty classes.
import ast
import os
import sys
def check_file(filepath):
try:
with open(filepath) as f:
code = f.read()
tree = ast.parse(code, filename=filepath)
except SyntaxError as e:
print(f"{filepath}: SyntaxError: {e.msg}")
return
issues = []
for node in ast.wal…
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…
How to Deduplicate Events with At-Least-Once Delivery in Python
Implements an exactly-once processing pattern for at-least-once event delivery by tracking seen event IDs in a set, skipping duplicates.
seen_ids = set()
def process_event(event_id: str, payload: dict) -> dict:
"""Process an event exactly once, ignoring duplicates."""
if event_id in seen_ids:
return {"status": "duplicate", "event_id": event_id}
seen_ids.add(event_id)
return {"status": "processed", "event_id": event_id, **payloa…
How to Track Checkpoint Offset After Batch Commit in Python
A batch processor that tracks the last successfully committed offset after processing records in batches, advancing the checkpoint only when each batch commits successfully.
import json
from typing import Any
class BatchProcessor:
"""Tracks checkpoint offset after committing batches."""
def __init__(self, batch_size: int = 3):
self.batch_size = batch_size
self.offset = 0 # last successfully committed offset (exclusive)
self.total_committed = 0
def …
Normalize Timestamps to UTC DateTime in Python
Convert timestamps in multiple formats to UTC-aware datetime objects using datetime.strptime and astimezone.
from datetime import datetime, timezone
raw_timestamps = [
"2024-01-15 14:30:00+02:00",
"17/05/2024 09:15:00 -0500",
"2024-03-01T22:45:00Z",
"2024-06-20 08:00:00+09:30"
]
def parse_and_convert(ts: str) -> datetime:
normalized_ts = ts.strip().replace("Z", "+00:00")
formats = [
"%Y-%m-%…
Amend Last Commit Message in Python
This script uses subprocess to run `git commit --amend` and update the most recent commit's message in your repository.
import subprocess
import sys
def amend_last_commit_message(new_message: str) -> None:
"""Change the message of the most recent commit."""
result = subprocess.run(
["git", "commit", "--amend", "-m", new_message],
capture_output=True,
text=True,
check=False,
)
if result.…
How to List Changed Files in the Last Git Commit with Python
Runs `git diff --name-only HEAD~1 HEAD` via subprocess to list the names of files changed in the most recent commit.
import subprocess
def list_changed_files():
result = subprocess.run(
["git", "diff", "--name-only", "HEAD~1", "HEAD"],
capture_output=True,
text=True,
check=True
)
files = result.stdout.strip().splitlines()
return files
if __name__ == "__main__":
changed = list_cha…
How to Squash Commits Range into One in Python
A mock script that displays the last N git commits as a single squashed commit, showing original commit subjects.
import subprocess
import re
def squash_last_commits(count):
"""Mock squashing the last N commits into one by display."""
git_log = subprocess.run(
["git", "log", f"-{count}", "--pretty=format:%h %s"],
capture_output=True, text=True
)
if git_log.returncode != 0:
return "Git comm…
Merge branch no ff mock in Python
Simulate a Git non-fast-forward merge in Python, producing a synthetic merge commit log for branches with differing SHAs.
class MergeResult:
def __init__(self, base, branch):
self.base = base
self.branch = branch
self.commit_log = []
self.merged = False
def simulate_merge(self):
"""Simulate a 'no-ff' merge by creating a new commit that references both branches."""
if self.base == s…
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 Mock ELB Target Health Status in Python
Simulate AWS Elastic Load Balancer target health checks with a Python dict that mutates status and healthy host counts.
from random import randint
def elb_target_mock_status(target_id, healthy=True):
targets = {
1: {"Id": "i-001", "Status": "healthy", "Port": 80, "HealthyHostCount": 1},
2: {"Id": "i-002", "Status": "unhealthy", "Port": 80, "HealthyHostCount": 0},
3: {"Id": "i-003", "Status": "healthy", "Por…
Mock Google Pub/Sub publish and pull in Python
A lightweight in-memory mock of Google Pub/Sub with publisher/subscriber classes to test topic-based fan-out and message pulling without real infrastructure.
import json
import time
from collections import deque
from dataclasses import dataclass, field
from typing import Any, Callable
@dataclass
class Message:
data: str
attributes: dict[str, str] = field(default_factory=dict)
message_id: str | None = None
ack_id: str | None = None
class MockPublisher:
…
Mock Route53 change_resource_record_sets in Python
This code demonstrates how to mock AWS Route53 change_resource_record_sets API calls using the botocore Stubber, allowing you to test DNS update logic without touching real infrastructure.
import boto3
from botocore.exceptions import ClientError
def mock_change_resource_record_sets():
"""Demonstrates Route53 change_resource_record_sets with a mock client."""
# Create a mock Route53 client
route53 = boto3.client('route53', region_name='us-east-1',
aws_access_key_id…
How to Mock a Fast uv pip sync in Python
Simulate a fast uv pip sync by mocking file operations and subprocess calls to test dependency installation workflows.
import os
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path
def uv_pip_sync_fast_install_mock(requirements_text: str) -> dict:
"""Simulate a fast uv pip sync by mocking file operations and subprocess calls."""
mock_dir = Path(tempfile.mkdtemp(prefix="uv_mock_"))
req_lines…
pytest mark slow skip integration
Uses pytest markers to select fast tests, skip unfinished ones, and run integration checks with verbose output.
import pytest
def test_fast():
assert 1 + 1 == 2
@pytest.mark.slow
def test_slow():
import time
time.sleep(1)
assert 5 * 5 == 25
@pytest.mark.skip(reason="Not ready for production")
def test_skipped():
assert 2 + 2 == 5
@pytest.mark.integration
def test_integration():
database = {"users": […
How to Parse JSON Files in Parallel with Python ThreadPoolExecutor
Load and transform JSON records from multiple files concurrently using ThreadPoolExecutor for faster I/O-bound parsing.
import time
from concurrent.futures import ThreadPoolExecutor
import json
def load_json_file(path):
with open(path, 'r') as f:
return json.load(f)
def transform_record(record):
record['full_name'] = f"{record.pop('first_name', '')} {record.pop('last_name', '')}".strip()
record['score'] = int(reco…
How to Use uvloop Faster Event Loop
Install uvloop at startup to replace asyncio's default event loop with a faster libuv-based one, with a graceful fallback when it's unavailable.
import asyncio
try:
import uvloop
uvloop.install()
USING_UVLOOP = True
except ImportError:
USING_UVLOOP = False
async def fetch_data(index):
await asyncio.sleep(0.01)
return f"data-{index}"
async def main():
tasks = [fetch_data(i) for i in range(10)]
results = await asyncio.gather(*…
How to Write a Fast Smoke Test for a Critical Path in Python
A quick smoke test that validates the /health critical path executes fast enough, raising errors on wrong paths or slow responses.
import time
def smoke_test(path):
if path != "/health":
raise ValueError("Critical path expected /health")
start = time.perf_counter()
# Simulate the critical health check work
time.sleep(0.01)
elapsed = time.perf_counter() - start
if elapsed > 0.05:
raise RuntimeError("Health …
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.