Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
Redact secrets from log message formatter in Python
Build a custom logging.Formatter that masks passwords, API keys, and credit card numbers in log output.
import re
import logging
class RedactingFormatter(logging.Formatter):
"""Formatter that masks sensitive data in log messages."""
SENSITIVE_PATTERNS = [
(re.compile(r'password[=:]\s*\S+', re.IGNORECASE), 'password=[REDACTED]'),
(re.compile(r'api[_-]?key[=:]\s*\S+', re.IGNORECASE), 'api_key…
How to Detect Hardcoded Secrets in Python Source Code
A Python utility that scans source code for common hardcoded secrets like API keys, passwords, tokens, and AWS credentials using regex patterns.
import re
def detect_secrets(text):
"""Detect potential hardcoded secrets in source code."""
patterns = {
'api_key': r'(?i)(api[_-]?key|apikey)\s*[=:]\s*["\']([^"\']+)["\']',
'password': r'(?i)(password|passwd)\s*[=:]\s*["\']([^"\']+)["\']',
'token': r'(?i)(\b(token|secret)\b)\s*[=:]\s…
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": …
Python Script to Rotate a Leaked API Key
A checklist-driven Python script that scans a codebase for a leaked API key, replaces it with a new one, and prints a step-by-step rotation checklist.
#!/usr/bin/env python3
"""Checklist for rotating a leaked API key across a codebase."""
import re
from pathlib import Path
CHECKLIST = [
"Identify all files containing the leaked key",
"Generate a new key with sufficient entropy",
"Update the secret storage/CI environment variables",
"Replace the ol…
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…
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 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…
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.
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…
How to Implement a Vault Dynamic Database Credentials Mock in Python
A Python dataclass-based mock of HashiCorp Vault that issues short-lived database credentials, tracks leases, and revokes them, demonstrating dynamic secrets rotation.
import time
import json
from dataclasses import dataclass, field
from typing import Dict
@dataclass
class DynamicCredential:
username: str
password: str
lease_duration: int
created_at: float = field(default_factory=time.time)
def is_valid(self) -> bool:
return time.time() - self.created_…
How to Mock Environment Variables in Python for 12-Factor Config
Read 12-factor config from env vars and test/mock them with unittest.mock.patch.dict without touching the real environment.
import os
import json
from unittest.mock import patch
def load_config(env_prefix="APP"):
"""Read 12-factor style config from env vars"""
required = ["DATABASE_URL", "API_KEY"]
optional = {"PORT": "8080", "DEBUG": "false"}
config = {}
for key in required:
full_key = f"{env_prefix}_{key…
How to redact secrets from log messages in Python
This code defines a logging.Filter subclass that automatically redacts sensitive keys like password, token, and API key from any dict logged.
import logging
from dataclasses import dataclass
@dataclass
class ApiResponse:
status: int
body: dict
class SecretRedactor(logging.Filter):
SENSITIVE_KEYS = {"password", "token", "secret", "api_key"}
def filter(self, record: logging.LogRecord) -> bool:
if isinstance(record.msg, dict):
…
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.