Reference library

Python Code Samples

Medium snippets you can copy, study, and run in the browser editor.

4 matches
API design & gRPC medium

Build a Mock REST API with PUT and GET in Python

A minimal mock REST server implementing idempotent PUT for resource replacement and GET for retrieval, built with Python's http.server module.

rest-api http-server mock
Python
from http.server import BaseHTTPRequestHandler, HTTPServer
import json
from urllib.parse import urlparse

mock_db = {}

class MockAPIHandler(BaseHTTPRequestHandler):
    def do_PUT(self):
        parsed = urlparse(self.path)
        resource_id = parsed.path.strip("/").split("/")[-1]
        content_length = int(self.…
15 0 Open
Reliability & rate limiting medium

At Least Once with Idempotent Consumer in Python

Implements a thread-safe idempotent consumer that processes each unique message exactly once, even when a producer sends duplicates under an at-least-once delivery model.

idempotency at-least-once threading
Python
import threading
import time
import uuid
from collections import Counter


class IdempotentConsumer:
    def __init__(self):
        self.processed = set()
        self._lock = threading.Lock()

    def consume(self, message_id, payload):
        with self._lock:
            if message_id in self.processed:
          …
15 0 Open
Reliability & rate limiting medium

How to retry idempotent operations with a mock in Python

Wrap a flaky idempotent operation in a retry loop with exponential backoff, and use unittest.mock to deterministically test the str's behavior.

retry backoff mock
Python
import random
import time
from unittest.mock import Mock


def idempotent_operation(value):
    """Simulate an idempotent operation that sometimes fails."""
    if random.random() < 0.6:  # 60% failure rate
        raise ConnectionError("Temporary failure")
    return value * 2


def retry_with_backoff(operation, max_…
14 0 Open
Database scaling & optimization medium

Idempotent Writes for Sharded Databases in Python

Implement a mock shard with idempotent write support using request IDs to prevent duplicate writes and track the latest value per key.

idempotency sharding distributed-systems
Python
import json


class ShardMock:
    """Mock distributed shard with idempotent write support."""

    def __init__(self, shard_id):
        self.shard_id = shard_id
        self._store = {}

    def write(self, key, value, request_id):
        """Write value only if request_id not yet processed; idempotent."""
        i…
13 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.