Reference library

Python Code Samples

Easy snippets you can copy, study, and run in the browser editor.

12 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 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 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
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 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

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.