Python Code
Samples
Medium snippets you can copy, study, and run in the browser editor.
Build a Secure Local Password Vault with Encrypted Storage in Python
A Python class that stores and retrieves passwords in an encrypted JSON file using Fernet symmetric encryption from the cryptography library.
import json
import os
import base64
import hashlib
from cryptography.fernet import Fernet
from getpass import getpass
class PasswordVault:
def __init__(self, vault_file="vault.json", key_file="vault.key"):
self.vault_file = vault_file
self.key_file = key_file
self.key = self._load_or_creat…
Create a Local File Versioning System Using Pure Python
Track file changes locally by copying versions with SHA-256 hashes and JSON metadata using only the Python standard library.
import os
import shutil
import hashlib
import json
import time
from pathlib import Path
class LocalFileVersioning:
def __init__(self, target_dir="versioned_files", versions_dir="versions"):
self.target_dir = Path(target_dir)
self.versions_dir = Path(versions_dir)
self.metadata_file = self.…
How to stream parse JSON arrays in Python
This code demonstrates two generators: one that streams a JSON array as individual chunks, and another that incrementally parses those chunks into Python objects using json.JSONDecoder.
import json
def json_array_stream(items):
"""Generator that yields JSON-encoded values one at a time."""
yield "["
for i, item in enumerate(items):
if i > 0:
yield ","
yield json.dumps(item)
yield "]"
def parse_json_stream(stream):
"""Consumes a stream of JSON fragme…
How to Build a Data Helper for LLM Prompts in Python
A beginner-friendly helper class that flattens nested dictionaries, formats prompt templates, and safely parses JSON for AI/LLM pipelines.
import json
from typing import Any, Dict, List, Optional
class DataHelper:
"""Simple helper class for working with data in AI/LLM pipelines."""
def __init__(self, data: Optional[Dict[str, Any]] = None) -> None:
self.data = data or {}
def flatten(self, prefix: str = "") -> Dict[str, Any]…
How to Repair Malformed JSON Braces Heuristically in Python
Heuristically fix malformed JSON by balancing braces and quotes, using a stack-based approach to add missing closing characters.
import json
import re
def repair_json(text: str) -> str:
"""Heuristically repair malformed JSON by balancing braces and quotes."""
# Trim whitespace and handle leading/trailing garbage
text = text.strip()
# Remove common non-JSON decorations
text = re.sub(r'^(
Build a Python Utility That Verifies Backup Integrity Automatically
Automatically compute and verify SHA-256 checksums of backup files using a JSON manifest to detect missing or corrupted data.
import hashlib
import os
import json
def compute_checksum(filepath, algorithm='sha256'):
"""Compute checksum for the given file."""
hash_func = hashlib.new(algorithm)
with open(filepath, 'rb') as f:
for chunk in iter(lambda: f.read(4096), b''):
hash_func.update(chunk)
return hash_f…
How to Compare Two GitHub Repositories and Highlight Differences in Python
Fetch metadata from two GitHub repositories using the GitHub API and compare key attributes like stars, forks, license, and language, printing any differences.
import requests
import json
from pathlib import Path
def fetch_repo_data(owner, repo_name):
"""Fetch repository metadata from GitHub API."""
url = f"https://api.github.com/repos/{owner}/{repo_name}"
response = requests.get(url)
response.raise_for_status()
return response.json()
def compare_repos(…
How to Monitor Laptop Battery Health Over Time in Python
Log battery percentage, power status, and remaining time every N seconds to a JSON file using psutil for ongoing health monitoring.
import time
import json
from pathlib import Path
from datetime import datetime
try:
import psutil
except ImportError:
print("psutil required: pip install psutil")
exit(1)
LOG_FILE = Path("battery_health_log.json")
def monitor_battery(log_interval=60, duration=300):
"""Log battery percentage and rema…
How to Track GitHub Stars, Forks, and Watchers in Python
Automatically fetch and track stars, forks, and watchers for multiple GitHub repositories, saving snapshots locally as JSON files for historical analysis.
import os
import time
import json
import requests
from pathlib import Path
from datetime import datetime
REPOS = [
"psf/requests",
"python/cpython",
"pallets/flask",
]
DATA_DIR = Path("github_metrics")
def fetch_repo_stats(repo):
url = f"https://api.github.com/repos/{repo}"
resp = requests.get(ur…
Track File Changes with Version History in Python
A Python utility that monitors a file for changes, creating versioned backups with SHA-256 hashing to detect modifications and store a local JSON history.
import hashlib, json, os, shutil, time
from pathlib import Path
class FileTracker:
def __init__(self, history_file="file_history.json"):
self.history_file = Path(history_file)
self.history = self._load_history()
def _load_history(self):
if self.history_file.exists():
retur…
Extract Schema.org Structured Data from Any Website in Python
A Python tool that fetches a webpage and extracts all JSON-LD structured data (Schema.org) embedded in <script> tags with type="application/ld+json".
import requests
from bs4 import BeautifulSoup
import json
def extract_schema_org(url):
"""Extract structured data (Schema.org) from a website."""
try:
response = requests.get(url, timeout=10)
response.raise_for_status()
except requests.exceptions.RequestException as e:
return {"err…
How to Stream a Large JSONL File Line by Line in Python
Process a large JSON-lines file incrementally using streaming techniques to avoid loading the entire file into memory.
import json
def process_large_file(filepath, chunk_size=8192):
"""
Stream a large JSON-lines file line by line, processing each record
without loading the entire file into memory.
"""
total_count = 0
total_sum = 0
with open(filepath, 'r') as f:
while True:
chunk = …
Mocking loguru for Structured Logging in Python
Simulate loguru's structured logging with a custom mock that captures JSON-formatted log entries with bound context.
import json
import sys
from io import StringIO
from unittest.mock import patch
def mock_loguru():
# Simulate a structured logger with context binding
class StructuredLogger:
def __init__(self):
self.context = {}
def bind(self, **kwargs):
logger = StructuredLogger()
…
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 Snapshot Test JSON with Mock in Python
Use pytest-snapshot to capture the exact output of a JSON-loading function, with and without mocking json.loads, so future changes are automatically detected.
import json
from unittest.mock import Mock, patch
import pytest
def load_config(data):
config = json.loads(data)
return {"host": config["host"], "port": config["port"]}
def test_load_config_snapshot(snapshot):
mock_data = json.dumps({"host": "localhost", "port": 8080, "extra": "ignored"})
result = …
Build a BFF (Backend for Frontend) Mock Aggregator in Python
A minimal HTTP server implementing the BFF pattern that aggregates user data and orders from two mock backends into a single JSON response.
import json
from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import urlparse
class MockBackendA:
def get_user(self, user_id):
return {"id": user_id, "name": "Alice", "service": "backend-a"}
class MockBackendB:
def get_orders(self, user_id):
return [
{…
Singleton Config Loader in Python with Caution
Implements a singleton config loader in Python that reads JSON config files, but demonstrates the hidden gotcha of shared state across instances.
import json
from pathlib import Path
class ConfigLoader:
_instance = None
def __new__(cls, *args, **kwargs):
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance
def __init__(self, config_file="config.json"):
if not hasattr(self, "loaded…
Build a Bulk Array POST Mock Server in Python
Creates an HTTP mock server that accepts POST requests with a JSON array and returns incremental IDs for each item.
import json
from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import urlparse
class MockHandler(BaseHTTPRequestHandler):
def do_POST(self):
if urlparse(self.path).path != "/bulk":
self.send_response(404)
self.end_headers()
return
cont…
How to Build a Batch Operations Multi-Status 207 Mock Server in Python
Build a mock HTTP server that accepts a batch of operations and returns HTTP 207 Multi-Status with per-operation status codes in JSON.
from http.server import BaseHTTPRequestHandler, HTTPServer
import json
class BatchHandler(BaseHTTPRequestHandler):
def do_POST(self):
if self.path != "/batch":
self.send_response(404)
self.end_headers()
return
content_length = int(self.headers.get("Content-Leng…
How to Build a Hypermedia Collection Resource in Python
Creates a paginated hypermedia collection resource with HATEOAS links and embedded items.
import json
import math
class HypermediaCollection:
"""A mock hypermedia collection resource."""
def __init__(self, items, base_url="/api/items"):
self.items = items
self.base_url = base_url
def to_dict(self, page=1, per_page=3):
total = len(self.items)
pages = math.ceil…
How to Build a Mock REST GET Endpoint Handler in Python
Create a lightweight mock REST GET server in Python using the standard library, with a dict-based route registry that maps paths to handler functions and returns JSON responses with proper HTTP status codes.
from http.server import BaseHTTPRequestHandler, HTTPServer
import json
# Mock API handler registry
def handle_users():
return {"status": "ok", "data": [{"id": 1, "name": "Alice"}, {"id": 2, "name": "Bob"}]}
def handle_products():
return {"status": "ok", "data": [{"id": 101, "name": "Laptop", "price": 999.99}…
How to Implement Content Negotiation with JSON and XML in Python
Build an HTTP server that returns JSON or XML responses based on the client's Accept header, with a 406 response for unsupported formats.
import json
import xml.etree.ElementTree as ET
from http.server import BaseHTTPRequestHandler, HTTPServer
class RequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
data = {"message": "Hello, world!"}
accept_header = self.headers.get("Accept", "")
if "application/json" in accept_hea…
How to Validate Request Body JSON Against a Schema in Python
Build a lightweight schema validator to check required fields, types, string lengths, allowed values, and nested objects in a JSON request body.
import json
def validate_against_schema(data, schema, path=""):
errors = []
if not isinstance(data, dict):
errors.append(f"{path}: expected object, got {type(data).__name__}")
return errors
for field, rules in schema.items():
field_path = f"{path}.{field}" if path else field
…
How to Implement an Outbox Table Poll Publisher in Python
This code simulates an outbox pattern with a class that polls for pending records and publishes them as JSON messages, removing only those that are due.
import time
import json
from dataclasses import dataclass, asdict
from datetime import datetime, timedelta
@dataclass
class OutboxRecord:
id: int
topic: str
payload: dict
created_at: datetime
class OutboxPollPublisher:
def __init__(self, poll_interval_seconds=1):
self.poll_interval = poll…
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.