Python Code
Samples
Easy snippets you can copy, study, and run in the browser editor.
Build a Command-Line Password Generator in Python
Generate cryptographically strong random passwords using Python's secrets module and print them for command-line use.
import secrets
import string
def generate_password(length=16):
"""Generate a cryptographically strong random password."""
alphabet = string.ascii_letters + string.digits + string.punctuation
password = ''.join(secrets.choice(alphabet) for _ in range(length))
return password
if __name__ == "__main__":…
Generate Strong Random Passwords with Custom Rules in Python
Build a configurable password generator using Python's secrets module that lets you toggle lowercase, uppercase, digits, and punctuation.
import secrets
import string
def generate_password(length=16, use_lower=True, use_upper=True, use_digits=True, use_punct=True):
pool = ''
if use_lower:
pool += string.ascii_lowercase
if use_upper:
pool += string.ascii_uppercase
if use_digits:
pool += string.digits
if use_pu…
Restrict Secrets File Permissions with the chmod Script in Python
This script restricts a secrets file to 0600 permissions, rotates it to a dated backup, and creates a fresh protected file for secure automation workflows.
import os
import sys
import stat
from pathlib import Path
def restrict_secrets_file(filepath: str) -> None:
"""Set restrictive permissions (0600) on a secrets file."""
path = Path(filepath).expanduser()
if not path.is_file():
raise FileNotFoundError(f"Secrets file not found: {path}")
…
How to Filter Git History to Remove Secret File Entries in Python
A pure-Python mock that filters a repository's history to drop any commit that touched a secret file, so you can plan a cleanup before rewriting Git history.
from pathlib import Path
import json
def filter_history(history, secret_path):
"""Remove entries that touch the secret file."""
return [entry for entry in history if secret_path not in entry["files"]]
if __name__ == "__main__":
repo_history = [
{"commit": "a1b2c3", "message": "Add app", "files": …
How to detect secrets in git history with Python
Scan a git history export file for common secret patterns using regex and Python.
import re
from pathlib import Path
def scan_history_for_secrets(history_file: str) -> list:
"""Scan a git history export for potential secrets using regex patterns."""
patterns = {
"AWS Access Key": r"AKIA[0-9A-Z]{16}",
"GitHub Token": r"gh[pousr]_[0-9A-Za-z]{36,255}",
"Private Key": …
How to Mock AWS Secrets Manager in Python
Create a lightweight mock of AWS Secrets Manager's get_secret_value API to test secret retrieval without cloud dependencies.
import json
from typing import Optional
class MockSecretsManager:
"""A simple mock of AWS Secrets Manager's get_secret_value API."""
def __init__(self):
self._secrets: dict[str, str] = {}
def create_secret(self, secret_id: str, secret_value: str) -> None:
"""Store a secret value under a…
Mock GCP Secret Manager access version in Python
A minimal mock of GCP Secret Manager that stores secret versions, retrieves payloads by version, and logs access timestamps.
import json
import time
from datetime import datetime, timezone
class MockSecretManager:
"""Minimal mock of GCP Secret Manager access/version behavior."""
def __init__(self):
self._secrets = {}
self._access_log = []
def create_secret(self, secret_id: str, payload: str) -> dict:
…
How to Validate a JWT Signature in Python with a Mock Secret
Validates a JWT's signature using a mock secret, decoding and handling expired or invalid tokens gracefully.
import jwt
import time
SECRET = "mock_secret_key_123"
def validate_token(token):
try:
payload = jwt.decode(token, SECRET, algorithms=["HS256"])
return f"Valid token. Payload: {payload}"
except jwt.ExpiredSignatureError:
return "Token expired"
except jwt.InvalidTokenError:
…
How to Redact Secrets from Log Messages in Python
Build a lightweight RedactingFormatter class that replaces sensitive tokens like passwords and API keys with [REDACTED] before log messages are printed.
class RedactingFormatter:
def __init__(self, secrets):
self.secrets = secrets
def redact(self, message):
for secret in self.secrets:
message = message.replace(secret, "[REDACTED]")
return message
def format(self, record):
message = record["message"]
ret…
Fetch Secrets from a Mock Secrets Manager in Python
Build a minimal in-memory secrets manager that stores and retrieves secret values, raising a KeyError for missing names.
import json
class SecretsManager:
"""Mock secrets manager that returns secrets from a local store."""
def __init__(self, store=None):
self.store = store or {
"api_key": "mock-api-key-123",
"db_password": "s3cret-p@ss",
"jwt_secret": "dev-only-secret"
}
…
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.
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…
How to Hash Passwords Securely in Python
Hash passwords with PBKDF2, random salts, and constant pepper, plus generate secure API keys using Python's stdlib.
import hashlib
import secrets
import time
import hmac
def hash_password(password: str, salt: str = None, pepper: str = "static-pepper") -> dict:
"""Hash a password with a random salt and constant pepper."""
if salt is None:
salt = secrets.token_hex(16)
salted = f"{pepper}{salt}{password}"
dig…
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.