Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
How to Build a Simple Decorator That Logs Function Calls in Python
This code shows how to create a reusable decorator that logs each function call, including arguments, return value, and execution time.
import functools
import time
def log_calls(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
print(f"Calling {func.__name__} with args={args}, kwargs={kwargs}")
start = time.time()
result = func(*args, **kwargs)
end = time.time()
print(f"{func.__name__} return…
How to Add a Correlation ID to Logging Records in Python
Attach a unique correlation ID to every log record using a custom logging.Filter, making distributed request tracking traceable.
import logging
import uuid
from dataclasses import dataclass, field
@dataclass
class CorrelationIdFilter(logging.Filter):
correlation_id: str = field(default_factory=lambda: str(uuid.uuid4()))
def filter(self, record: logging.LogRecord) -> bool:
record.correlation_id = self.correlation_id
re…
How to Configure Python Logging with File Rotation
A complete demo that sets up a logger with a rotating file handler, writes several log entries, and shows the contents of the current log file.
import logging
from logging.handlers import RotatingFileHandler
logger = logging.getLogger("rotating_logger")
logger.setLevel(logging.DEBUG)
file_handler = RotatingFileHandler(
"app.log",
maxBytes=100,
backupCount=3
)
file_handler.setFormatter(
logging.Formatter("%(asctime)s - %(levelname)s - %(messa…
How to Debug Print Behind a DEBUG Environment Flag in Python
Create a debug_print function that only outputs when the DEBUG environment variable is set to a truthy value like 1, true, yes, or on.
import os
def debug_print(*args, **kwargs):
"""Print only when DEBUG environment variable is set to a truthy value."""
if os.environ.get("DEBUG", "").lower() in ("1", "true", "yes", "on"):
print(*args, **kwargs)
if __name__ == "__main__":
# Example usage: run as `DEBUG=1 python script.py` to se…
How to Log Errors with Structured Fields in Python
Logs error details as structured dictionary fields using Python's logging module with extra parameters.
import logging
import sys
def log_structured_error(operation: str, user_id: int, status_code: int, error_msg: str):
"""Log an error with structured fields using a dictionary."""
logger = logging.getLogger("structured_logger")
logger.setLevel(logging.ERROR)
# Create console handler if not already …
How to Log Exceptions with traceback.format_exc in Python
Capture and log a full traceback string when an exception occurs using Python's traceback.format_exc() and logging module.
import traceback
import logging
def risky_operation(value):
return 10 / value
logging.basicConfig(level=logging.ERROR, format='%(asctime)s - %(levelname)s - %(message)s')
def main():
try:
result = risky_operation(0)
print(f"Result: {result}")
except ZeroDivisionError:
error_msg =…
How to Serialize an Exception to a JSON-Safe Dict in Python
Convert any Python exception into a JSON-safe dictionary with type, message, and the last few traceback lines for logging.
import json
import traceback
from typing import Any
def exception_to_dict(exc: Exception) -> dict[str, Any]:
"""Convert an exception into a JSON-safe dictionary."""
return {
"type": type(exc).__name__,
"message": str(exc),
"traceback": traceback.format_exc().strip().split("\n")[-3:],
…
How to attach a request ID to exception messages in Python
This code shows how to enrich exception messages with contextual request IDs using context variables, making error logs more traceable across concurrent requests.
import logging
from contextvars import ContextVar
request_id_var = ContextVar("request_id", default="unknown")
def add_request_id(exc: Exception) -> Exception:
exc.args = (f"request_id={request_id_var.get()} | {exc.args[0]}" if exc.args else f"request_id={request_id_var.get()}",) + exc.args[1:]
return exc
d…
Log to stderr with Python logging basicConfig
Configure Python's logging module to send all log messages to standard error (stderr) instead of the default stderr, with a readable timestamped format.
import logging
def main():
logging.basicConfig(
level=logging.DEBUG,
format="%(asctime)s — %(name)s — %(levelname)s — %(message)s",
stream=__import__("sys").stderr,
)
logger = logging.getLogger("example")
logger.debug("Debug message")
logger.info("Info message")
logger.…
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…
Append a Line to a Log File in Python
Append a line to a file using a context manager and Path.open().
from pathlib import Path
def append_to_log(filepath, message):
with Path(filepath).open("a") as log_file:
log_file.write(f"{message}\n")
if __name__ == "__main__":
log_path = "log.txt"
append_to_log(log_path, "First entry")
append_to_log(log_path, "Second entry")
# Verify contents
…
How to Implement the Decorator Pattern in Python to Add Behavior
This Python code demonstrates the decorator pattern by wrapping a function to add logging behavior without modifying the original function.
import functools
def logger(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
print(f"Calling {func.__name__} with {args} {kwargs}")
result = func(*args, **kwargs)
print(f"{func.__name__} returned {result}")
return result
return wrapper
@logger
def add(a, b):
…
How to Log Prompts and Completions as JSONL Audit Files in Python
Read a JSONL file of LLM prompt–completion pairs, compute totals and averages, then write an audit summary with timestamps.
import json
from pathlib import Path
from datetime import datetime
def audit_jsonl(filepath):
logs = []
with open(filepath, encoding="utf-8") as f:
for line in f:
line = line.strip()
if not line:
continue
entry = json.loads(line)
logs.ap…
How to Serialize Chat Messages to a JSON File in Python
Writes a list of chat message dicts to a JSON file with metadata like export time and message count.
import json
from pathlib import Path
from datetime import datetime
def serialize_messages(messages, output_path):
data = {
"exported_at": datetime.now().isoformat(),
"count": len(messages),
"messages": messages
}
Path(output_path).write_text(
json.dumps(data, indent=2, ensu…
How to Monitor Laptop Battery Health Over Time in Python
Log battery percentage, power status, and remaining time every N seconds to a JSON file using psutil for ongoing health monitoring.
import time
import json
from pathlib import Path
from datetime import datetime
try:
import psutil
except ImportError:
print("psutil required: pip install psutil")
exit(1)
LOG_FILE = Path("battery_health_log.json")
def monitor_battery(log_interval=60, duration=300):
"""Log battery percentage and rema…
How to Tail and Colorize Error Lines in Python
Reads the last N lines of a log file and prints error lines in red using ANSI color codes.
import sys
import time
from pathlib import Path
def tail_colorize(filename: str, lines: int = 20) -> None:
"""Read last N lines of a file, printing errors in red."""
path = Path(filename)
if not path.exists():
print(f"File '{filename}' not found.", file=sys.stderr)
return
# Read last …
Monitor Website Uptime with Python
Periodically check if a website is reachable and its HTTP status is 200, logging the status with timestamps.
import requests
import time
def check_website(url):
try:
response = requests.get(url, timeout=5)
if response.status_code == 200:
return True
else:
return False
except requests.ConnectionError:
return False
except requests.Timeout:
return Fals…
Track Internet Connectivity and Downtime Automatically in Python
Monitors internet connectivity by pinging a remote host and logs any downtime events with timestamps and duration.
import time
import subprocess
from datetime import datetime
def check_internet(host="8.8.8.8", timeout=3):
"""Returns True if internet is reachable via ping."""
try:
subprocess.run(
["ping", "-c", "1", "-W", str(timeout), host],
capture_output=True,
timeout=timeout …
How to List Failed Records in a Dead Letter Queue Mock in Python
A mock Dead Letter Queue stores failed processing records with error details and timestamps, lists them, and exports to JSON.
import json
from datetime import datetime, timedelta
import random
class DeadLetterQueue:
def __init__(self):
self.failed_records = []
def add_failed_record(self, record_id, payload, error_message):
self.failed_records.append({
"record_id": record_id,
"payload": paylo…
Build a Simple Log Graph in Python
Create a basic one-dimensional bar chart from log lines by counting occurrences of leading numeric keys.
import heapq
def log_graph(log_lines: list[str]) -> str:
"""Build a simple per-line, one-dimensional visual graph from log entries."""
counts: dict[int, int] = {}
for line in log_lines:
tokens = line.split()
if tokens:
try:
idx = int(tokens[0])
exce…
How to Make a Git Commit Heatmap by Hour in Python
Parse a git log output and count commits by weekday and hour, then print a compact heatmap table.
import re
from collections import Counter
from datetime import datetime
def parse_commits(log_text):
"""Parse git log lines and count commits by (weekday, hour)."""
pattern = re.compile(r"^Date:\s+(.+)$")
counts = Counter()
for line in log_text.splitlines():
match = pattern.match(line)
…
Mock AWS Spot Instance Interruption Handler in Python
A Python class that simulates AWS Spot instance interruption checks, handling the 10% chance of termination, logging state-saving, and storing notice details.
import time
import random
class SpotInstanceHandler:
def __init__(self, instance_id):
self.instance_id = instance_id
self.interruption_notices = []
def start(self):
print(f"Spot instance {self.instance_id} started")
def check_interruption(self):
# Simulate random interrup…
How to Bind and Mock structlog Context in Python
Shows how to bind persistent key-value context to a structlog logger, unbind keys, and mock the logger in tests to verify context is passed correctly.
import structlog
from unittest.mock import patch
logger = structlog.get_logger()
def demo():
logger = structlog.get_logger()
logger = logger.bind(user_id=42, request_id="abc123")
logger.info("user logged in", action="login")
# Unbind a key
logger = logger.unbind("user_id")
logger.info("r…
Mocking loguru for Structured Logging in Python
Simulate loguru's structured logging with a custom mock that captures JSON-formatted log entries with bound context.
import json
import sys
from io import StringIO
from unittest.mock import patch
def mock_loguru():
# Simulate a structured logger with context binding
class StructuredLogger:
def __init__(self):
self.context = {}
def bind(self, **kwargs):
logger = StructuredLogger()
…
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.