Reference library

Python Code Samples

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

5 matches
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
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
Modern tooling easy

Build a Textual TUI App Skeleton in Python

Create a minimal Textual terminal UI app with a header, label, button, and footer, ready for interactive mock demonstrations.

textual tui terminal
Python
from textual.app import App, ComposeResult
from textual.widgets import Header, Footer, Button, Label

class MockApp(App):
    """A minimal Textual TUI app skeleton."""

    BINDINGS = [("q", "quit", "Quit")]

    def compose(self) -> ComposeResult:
        """Create child widgets."""
        yield Header()
        yie…
14 0 Open
API design & gRPC easy

Return Proper HTTP Status Codes Table in Python

Mock HTTP status code table with proper numeric and textual representations, including formatted status lines and a filtered table view.

http-status api mock
Python
# Mock HTTP status code table with proper numeric and textual representations

codes = {
    200: "OK",
    201: "Created",
    204: "No Content",
    301: "Moved Permanently",
    302: "Found",
    304: "Not Modified",
    400: "Bad Request",
    401: "Unauthorized",
    403: "Forbidden",
    404: "Not Found",
    50…
12 0 Open
A/B testing & experimentation medium

How to simulate a contextual bandit in Python

Simulate a contextual multi-armed bandit with random features and epsilon-greedy action selection in Python.

bandit-algorithms simulation epsilon-greedy
Python
import random


class ContextualBandit:
    def __init__(self, n_actions=3, n_features=4):
        self.n_actions = n_actions
        self.n_features = n_features
        self.theta = [random.random() for _ in range(n_actions * n_features)]

    def mock_context(self):
        return [random.uniform(-1, 1) for _ in ra…
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.