Reference library

Python Code Samples

Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.

25 matches
Files & data easy

Automatically Detect Corrupted Files Using SHA-256 Checksums in Python

Compute SHA-256 checksums of files and compare them to detect corruption in Python.

checksum file-integrity hashlib
Python
import hashlib
import os

def compute_sha256(filepath: str) -> str:
    """Compute SHA-256 checksum of a file."""
    sha256 = hashlib.sha256()
    with open(filepath, 'rb') as f:
        for chunk in iter(lambda: f.read(4096), b''):
            sha256.update(chunk)
    return sha256.hexdigest()

def validate_file_int…
57 1 Open
Files & data medium

Chunk Large File Upload Simulation by Blocks in Python

A Python script reads a large binary file in fixed-size chunks and simulates a block-by-block upload with per-chunk SHA256 hashing.

file i/o chunking hashing
Python
import os
import hashlib
from pathlib import Path


def read_file_in_chunks(file_path, chunk_size=8196):
    """Yield chunks of a file as bytes."""
    with open(file_path, 'rb') as f:
        while chunk := f.read(chunk_size):
            yield chunk


def simulate_chunked_upload(file_path, chunk_size=8196):
    """S…
15 0 Open
Files & data medium

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.

file-versioning files backup
Python
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.…
52 0 Open
Files & data medium

Find Duplicate Web Pages by Content Similarity in Python

Compute SHA-256 hashes of file contents to detect and report duplicate HTML pages or any files in a directory.

duplicate-detection hashing sha256
Python
import hashlib
import os
from collections import defaultdict

def get_file_hash(filepath):
    """Compute SHA-256 hash of file contents."""
    sha256 = hashlib.sha256()
    with open(filepath, 'rb') as f:
        for chunk in iter(lambda: f.read(4096), b''):
            sha256.update(chunk)
    return sha256.hexdiges…
46 0 Open
Files & data medium

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.

hashlib sha256 file-hashing
Python
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…
13 0 Open
Files & data easy

How to Compute File SHA256 Hash with hashlib in Python

Compute the SHA256 hash of a file by reading it in chunks with hashlib and Path.open.

hashlib sha256 file-hash
Python
import hashlib
from pathlib import Path

def sha256_file(file_path: Path) -> str:
    sha256_hash = hashlib.sha256()
    with file_path.open("rb") as f:
        for chunk in iter(lambda: f.read(4096), b""):
            sha256_hash.update(chunk)
    return sha256_hash.hexdigest()

if __name__ == "__main__":
    demo_fi…
16 0 Open
AI & LLM integration patterns easy

How to hash a prompt with SHA-256 in Python

Create a SHA-256 hex fingerprint of a prompt string, with a short-prefix variant for quick references.

hashlib sha256 fingerprint
Python
import hashlib

def prompt_hash_fingerprint(prompt: str) -> str:
    """Return the full SHA-256 hex digest of the prompt."""
    return hashlib.sha256(prompt.encode("utf-8")).hexdigest()

def short_fingerprint(prompt: str, length: int = 12) -> str:
    """Return a short prefix of the SHA-256 digest for quick reference…
13 0 Open
Automation & scripting medium

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.

sha256 backup integrity
Python
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…
50 0 Open
Automation & scripting medium

Find and Delete Duplicate Files Using Hashing in Python

Walk a directory tree, compute SHA256 hashes for every file, and delete duplicates that share the same hash.

deduplication files hashing
Python
import hashlib
import os
from pathlib import Path

def file_hash(path, block_size=65536):
    """Return SHA256 hash of file content."""
    hasher = hashlib.sha256()
    with open(path, 'rb') as f:
        while chunk := f.read(block_size):
            hasher.update(chunk)
    return hasher.hexdigest()

def find_and_d…
51 0 Open
Automation & scripting easy

How to Hash Duplicate Photos and Delete Copies in Python

This script hashes image files in a directory using SHA-256 and deletes duplicate copies while keeping the first occurrence, ideal for cleaning up photo libraries.

hashlib deduplication file-automation
Python
from pathlib import Path
import hashlib

def file_hash(path, chunk_size=8192):
    hasher = hashlib.sha256()
    with open(path, "rb") as f:
        for chunk in iter(lambda: f.read(chunk_size), b""):
            hasher.update(chunk)
    return hasher.hexdigest()

def delete_duplicate_photos(directory):
    directory …
14 0 Open
Automation & scripting easy

How to Scan Files Against a Malware Hash List in Python

Compare a file's SHA-256 hash against a known malware hash set and report whether it's clean or infected.

hashlib file-scanning security
Python
import hashlib
from pathlib import Path

# Mock file content (in real usage, read from disk)
MOCK_FILE_CONTENT = b"print('hello world')"

KNOWN_MALWARE_HASHES = {
    "8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92",
    "5e884898da28047151d0e56f8dc6292773603d0d6aabbdd62a11ef721d1542d8",
}

def sha25…
14 0 Open
Data pipelines & processing easy

Generate a Deterministic Hash for Deduplication in Python

Create a stable SHA-256 fingerprint from nested data and file contents to deduplicate records in a data pipeline.

hashing deduplication sha256
Python
import hashlib
import json
from pathlib import Path

def natural_key_hash(data, salt=""):
    """
    Generate a deterministic fingerprint from raw data (dict/list/str).
    Uses JSON canonical-ish serialization with sorted keys and SHA-256.
    """
    canonical = json.dumps(data, sort_keys=True, separators=(",", ":"…
14 0 Open
Data pipelines & processing easy

How to Hash Email Addresses in a PII Masking Pipeline in Python

Replaces every email address in a text string with its SHA-256 hash to protect personally identifiable information (PII).

pii hashing sha256
Python
import hashlib
import re

def hash_email(email: str) -> str:
    """Mask an email address by hashing it with SHA-256."""
    normalized = email.strip().lower()
    return hashlib.sha256(normalized.encode("utf-8")).hexdigest()

def mask_pii_emails(text: str) -> str:
    """Replace all email addresses in text with their…
14 0 Open
Git + Python easy

Verify Git tag signatures with HMAC in Python

Create and verify deterministic HMAC-SHA256 signatures for git tags using the Python standard library.

hmac git security
Python
import hashlib
import hmac


def sign_tag(tag: str, secret_key: str) -> str:
    """Create a deterministic HMAC signature for a tag."""
    message = tag.encode("utf-8")
    key = secret_key.encode("utf-8")
    return hmac.new(key, message, hashlib.sha256).hexdigest()


def verify_signed_tag(tag: str, signature: str, …
14 0 Open
Cloud + Python medium

Generate a Mock Presigned URL in Python with HMAC

Build a mock AWS S3 presigned URL using an HMAC-SHA256 signature, mimicking the core SigV4 pattern without cloud SDK dependencies.

aws s3 presigned-url
Python
import hashlib
import hmac
import time
import base64

def generate_presigned_url_mock(secret_key, bucket, object_key, expires_in=3600):
    # Build the canonical request string (simplified AWS SigV4 style)
    timestamp = str(int(time.time()))
    expiry = str(int(time.time()) + expires_in)
    payload = f"GET\n/{buck…
13 0 Open
API design & gRPC medium

Verify Webhook HMAC Signatures in Python

Create and verify HMAC-SHA256 signatures for webhook payloads using Python's hmac module, protecting against tampering.

webhooks hmac security
Python
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…
12 0 Open
Caching & Redis easy

How to create a stable cache key from function arguments in Python

Generate a stable SHA-256 cache key from normalized function arguments, with keyword order normalized and tests using mocks.

caching hash key-normalization
Python
import hashlib
import json
from unittest.mock import Mock


def make_cache_key(*args, **kwargs):
    """Normalize args/kwargs into a stable hash key for caching."""
    normalized = {
        "args": [repr(arg) for arg in args],
        "kwargs": {key: repr(value) for key, value in sorted(kwargs.items())}
    }
    pa…
13 0 Open
Microservices patterns easy

How to Deduplicate Events in Python with SHA256 Hashing

Build an event deduplicator that identifies duplicate inbox messages using SHA256 hashes and tracks duplicate counts per event type.

deduplication event-processing hashing
Python
```python
import hashlib
import json
from collections import defaultdict


class EventDeduplicator:
    def __init__(self):
        self.seen_hashes = set()
        self.duplicate_counts = defaultdict(int)

    def process_event(self, event):
        event_key = f"{event['event_id']}:{event['timestamp']}"
        even…
12 0 Open
Auth & security at scale medium

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.

hmac sha256 authentication
Python
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…
14 0 Open
Auth & security at scale medium

How to Encode and Decode JWT with HS256 in Python

Implement JWT encoding and decoding using HMAC-SHA256 (HS256) with Python's standard library, including signature verification.

jwt hmac authentication
Python
import base64
import hashlib
import hmac
import json


def base64url_encode(data: bytes) -> bytes:
    return base64.urlsafe_b64encode(data).rstrip(b"=")


def base64url_decode(data: str) -> bytes:
    padding = "=" * (-len(data) % 4)
    return base64.urlsafe_b64decode(data + padding)


def encode_jwt(payload: dict, …
16 0 Open
Auth & security at scale easy

How to Generate and Verify HMAC Signatures in Python

Create and validate HMAC-SHA256 signatures with a shared secret key using Python's hmac and hashlib modules.

hmac security cryptography
Python
import hashlib
import hmac

SECRET_KEY = b"pepper-secret-2024"

def generate_hmac(message: str) -> str:
    return hmac.new(SECRET_KEY, message.encode("utf-8"), hashlib.sha256).hexdigest()

def verify_hmac(message: str, received_hmac: str) -> bool:
    expected = generate_hmac(message)
    return hmac.compare_digest(e…
15 0 Open
Auth & security at scale easy

How to Hash and Verify Passwords in Python

Hash passwords securely with PBKDF2-SHA256 and verify them using a constant-time comparison.

password-hashing security pbkdf2
Python
import hashlib
import hmac
import secrets
from typing import Tuple


def hash_password(password: str, salt: str = None) -> Tuple[str, str]:
    """Hash a password with a random salt using PBKDF2-SHA256."""
    salt = salt or secrets.token_hex(16)
    hashed = hashlib.pbkdf2_hmac(
        "sha256", password.encode("utf…
14 0 Open
Auth & security at scale medium

How to Implement a CSRF Token Double Submit Mock in Python

A mock CSRF protection class that generates and validates double-submit tokens using HMAC-SHA256 with a secret key.

csrf security hmac
Python
import hmac
import hashlib
import secrets


class CSRFProtection:
    def __init__(self, secret_key: str):
        self.secret_key = secret_key.encode("utf-8")

    def generate_token(self) -> str:
        random_value = secrets.token_hex(16)
        signature = hmac.new(
            self.secret_key, random_value.enco…
13 0 Open
Auth & security at scale medium

How to mock Argon2 password hashing in Python

This code demonstrates a mock Argon2 password hasher using HMAC-SHA256 iterations, providing hash and verify methods that mimic Argon2's salted, iterated derivation.

password-hashing security argon2
Python
import hashlib
import hmac
import os


class Argon2Mock:
    def __init__(self, salt_size=16, hash_len=32):
        self.salt_size = salt_size
        self.hash_len = hash_len
        
    def hash(self, password: str, salt: bytes = None) -> str:
        if salt is None:
            salt = os.urandom(self.salt_size)
 …
14 0 Open

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

  1. Pick a topic section — strings, lists, files, functions, and more
  2. Open a sample, read How it works, and copy the code block
  3. 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.