Python Code
Samples
Medium snippets you can copy, study, and run in the browser editor.
How to Compare Two Files by Content Hash Equality in Python
Compares two files by hashing their contents with SHA-256, skipping the hash if file sizes differ, and returns whether they are identical.
import hashlib
from pathlib import Path
def file_hash(path: Path, chunk_size: int = 8192) -> str:
sha256 = hashlib.sha256()
with path.open("rb") as f:
for chunk in iter(lambda: f.read(chunk_size), b""):
sha256.update(chunk)
return sha256.hexdigest()
def files_are_identical(file_a: Pat…
How to Find Duplicate Files by Size and Hash in Python
Recursively scan a directory, group files by size, then hash candidates to identify exact duplicate files.
import hashlib
from pathlib import Path
def hash_file(path, chunk_size=8192):
hasher = hashlib.md5()
with open(path, 'rb') as f:
while chunk := f.read(chunk_size):
hasher.update(chunk)
return hasher.hexdigest()
def find_duplicates(directory):
size_map = {}
for path in Path(dir…
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 Build an Idempotency-Key POST Handler in Python
Python HTTP server mock that accepts POST requests and deduplicates them using an Idempotency-Key header, returning the same response for repeated calls.
import hashlib
import json
from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import urlparse
class MockAPI(BaseHTTPRequestHandler):
responses = {}
def do_POST(self):
length = int(self.headers.get("Content-Length", 0))
body = self.rfile.read(length).decode("utf-8")
…
Verify Webhook HMAC Signatures in Python
Create and verify HMAC-SHA256 signatures for webhook payloads using Python's hmac module, protecting against tampering.
import hashlib
import hmac
import json
SECRET = b"super-secret-webhook-key"
def create_signature(payload: bytes) -> str:
return hmac.new(SECRET, payload, hashlib.sha256).hexdigest()
def verify_signature(payload: bytes, signature: str) -> bool:
expected = create_signature(payload)
return hmac.compare_dig…
How to Build a Bloom Filter to Reduce Cache Misses in Python
Implement a probabilistic Bloom filter in Python that lets a cache quickly determine which keys are definitely not present, reducing expensive source lookups on cache misses.
import hashlib
import random
class BloomFilter:
def __init__(self, size=100, num_hashes=3):
self.size = size
self.num_hashes = num_hashes
self.bit_array = [0] * size
def _hashes(self, item):
result = []
for i in range(self.num_hashes):
hash_value = int(hash…
How to Create and Verify HMAC SHA256 API Signatures in Python
Generate and verify HMAC-SHA256 signatures for API requests using Python's hmac, hashlib, and base64 modules.
import hmac
import hashlib
import base64
import json
from datetime import datetime, timezone
def create_api_signature(secret_key: str, method: str, path: str, timestamp: str, body: dict = None) -> str:
"""Create HMAC-SHA256 signature for API request."""
payload = {
"method": method.upper(),
"p…
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.