Python Code
Samples
Copy-ready Python snippets by topic and difficulty — short, focused, and runnable in the browser editor.
Route Tool Call Name to Python Handler Dict
Routes a tool call name to the correct Python handler function using a dictionary lookup, returning an error for unknown tools.
def get_name():
return {"name": "Alice"}
def get_age():
return {"age": 30}
def get_email():
return {"email": "alice@example.com"}
handlers = {
"get_name": get_name,
"get_age": get_age,
"get_email": get_email,
}
def route(tool_call):
handler = handlers.get(tool_call["name"])
if handl…
Route Messages to Handlers with a Python Dict
This code demonstrates a simple message routing pattern using a dictionary to map topic keys to handler functions, with a default handler for unmatched topics.
def route_message(message, routing_table):
"""Route a message to the correct handler based on the topic key."""
topic = message.get("topic", "default")
handler = routing_table.get(topic, routing_table.get("default"))
return handler(message)
def handle_orders(message):
return f"Orders handler proc…
How to Simulate RabbitMQ Exchange Routing in Python
Simulate RabbitMQ exchange routing using a nested dict, matching routing keys against patterns like error.* and info.# to return bound queues.
from collections import defaultdict
def route_message(exchanges, exchange_name, routing_key):
"""
Simulate RabbitMQ exchange routing using a nested dict structure.
Returns list of queue names that match the routing key.
"""
queues = exchanges.get(exchange_name, {})
matched = []
for pa…
How to mock RabbitMQ queue binding with routing keys in Python
A mock demonstration of binding a queue to an exchange with multiple routing keys in RabbitMQ using Python and pika, without a real broker connection.
import pika
import sys
def bind_queue_with_routing(channel, queue_name, exchange_name, routing_keys):
"""
Mock RabbitMQ queue binding with routing keys.
Prints the binding configuration instead of connecting to a real broker.
"""
for routing_key in routing_keys:
binding = {
"q…
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.
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…
How to Mock a Service Mesh Sidecar Proxy in Python
Simulate a service mesh sidecar proxy with route registration, service discovery, and request proxying using a simple Python class.
class SidecarProxy:
def __init__(self, name):
self.name = name
self.routes = {}
self.services = {}
self.requests_processed = 0
def register_service(self, service_name, address, port):
self.services[service_name] = f"{address}:{port}"
def add_route(self, path, servi…
How to Mock an API Gateway Router in Python
Create a lightweight HTTP server that routes requests to mock microservice responses, simulating an API gateway for local development and testing.
from http.server import HTTPServer, BaseHTTPRequestHandler
import json
class SimpleGateway(BaseHTTPRequestHandler):
def do_GET(self):
routes = {
"/users": {"service": "user-service", "status": "ok", "count": 42},
"/orders": {"service": "order-service", "status": "ok", "count": 17}…
How to implement read-your-writes sticky routing in Python
A mock StickyRouter class that routes all requests for the same key to the same node, ensuring read-after-write consistency.
import random
class StickyRouter:
def __init__(self, nodes):
self.nodes = nodes
self.routes = {}
def route(self, key):
if key not in self.routes:
self.routes[key] = random.choice(self.nodes)
return self.routes[key]
def read(self, key):
node = self.rout…
Geo shard by region in Python
Maps users to database shards based on geographic region with a deterministic hash fallback.
import json
from collections import defaultdict
REGION_SHARD_MAP = {
"na": ["shard-01", "shard-02"],
"eu": ["shard-03", "shard-04", "shard-05"],
"ap": ["shard-06"],
"sa": ["shard-07", "shard-08"],
}
# user_id -> region (mock lookup)
USER_REGIONS = {
"u_1001": "na",
"u_1002": "eu",
"u_1003…
Route SELECT Queries to Read Replicas in Python
A mock round-robin router that forwards SELECT queries to read replicas and sends writes to the primary.
import random
class ReadReplicaRouter:
"""Round-robin router that sends SELECT queries to read replicas."""
def __init__(self, replicas):
self.replicas = replicas
self.counter = 0
def route(self, sql):
if sql.strip().upper().startswith("SELECT"):
replica = sel…
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.