Reference library

Python Code Samples

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

23 matches
Strings & text easy

How to wrap long text to a specified width in Python

Uses Python's textwrap.fill to wrap a long string to a specified width at word boundaries, preserving readability in console output or logs.

textwrap text wrapping formatting
Python
import textwrap

text = """This is a long piece of text that definitely exceeds the width limit
if we try to print it on a single line without any wrapping applied."""

wrapped = textwrap.fill(text, width=40)

print(wrapped)
11 0 Open
Functions & basics easy

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.

decorator logging functools
Python
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…
10 0 Open
Errors & debugging medium

How to Log Errors with Structured Fields in Python

Logs error details as structured dictionary fields using Python's logging module with extra parameters.

logging errors structured
Python
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 …
14 0 Open
Errors & debugging medium

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.

contextvars exception-handling logging
Python
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…
12 0 Open
Files & data medium

Build a Personal Work Hours Tracker in Python

A Python class that logs daily work hours to a CSV file and produces a weekly summary of total hours worked.

work-hours time-tracking csv
Python
import csv
from pathlib import Path
from datetime import datetime, date

class WorkHoursTracker:
    def __init__(self, file_path="work_hours.csv"):
        self.file_path = Path(file_path)
        if not self.file_path.exists():
            with open(self.file_path, "w", newline="") as f:
                writer = csv…
59 0 Open
Files & data easy

Generate Timesheet Reports from Daily Logs in Python

Aggregate daily log entries by project and produce a formatted timesheet report using Python's standard library.

timesheet reporting aggregation
Python
import json
from pathlib import Path
from collections import defaultdict

def generate_timesheet_report(daily_logs: list[dict]) -> str:
    """
    Generate a timesheet report from daily log entries.
    
    Args:
        daily_logs: List of dicts with 'date', 'project', 'hours', 'task' keys
    
    Returns:
       …
44 0 Open
Files & data easy

How to Extract IP Address Counts from Access Logs in Python

Read a web server access log, count occurrences of each IP address using regex and Counter, and print the ranked results.

regex access log counter
Python
import re
from collections import Counter
from pathlib import Path

def extract_ip_counts(log_file_path):
    ip_pattern = r'^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})'
    ip_counter = Counter()
    
    with open(log_file_path, 'r') as file:
        for line in file:
            match = re.match(ip_pattern, line)
       …
16 0 Open
AI & LLM integration patterns medium

Parse ReAct Logs into Thought Action Observation Steps in Python

Parse a ReAct agent's textual log into structured steps with thought, action, and observation using regex and named tuples.

react regex llm
Python
import re
from collections import namedtuple


ReActStep = namedtuple("ReActStep", ["thought", "action", "observation"])


def parse_react_log(log: str) -> list[ReActStep]:
    """Parse a ReAct log into structured thought/action/observation steps."""
    pattern = re.compile(
        r"Thought:\s*(?P<thought>.+?)\s*"
…
12 0 Open
Automation & scripting easy

Aggregate Log Errors Count by Hour in Python

Counts ERROR log lines per hour using regex and Counter, returning a sorted dictionary of hourly totals.

logs regex counter
Python
import re
from collections import Counter
from datetime import datetime

def aggregate_errors_by_hour(log_lines):
    pattern = re.compile(r'^(\d{4}-\d{2}-\d{2} \d{2}):\d{2}:\d{2}.*ERROR')
    hourly_counts = Counter()
    
    for line in log_lines:
        match = pattern.match(line)
        if match:
            ho…
20 0 Open
Automation & scripting easy

Automatically Log CPU, RAM, and Disk Usage Every Minute in Python

This script logs CPU, RAM, and disk usage to a CSV file every 60 seconds using psutil and Python's standard library.

psutil automation monitoring
Python
import psutil
import time
import csv
from pathlib import Path

LOG_FILE = Path("system_usage_log.csv")
INTERVAL_SECONDS = 60

def log_system_usage():
    """Write CPU, RAM, and disk usage to CSV every minute."""
    file_exists = LOG_FILE.exists()
    with open(LOG_FILE, mode="a", newline="") as f:
        writer = cs…
48 0 Open
Automation & scripting easy

Generate a Monthly Report CSV from Log Files in Python

Reads a CSV log file, filters events by a given month, aggregates daily event counts and revenue, and writes a summarized monthly report to a new CSV.

csv logs report
Python
import csv
from collections import defaultdict
from datetime import datetime

def generate_monthly_report(log_file: str, month: str, output_file: str) -> None:
    events_by_date = defaultdict(int)
    revenue_by_date = defaultdict(float)
    
    with open(log_file, 'r') as f:
        for line in f:
            date_…
13 0 Open
Automation & scripting medium

Python: Archive Old Logs by Compressing Gzip by Age

A Python script that finds .log files older than a specified age and compresses them into .gz archives while removing the originals.

gzip log-rotation automation
Python
import gzip
import os
import shutil
from pathlib import Path


def archive_logs(log_dir: str, max_age_days: int) -> list[str]:
    """Compress log files older than max_age_days into .gz archives.
    
    Returns a list of compressed file paths.
    """
    cutoff = time.time() - max_age_days * 86400
    compressed = …
13 0 Open
Automation & scripting medium

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.

internet connectivity monitoring
Python
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 …
37 0 Open
Cloud + Python easy

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.

gcp secret-manager mock
Python
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:
        …
14 0 Open
System design patterns medium

How to Build a Sidecar Logging Proxy in Python

Wrap any object with a proxy that transparently logs every method call, arguments, return value, and execution time to a file — mimicking a sidecar pattern.

proxy logging sidecar
Python
import logging
import time
from datetime import datetime


class LoggingProxy:
    """Sidecar-style proxy that logs all calls to a wrapped object."""

    def __init__(self, target, log_file="proxy.log"):
        self._target = target
        logging.basicConfig(
            filename=log_file,
            level=loggin…
14 0 Open
API design & gRPC easy

How to Add a Correlation ID Tracing Header in Python

A mock middleware generates or preserves a correlation ID header and logs structured JSON messages with it for API request tracing.

correlation-id tracing middleware
Python
import uuid
import json
from dataclasses import dataclass, field
from typing import Optional

@dataclass
class Request:
    headers: dict = field(default_factory=dict)

    def get(self, key, default=None):
        return self.headers.get(key, default)

class CorrelationIdMiddleware:
    def __init__(self, header_name…
14 0 Open
Observability & SRE easy

How to Do Structured JSON Line Logging in Python

Create a simple JSON-lines logger that writes one JSON object per line to stdout with timestamp, level, message, and custom context fields.

logging json observability
Python
import json
import sys
from datetime import datetime

class JsonLineLogger:
    def __init__(self, stream=sys.stdout):
        self.stream = stream

    def log(self, level, message, **context):
        record = {
            "timestamp": datetime.utcnow().isoformat() + "Z",
            "level": level,
            "me…
14 0 Open
Observability & SRE easy

How to Do Structured JSON Logging in Python

Create a custom logging formatter that outputs each log entry as a single JSON line with timestamp, level, logger name, and message.

logging json observability
Python
import json
import logging
from datetime import datetime


class JsonFormatter(logging.Formatter):
    def format(self, record):
        log_entry = {
            "timestamp": datetime.utcnow().isoformat() + "Z",
            "level": record.levelname,
            "logger": record.name,
            "message": record.ge…
13 0 Open
Observability & SRE easy

How to Route Alerts by Severity in Python

Map alert severity levels to routing targets and simulate dispatching alerts to on-call pages, email, Slack, or logs.

observability alerts routing
Python
def main():
    # Severity levels with corresponding alert routing targets
    routing_map = {
        "critical": "call_page",
        "high": "call_page",
        "medium": "email_team",
        "low": "slack_channel",
        "info": "log_only"
    }

    # Simulated alerts with severity
    alerts = [
        {"na…
11 0 Open
Observability & SRE easy

How to Ship Logs to an Aggregator Endpoint in Python

Ship batched log entries to a mock HTTP aggregator endpoint with proper error handling and response status.

logging requests json
Python
import json
import requests
from datetime import datetime, timezone

LOG_ENTRIES = [
    {"timestamp": "2024-01-15T10:00:00Z", "level": "INFO", "message": "Server started"},
    {"timestamp": "2024-01-15T10:00:05Z", "level": "WARN", "message": "High memory usage"},
    {"timestamp": "2024-01-15T10:00:10Z", "level": "E…
12 0 Open
A/B testing & experimentation medium

How to join assignment logs with outcomes in Python

Merge submission log entries with grading outcomes using left join and full outer join patterns in pure Python.

join data-merge ab-testing
Python
from datetime import datetime, timedelta

class AssignmentLog:
    def __init__(self):
        self.logs = [
            {"assignment_id": 101, "student_id": "S001", "submitted_at": "2024-03-01 10:30:00"},
            {"assignment_id": 101, "student_id": "S002", "submitted_at": "2024-03-02 14:15:00"},
            {"as…
11 0 Open
Production deployment patterns easy

How to Build a Data Helper for Production Deployment in Python

Build a reusable DataHelper class that loads configs, validates required keys, normalizes string values, and logs schema details — a production-ready data processing pattern.

json pathlib data-processing
Python
import json
from pathlib import Path
from typing import Any, Dict

class DataHelper:
    """Common data processing patterns for production deployment."""
    
    def __init__(self, config_path: str | Path):
        self.config_path = Path(config_path)
        self.config = self._load_config()
    
    def _load_confi…
13 0 Open
Production deployment patterns easy

How to Implement a Manual Approval Gate Mock in Python

Simulates a manual approval workflow with threshold-based rules, random decisions for medium amounts, and logs each result with timing.

approval simulation workflow
Python
import random
import time


def approve_request(amount: float) -> bool:
    if amount <= 1000:
        return True
    if amount <= 5000:
        return random.random() < 0.7
    return False


def main():
    requests = [500, 1200, 7500, 3000, 50]
    for amount in requests:
        start = time.perf_counter()
      …
17 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.