Reference library

Python Code Samples

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

7 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
System design patterns medium

Mock Unit of Work commit and rollback in Python

Verify that a Unit of Work pattern commits on success and rolls back on failure using unittest.mock in Python.

unit-of-work mocking testing
Python
from unittest import mock


class UnitOfWork:
    def __init__(self):
        self.committed = False
        self.rolled_back = False

    def commit(self):
        self.committed = True
        print("Commit executed")

    def rollback(self):
        self.rolled_back = True
        print("Rollback executed")


def b…
13 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
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
Production deployment patterns medium

Auto Rollback on Error Rate Exceeded in Python

Simulate a service that monitors a rolling window of request errors and automatically rolls back when the error rate exceeds a threshold.

error-rate rollback rolling-window
Python
import random
import time


def simulate_requests(total_requests=1000, rollback_threshold=0.2):
    """
    Simulate a service that automatically rolls back when the error rate
    exceeds a threshold within a rolling window.
    """
    window_size = 100
    errors_seen = []
    rolled_back = False

    for req_num i…
15 0 Open
Production deployment patterns medium

How to Simulate Blue-Green Deployment Switch in Python

A mock Blue-Green deployment class that deploys new versions to an inactive environment, runs a health check, switches traffic, and supports rollback in Python.

deployment blue-green mock
Python
import random
import time

class BlueGreenDeployment:
    def __init__(self, initial_env="blue"):
        self.environments = {"blue": "v1.0", "green": "v1.0"}
        self.active_env = initial_env
        self.running = True

    def deploy_new_version(self, version, target_env):
        if target_env == self.active_…
16 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.