Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
Profile Python functions with cProfile
Profile a Python program with cProfile, capture the stats in memory, and print a sorted performance report.
import cProfile
import pstats
import io
def slow_function():
total = 0
for i in range(100000):
total += i ** 2
return total
def medium_function():
return sum(range(10000))
def fast_function():
return sum(range(100))
def main():
result1 = slow_function()
result2 = medium_func…
How to Inspect Local Variables in an except Block in Python
Capture and print local variables at the moment an exception occurs using locals() inside an except block.
def risky_operation(value):
try:
result = 10 / value
return result
except ZeroDivisionError as e:
local_vars = dict(locals())
print(f"Error: {e}")
print("Local variables at exception:")
for key, val in local_vars.items():
print(f" {key} = {val}")
…
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 Send Values into a Python Generator Coroutine
Use the .send() method to pass values into a running generator coroutine and capture them.
def coroutine():
received = []
while True:
value = yield
received.append(value)
print(f"Coroutine received: {value}")
if value == "stop":
break
return received
if __name__ == "__main__":
gen = coroutine()
next(gen) # Prime the generator
gen.send("he…
How to Run Git Commands from Python with subprocess
This helper runs `git status --short` and `git log --oneline` from Python, captures their output, and returns readable strings with error handling for non-repo directories.
import subprocess
def git_status():
"""Return a short, human-readable git status."""
try:
output = subprocess.run(
["git", "status", "--short"],
capture_output=True,
text=True,
check=True,
).stdout.strip()
return output if output else "W…
How to Mock CLI Output in Typer with unittest.mock
Mock and capture Typer CLI output using unittest.mock.patch and io.StringIO for testing command-line applications.
import typer
from unittest.mock import patch
import io
app = typer.Typer()
@app.command()
def greet(name: str, age: int = 18, uppercase: bool = False):
"""Greet a person with optional formatting."""
message = f"Hello {name}, age {age}"
if uppercase:
message = message.upper()
typer.echo(messag…
How to Mock OpenTelemetry Tracer Setup in Python
Set up a mock OpenTelemetry tracer with an in-memory span exporter to capture spans for testing and debugging.
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import SimpleSpanProcessor
from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter
def setup_tracer():
provider = TracerProvider()
exporter = InMemorySpanExpo…
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()
…
Capture stdout and stderr with pytest capsys
Use pytest's capsys fixture to capture and assert on standard output and error streams in your tests.
import pytest
# Function under test
def greet(name):
print(f"Hello, {name}!")
print(f"Error: {name} not found", file=sys.stderr)
def test_captures_stdout_and_stderr(capsys):
greet("Alice")
captured = capsys.readouterr()
assert "Hello, Alice!" in captured.out
assert "Error: Alice not foun…
Characterization Test for Legacy Python Code
Capture the exact output of a legacy Python function for known inputs, creating a characterization test that documents current behavior before refactoring.
def legacy_behavior(value):
"""Legacy function that returns a tuple with unconventional types."""
if value == "special":
return None, "legacy-special"
elif value > 100:
return value, "large"
elif value > 0:
return value * 2, "positive-doubled"
elif value == 0:
…
How to Capture Logging Records with pytest caplog in Python
Capture and assert on logging records in pytest using the built-in caplog fixture.
import logging
import pytest
def divide(a, b):
"""Divide two numbers and log an error if b is zero."""
if b == 0:
logging.error("Division by zero attempted")
return None
logging.info(f"Dividing {a} by {b}")
return a / b
def test_divide_logs_error(caplog):
with caplog.at_level(logg…
How to Snapshot Test JSON with Mock in Python
Use pytest-snapshot to capture the exact output of a JSON-loading function, with and without mocking json.loads, so future changes are automatically detected.
import json
from unittest.mock import Mock, patch
import pytest
def load_config(data):
config = json.loads(data)
return {"host": config["host"], "port": config["port"]}
def test_load_config_snapshot(snapshot):
mock_data = json.dumps({"host": "localhost", "port": 8080, "extra": "ignored"})
result = …
How to Take Periodic Snapshots of Aggregate State in Python
Build a Python class that accumulates values and periodically captures immutable snapshots of total, count, and average for later analysis.
import time
import random
from collections import defaultdict
class SnapshotAggregator:
def __init__(self):
self.total = 0
self.count = 0
self.history = []
def add(self, value):
self.total += value
self.count += 1
def snapshot(self):
avg = self.total / se…
How to Build a Mock Change Data Capture Event Stream in Python
Generate a deterministic list of mock CDC events with event IDs, stream positions, payloads, and timestamps for testing streaming pipelines.
from itertools import count
from random import choice, randint, seed
from datetime import datetime, timedelta
seed(42) # Make output deterministic
event_types = ["INSERT", "UPDATE", "DELETE"]
table_names = ["users", "orders", "products", "payments"]
counter = count(1)
def mock_cdc_event(stream_index: int) -> dict:
…
How to Create a StatsD UDP Metric Mock Server in Python
Run a lightweight mock UDP server that captures StatsD metrics over a short window for local testing.
import socket
import threading
import time
def start_mock_statsd_server(host="127.0.0.1", port=8125, timeout=3):
"""Run a mock StatsD UDP server that captures metrics for a short window."""
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind((host, port))
sock.settimeout(timeout)
me…
How to use foreachBatch with a mock sink in PySpark
Demonstrates using Spark Structured Streaming's foreachBatch sink to capture and verify streaming batches by writing them into a custom mock sink object.
from pyspark.sql import SparkSession
from pyspark.sql.functions import col, lit
class MockSink:
def __init__(self):
self.batches = []
def write_batch(self, batch_df, batch_id):
# Collect batch data as list of dicts for verification
records = batch_df.collect()
self.batches…
How to Mock HTTP Responses to Verify HSTS Headers in Python
This code demonstrates how to use unittest.mock to intercept and capture HTTP response headers, specifically the Strict-Transport-Security header, from a mocked HTTPServer handler for security validation.
from http.server import BaseHTTPRequestHandler, HTTPServer
from unittest.mock import patch
class StrictTransportMock(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(200)
self.send_header("Strict-Transport-Security", "max-age=31536000; includeSubDomains")
self.end_headers()
…
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.