Reference library

Python Code Samples

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

4 matches
Errors & debugging medium

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.

logging redaction security
Python
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…
14 0 Open
AI & LLM integration patterns easy

How to Redact Emails and Phones Before Sending to an LLM in Python

This code uses regular expressions to replace email addresses and US phone numbers with [EMAIL] and [PHONE] placeholders before any LLM processing.

pii redaction regular-expressions
Python
import re

def redact_pii(text: str) -> str:
    # Replace email addresses with [EMAIL]
    text = re.sub(r'[\w.+-]+@[\w-]+\.[\w.-]+', '[EMAIL]', text)
    # Replace phone numbers (US format) with [PHONE]
    text = re.sub(r'\(?\d{3}\)?[-.\s]?\d{3}[-.\s]?\d{4}', '[PHONE]', text)
    return text

if __name__ == "__main…
15 0 Open
Observability & SRE easy

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.

redaction logging secrets
Python
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…
12 0 Open
Auth & security at scale medium

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.

logging security redaction
Python
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):
    …
12 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.