Reference library

Python Code Samples

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

73 matches
Testing & modern typing easy

Dependency Injection in Python for Testability

Inject a config dependency into a service so you can swap a real environment-based config for a fake one in tests.

dependency-injection testing mocking
Python
import os


class Config:
    """Simple config loader that can be easily faked in tests."""
    def get(self, key, default=None):
        return os.environ.get(key, default)


class UserService:
    def __init__(self, config):
        self.config = config

    def get_timeout(self):
        return int(self.config.get(…
16 0 Open
Testing & modern typing medium

How to Benchmark Python Code with pytest-benchmark and mocks

Use pytest-benchmark to measure function performance while combining Mock and patch for controlled test scenarios.

pytest benchmark mock
Python
import time
from unittest.mock import Mock, patch

import pytest
from pytest_benchmark.fixture import BenchmarkFixture


def heavy_operation(data: list[int]) -> int:
    """Simulates a CPU-bound operation."""
    return sum(x * x for x in data)


def test_heavy_operation_benchmark(benchmark: BenchmarkFixture) -> None:…
14 0 Open
Testing & modern typing medium

How to Mock a Factory Boy Model Instance in Python

Create a factory boy factory, then patch its Meta.model with a Mock to control instance behavior in tests.

factory-boy mocking unit-testing
Python
import factory
from dataclasses import dataclass
from unittest.mock import Mock, patch
import builtins


@dataclass
class User:
    name: str
    age: int


class UserFactory(factory.Factory):
    class Meta:
        model = User

    name = "Alice"
    age = 30


def get_user_name(user):
    return user.name


def ma…
15 0 Open
Testing & modern typing medium

How to Mock and Stub API Calls in Playwright E2E Tests with Python

This code demonstrates how to mock and stub API responses in Playwright end-to-end tests using Python's unittest.mock patch and Playwright's APIRequestContext.

playwright e2e-testing mocking
Python
import re
from unittest.mock import patch
from playwright.sync_api import sync_playwright

def verify_api_mock(page, mock_url, mock_response):
    with patch("playwright.sync_api.APIRequestContext.get") as mock_get:
        mock_get.return_value.json.return_value = mock_response
        mock_get.return_value.status_co…
13 0 Open
Testing & modern typing easy

How to Mock requests.get in Python

Mock requests.get with unittest.mock to test code that makes HTTP calls without hitting the network.

mocking requests unit-testing
Python
import requests
from unittest.mock import Mock, patch

def fetch_user_data(user_id):
    response = requests.get(f"https://api.example.com/users/{user_id}")
    return response.json()

def process_user(user_id):
    mock_response = Mock()
    mock_response.json.return_value = {"id": user_id, "name": "Alice", "age": 30…
12 0 Open
Testing & modern typing medium

How to Run an Integration Test with Docker Compose Mock in Python

Run a Python integration test against a docker-compose environment, using mocks to simulate service health and business logic responses.

docker integration-testing mocking
Python
import subprocess
import json
from typing import Dict

def run_integration_test() -> Dict[str, str]:
    """
    Simulates an integration test against a docker-compose environment
    using a mock service that returns canned responses.
    """
    # Mock docker-compose environment check
    env_ready = subprocess.run(…
15 0 Open
Testing & modern typing medium

How to Snapshot Test JSON with Mock in Python

Use pytest-snapshot to capture the exact output of a JSON-loading function, with and without mocking json.loads, so future changes are automatically detected.

pytest snapshot mock
Python
import json
from unittest.mock import Mock, patch
import pytest


def load_config(data):
    config = json.loads(data)
    return {"host": config["host"], "port": config["port"]}


def test_load_config_snapshot(snapshot):
    mock_data = json.dumps({"host": "localhost", "port": 8080, "extra": "ignored"})
    result = …
14 0 Open
Testing & modern typing easy

Interface Segregation with Fake Test Implementations in Python

Defines segregated abstract interfaces (Printer, Scanner) and uses a FakePrinter to record calls for unit testing without real resources.

abc interface-segregation testing
Python
from abc import ABC, abstractmethod


class Printer(ABC):
    @abstractmethod
    def print_document(self, doc: str) -> str:
        pass


class Scanner(ABC):
    @abstractmethod
    def scan_document(self) -> str:
        pass


class MultiFunctionPrinter(Printer, Scanner):
    def print_document(self, doc: str) -> …
13 0 Open
Testing & modern typing easy

Mock datetime with time-machine in Python

Use the time-machine library to travel to a fixed datetime when running tests or scripts, mocking datetime.utcnow().

testing datetime mock
Python
from time_machine import travel
from datetime import datetime


@travel("2020-01-01 10:30:00")
def check_date():
    return datetime.utcnow()


if __name__ == "__main__":
    print(check_date())
14 0 Open
Testing & modern typing medium

Use pytest fixture to mock a database connection in Python

This code shows how to use a pytest fixture and unittest.mock to replace a database connection with a Mock, enabling isolated tests without a real database.

pytest fixtures unittest.mock
Python
import pytest
import sqlite3
from unittest.mock import Mock

class Database:
    def __init__(self, connection):
        self.connection = connection

    def get_user(self, user_id):
        cursor = self.connection.cursor()
        cursor.execute("SELECT * FROM users WHERE id = ?", (user_id,))
        return cursor.…
19 0 Open
System design patterns easy

Builder pattern for mocking complex objects in Python

Use a fluent Builder to construct realistic mock objects with defaults, enabling readable test data setup.

builder-pattern mock-data testing
Python
class User:
    def __init__(self):
        self.name = "default"
        self.age = 0
        self.email = "unknown@example.com"
        self.address = "unknown"

    def __repr__(self):
        return f"User(name={self.name!r}, age={self.age}, email={self.email!r}, address={self.address!r})"


class UserBuilder:
   …
15 0 Open
System design patterns medium

How to Implement a Simple MVVM Binding Mock in Python

A minimal Python implementation of the MVVM pattern, mocking data binding so views auto-update when the view model changes.

mvvm binding observer pattern
Python
class BindingMock:
    def __init__(self, view_model):
        self.view_model = view_model
        self.subscribers = []

    def bind(self, property_name, callback):
        self.subscribers.append((property_name, callback))

    def set(self, property_name, value):
        setattr(self.view_model, property_name, va…
18 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
System design patterns medium

Object Pool Pattern for Database Connections in Python

Implements a reusable connection pool with acquire/release and context manager support, mocking database connections with idle reuse and exhaustion handling.

object-pool connection-pool databases
Python
import time
from contextlib import contextmanager
from collections import deque


class ConnectionPool:
    def __init__(self, size=3, max_idle=5):
        self._idle = deque(maxlen=max_idle)
        self._active = set()
        self.size = size

    def _create(self):
        return {"created_at": time.time(), "queri…
12 0 Open
API design & gRPC easy

How to Mock Content-Disposition and Extract Filename in Python

Parse and mock Content-Disposition headers in Python to extract filenames, handling both plain and RFC 5987 encoded values.

http mocking regex
Python
import os
from pathlib import Path
import re
from unittest.mock import patch

def get_filename_from_content_disposition(header_value):
    """
    Extract filename from a Content-Disposition header value.
    Supports both filename and filename* parameters (RFC 5987).
    """
    if not header_value:
        return No…
15 0 Open
Streaming & messaging easy

How to Build a Materialized View Updater Consumer Mock in Python

A mock consumer that queues change events and triggers refresh callbacks to simulate materialized view updates.

dataclasses deque mocking
Python
import time
from collections import deque
from dataclasses import dataclass, field
from typing import Callable, Deque, Optional


@dataclass
class MaterializedViewUpdater:
    """Mock updater that consumes change events and refreshes a view."""
    refresh: Optional[Callable[[str], None]] = None
    queue: Deque[tuple…
14 0 Open
Streaming & messaging medium

How to Mock NATS Subject Hierarchies with Wildcards in Python

Build a lightweight NATS-style pub/sub mock that matches subject hierarchies with '*' and '>' wildcards for tests or prototypes.

nats pubsub wildcards
Python
# Mock a simplified NATS subject hierarchy with wildcard matching
# Supports: exact match, '*' (single token), '>' (tail wildcard)

class NATSSubjectMock:
    def __init__(self):
        self.subscriptions = {}  # subject -> list of callbacks

    def subscribe(self, subject, callback):
        self.subscriptions.setd…
13 0 Open
Streaming & messaging medium

How to Mock Offset Commit Auto vs Manual in Python

Demonstrates a Kafka-style offset commit function with auto/manual modes and tests it using unittest.mock.patch.

unittest mocking kafka
Python
from unittest.mock import Mock, patch

def commit_offsets(topic_partition_offsets, auto_commit=False):
    """Manually commit offsets or simulate auto-commit."""
    if auto_commit:
        print(f"Auto-committing offsets: {topic_partition_offsets}")
        return {"status": "auto_committed"}
    
    print(f"Manuall…
15 0 Open
Streaming & messaging medium

How to Mock a Kafka Rebalance Listener in Python

Simulate Kafka consumer rebalance callbacks (on_partitions_revoked and on_partitions_assigned) with a mock consumer to test listener logic.

kafka rebalance mocking
Python
import time
from collections import defaultdict


class MockKafkaConsumer:
    def __init__(self):
        self.assignments = defaultdict(list)
        self.rebalances = 0

    def assign(self, partitions):
        self.rebalances += 1
        self.assignments.clear()
        for partition in partitions:
            s…
15 0 Open
Streaming & messaging medium

Mock Redis Streams XADD and XREAD in Python

A pure-Python mock of Redis streams that implements basic XADD, XREAD, and XLEN behavior for local testing without a real Redis server.

redis streams mocking
Python
import redis
import time
import threading


class MockRedisStreams:
    def __init__(self):
        self.streams = {}

    def xadd(self, stream_name, fields):
        if stream_name not in self.streams:
            self.streams[stream_name] = []
        entry_id = f"{time.time_ns()}-{len(self.streams[stream_name])}"
…
13 0 Open
Caching & Redis easy

How to Mock a Cache Key Schema Version Bump in Python

Show how to test a cache key schema bump by mocking the class-level version attribute with unittest.mock.

mock caching unittest
Python
from unittest import mock

class VersionCache:
    SCHEMA_VERSION = 1

    def __init__(self, key_prefix="cache"):
        self.key_prefix = key_prefix

    def build_key(self, resource_id):
        return f"{self.key_prefix}:schema-v{self.SCHEMA_VERSION}:{resource_id}"

    def bump_schema(self):
        # Simulated …
13 0 Open
Caching & Redis medium

Implement a TTL cache with a mock clock in Python

This code creates a simple TTL cache that stores values with an expiration timestamp and allows injecting a mock time function to test expiry behavior deterministically.

cache ttl mocking
Python
import time
from functools import wraps

class TTLCache:
    def __init__(self, ttl_seconds):
        self.ttl = ttl_seconds
        self.cache = {}
        self._now = time.time

    def set_mock_time(self, mock_time_fn):
        """Inject a mock time function for testing TTL expiry."""
        self._now = mock_time_…
15 0 Open
Reliability & rate limiting medium

How to Implement Graceful Degradation with Feature Disabling in Python

A pattern that disables enhanced features and falls back to basic functionality when a dependency fails, with mock-based testing.

graceful-degradation feature-flags resilience
Python
import random
from unittest.mock import patch


class EnhancedFeature:
    """A feature that can gracefully degrade when a dependency is unavailable."""

    def __init__(self):
        self.feature_enabled = True

    def get_enhanced_data(self):
        """Simulate an enhanced feature that depends on external data."…
12 0 Open
Reliability & rate limiting easy

How to Mock a Timeout per HTTP Request in Python

Simulate a per-request HTTP timeout using unittest.mock to test timeout handling without network access.

mocking timeout testing
Python
import time
from unittest.mock import Mock, patch

# Simulate an HTTP client that might time out
def fetch_data(url, timeout=5):
    time.sleep(0.5)  # Simulate network delay
    return f"Response from {url}"

# Mock to test timeout behavior without real network
def test_timeout():
    mock_response = Mock(side_effect…
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.