Reference library

Python Code Samples

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

18 matches
OOP & classes medium

Unit of Work Pattern: Track Changes, Commit, and Rollback in Python

This code defines a UnitOfWork class that tracks operations (add) and supports commit to apply changes and rollback to revert them, using a dataclass-based logger.

unit-of-work dataclass transaction
Python
from dataclasses import dataclass, field
from typing import Any, Callable, List, Tuple


@dataclass
class UnitOfWork:
    log: List[Tuple[str, Callable, tuple, dict]] = field(default_factory=list)

    def track(self, operation: str, fn: Callable, *args, **kwargs):
        self.log.append((operation, fn, args, kwargs)…
13 0 Open
Data pipelines & processing easy

Implement Exactly-Once Transaction Log in Python

A mock transaction log that deduplicates transaction IDs so each is recorded only once, with a dataclass for records and simple in-memory storage.

transactions deduplication dataclass
Python
from dataclasses import dataclass
from typing import Dict, Optional


@dataclass
class TxnRecord:
    txn_id: str
    status: str


class ExactlyOnceTxnLog:
    def __init__(self) -> None:
        self._log: Dict[str, TxnRecord] = {}
        self._processed_ids: set = set()

    def record(self, txn_id: str, status: s…
14 0 Open
System design patterns medium

How to implement saga orchestration with compensating steps in Python

Orchestrate a distributed transaction across services, rolling back completed steps with compensations when a later step fails.

saga distributed-transactions compensation
Python
class InventoryService:
    def reserve(self, order_id):
        print(f"[Inventory] Reserving stock for order {order_id}")
        return True

    def compensate(self, order_id):
        print(f"[Inventory] Releasing stock for order {order_id}")


class PaymentService:
    def charge(self, order_id):
        print(f…
14 0 Open
System design patterns medium

Outbox pattern reliable publish in Python with SQLite

Implements a transactional outbox with SQLite, ensuring reliable message publishing by storing events in the same DB transaction as business changes.

outbox sqlite transaction
Python
import sqlite3
from contextlib import contextmanager
from datetime import datetime, timezone


class Outbox:
    def __init__(self, db_path=":memory:"):
        self.conn = sqlite3.connect(db_path)
        self.conn.execute("""
            CREATE TABLE IF NOT EXISTS outbox (
                id INTEGER PRIMARY KEY AUTO…
11 0 Open
Streaming & messaging medium

Implement the Transactional Outbox Pattern with SQLite in Python

A Python implementation of the transactional outbox pattern using SQLite, ensuring atomic writes of order data and outbox events in a single transaction while supporting reliable message publishing and consumption.

outbox-pattern sqlite transactions
Python
import sqlite3
from dataclasses import dataclass
from datetime import datetime, timezone
import json

@dataclass
class Order:
    order_id: str
    amount: float
    status: str

class TransactionalOutbox:
    def __init__(self, db_path=":memory:"):
        self.conn = sqlite3.connect(db_path)
        self._create_tab…
17 0 Open
Caching & Redis medium

How to Mock a Redis Transaction with MULTI/EXEC in Python

A minimal in-memory mock of Redis MULTI/EXEC transactions that queues commands and applies them atomically on EXEC.

redis mock transactions
Python
class RedisTransactionMock:
    def __init__(self):
        self.data = {}
        self.queue = []
        self.in_transaction = False

    def multi(self):
        self.in_transaction = True
        self.queue = []
        return "OK"

    def set(self, key, value):
        if self.in_transaction:
            self.qu…
14 0 Open
Caching & Redis medium

Python Redis WATCH optimistic lock mock

A MockRedis class that simulates WATCH/MULTI/EXEC transactions with optimistic locking to detect concurrent modifications before committing.

redis optimistic-locking transactions
Python
import time
import threading


class MockRedis:
    def __init__(self):
        self.data = {}
        self.watched = {}
        self.lock = threading.Lock()

    def get(self, key):
        return self.data.get(key)

    def set(self, key, value):
        self.data[key] = value

    def watch(self, *keys):
        wi…
12 0 Open
Reliability & rate limiting medium

Mock a Two-Phase Commit Coordinator in Python

Simulates a two-phase commit protocol where a coordinator asks participants to prepare, then commits or aborts based on unanimous readiness.

two-phase commit distributed systems transactions
Python
import random
import time
from typing import Dict, List


class TwoPhaseCommitCoordinator:
    def __init__(self, participants: List[str]):
        self.participants = participants
        self.participant_state: Dict[str, bool] = {}

    def prepare(self) -> bool:
        print("[Coordinator] Phase 1: Prepare")
     …
12 0 Open
Reliability & rate limiting medium

Saga Compensating Transaction Mock in Python

Simulates a distributed transaction using a saga pattern with compensating actions that roll back steps on failure.

saga transaction compensation
Python
import random
import time


class OrderService:
    def __init__(self):
        self.orders = {}

    def create_order(self, order_id):
        print(f"[Order] Creating order {order_id}...")
        time.sleep(0.1)
        if random.random() < 0.3:  # 30% chance of failure
            raise RuntimeError(f"Order {order…
12 0 Open
Microservices patterns medium

How to Implement a Two-Phase Commit Mock in Python

Simulate a distributed two-phase commit with prepare, commit, and abort phases, including deterministic failure injection for testing.

2pc transaction microservices
Python
import random
from dataclasses import dataclass
from typing import Dict, List, Optional


@dataclass
class Transaction:
    tx_id: int
    data: Dict[str, str]


class TwoPhaseCommitMock:
    """Simple two-phase commit mock with prepare and commit phases."""

    def __init__(self) -> None:
        self.prepared: List…
13 0 Open
Microservices patterns medium

How to Mock a Choreography Saga in Python

Simulate a choreography-based saga with event envelopes, status tracking, and compensating actions to model distributed transactions.

saga microservices events
Python
import json
from dataclasses import dataclass, asdict
from typing import List, Optional
from enum import Enum


class SagaStatus(Enum):
    PENDING = "PENDING"
    COMPLETING = "COMPLETING"
    COMPLETED = "COMPLETED"
    FAILED = "FAILED"


@dataclass
class EventEnvelope:
    event_type: str
    order_id: str
    sta…
13 0 Open
Microservices patterns medium

Python Saga Compensating Steps Mock

Mock a distributed transaction saga with forward steps and compensating actions that reverse partial progress on failure.

saga microservices compensation
Python
from datetime import datetime


def make_payment(user_id, amount):
    print(f"[{datetime.now():%H:%M:%S}] Payment of ${amount} processed for user {user_id}")
    return {"step": "payment", "status": "ok", "details": f"${amount} charged"}


def deduct_inventory(order_id, items):
    print(f"[{datetime.now():%H:%M:%S}]…
14 0 Open
Microservices patterns medium

Saga pattern orchestration with rollback in Python

Orchestrate a distributed transaction with Saga steps and automated compensation rollback on failure.

saga microservices transaction
Python
import time
import random


class SagaStep:
    def __init__(self, name):
        self.name = name
        self.executed = False

    def execute(self):
        print(f"Executing {self.name}...")
        time.sleep(0.2)
        if random.random() < 0.3:
            raise RuntimeError(f"{self.name} failed")
        sel…
14 0 Open
Big data & Spark medium

Delta Lake ACID Transaction Log Mock in Python

Simulates Delta Lake's transactional log with JSON files for atomic commits, versioned operations, and crash recovery

delta-lake transaction-log acid
Python
import json
import time
from pathlib import Path

class DeltaLog:
    def __init__(self, path):
        self.log_dir = Path(path)
        self.log_dir.mkdir(parents=True, exist_ok=True)
        self.version = 0

    def _write_txn(self, action, payload):
        txn = {
            "version": self.version,
           …
16 0 Open
Database scaling & optimization medium

How to Mock a Cross-Shard Saga in Python

Simulate a distributed saga with compensating transactions across multiple database shards using a lightweight Python class that tracks executed steps and rolls them back in reverse on failure.

saga sharding distributed-systems
Python
import json


class SagaState:
    def __init__(self, saga_id):
        self.saga_id = saga_id
        self.executed_steps = []
        self.compensations = []

    def execute_step(self, shard, step_name, operation):
        self.executed_steps.append((shard, step_name))
        print(f"[Saga {self.saga_id}] Executin…
14 0 Open
Database scaling & optimization medium

How to Simulate Distributed Transactions in Python with a Mock

Model distributed transaction behavior with a mock Transaction class that supports commit, rollback, and failure simulation.

transactions mock database
Python
class Transaction:
    def __init__(self, id):
        self.id = id
        self.operations = []
        self.committed = False

    def add_operation(self, op, data):
        self.operations.append((op, data))

    def commit(self):
        if not self.operations:
            raise ValueError("No operations to commit…
13 0 Open
Database scaling & optimization medium

How to mock batch commit of transactions in Python

Simulate a transaction batch writer with commit, rollback, and summary logic to test database write patterns without a real database.

transactions mock batch
Python
import json
from datetime import datetime, timezone

class TransactionBatch:
    def __init__(self):
        self.pending = []
        self.committed = []
        self._log = []

    def add(self, operation):
        self.pending.append(operation)

    def commit(self):
        if not self.pending:
            return …
16 0 Open
Database scaling & optimization medium

Two Phase Commit Cross Shard Mock in Python

Simulates a two-phase commit across shards with failure handling to demonstrate distributed transaction coordination in Python.

two-phase-commit distributed-systems transaction
Python
"""Mock cross-shard two-phase commit with caution handling."""

class Shard:
    def __init__(self, name):
        self.name = name
        self.prepared = False
        self.committed = False
        self.aborted = False

    def prepare(self):
        # Simulate potential failure (1 in 3 chance on third shard)
     …
14 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.