Reference library

Python Code Samples

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

15 matches
Automation & scripting easy

How to Create a Mock Headless Browser Screenshot Stub in Python

This code provides a deterministic stub that simulates capturing webpage screenshots with a headless browser, returning formatted output without real browser dependencies.

mock headless screenshot
Python
import subprocess
import sys

def mock_screenshot_webpage(url: str, width: int = 1280, height: int = 800) -> str:
    """Stub that simulates taking a screenshot of a webpage using headless browser."""
    # In real implementation, you would use playwright/selenium/headless chrome
    result = {
        "url": url,
   …
13 0 Open
Automation & scripting easy

How to Generate an Inventory CSV of Installed pip Packages in Python

This script uses subprocess and csv to list all installed pip packages and write their names and versions into a CSV inventory file.

pip csv subprocess
Python
import subprocess
import csv

def get_installed_packages():
    """Return a list of (name, version) tuples for installed pip packages."""
    result = subprocess.run(
        ["pip", "list", "--format=freeze"],
        capture_output=True,
        text=True,
        check=True
    )
    packages = []
    for line in r…
13 0 Open
Automation & scripting medium

Scrape HTML Tables in Python with html.parser

Extract data from HTML tables using Python's built-in html.parser module, without third-party dependencies, by overriding callback methods to track table, row, and cell states.

html scraping parser
Python
import html.parser
from urllib.request import urlopen


class TableParser(html.parser.HTMLParser):
    def __init__(self):
        super().__init__()
        self.in_table = False
        self.in_row = False
        self.in_cell = False
        self.current_cell = []
        self.rows = []
        self.row = []

    d…
12 0 Open
Data pipelines & processing medium

How to Topologically Sort a DAG in Python

Compute a valid execution order for tasks with dependencies using Kahn's algorithm in Python.

dag topological-sort graph
Python
from collections import defaultdict, deque


def topological_order(dependencies):
    graph = defaultdict(list)
    in_degree = defaultdict(int)
    tasks = set(dependencies.keys())

    for task, depends_on in dependencies.items():
        for d in depends_on:
            graph[d].append(task)
            in_degree[t…
11 0 Open
Cloud + Python medium

Generate a Mock Presigned URL in Python with HMAC

Build a mock AWS S3 presigned URL using an HMAC-SHA256 signature, mimicking the core SigV4 pattern without cloud SDK dependencies.

aws s3 presigned-url
Python
import hashlib
import hmac
import time
import base64

def generate_presigned_url_mock(secret_key, bucket, object_key, expires_in=3600):
    # Build the canonical request string (simplified AWS SigV4 style)
    timestamp = str(int(time.time()))
    expiry = str(int(time.time()) + expires_in)
    payload = f"GET\n/{buck…
13 0 Open
Cloud + Python easy

How to Mock AWS Secrets Manager in Python

Create a lightweight mock of AWS Secrets Manager's get_secret_value API to test secret retrieval without cloud dependencies.

aws secrets-manager mock
Python
import json
from typing import Optional


class MockSecretsManager:
    """A simple mock of AWS Secrets Manager's get_secret_value API."""

    def __init__(self):
        self._secrets: dict[str, str] = {}

    def create_secret(self, secret_id: str, secret_value: str) -> None:
        """Store a secret value under a…
14 0 Open
Cloud + Python easy

How to Mock Azure Service Bus Queue in Python

A lightweight in-memory mock of the Azure Service Bus queue API for local testing without cloud dependencies.

azure service-bus mock
Python
import json
import time
from collections import deque

class ServiceBusQueueMock:
    def __init__(self, queue_name):
        self.queue_name = queue_name
        self._messages = deque()
        self._dead_letter_queue = deque()
        self._message_counter = 0

    def send_message(self, body, message_id=None, prop…
14 0 Open
Cloud + Python medium

Mock S3, GCS, and Azure storage with a Python abstract interface

Define an abstract Storage interface and implement a local, filesystem-backed mock so S3, GCS, and Azure code can be tested without cloud dependencies.

storage abstraction testing
Python
from abc import ABC, abstractmethod
from pathlib import Path


class Storage(ABC):
    @abstractmethod
    def put(self, name: str, data: bytes) -> None:
        pass

    @abstractmethod
    def get(self, name: str) -> bytes:
        pass


class LocalStorage(Storage):
    def __init__(self, base_dir: str = "mock_sto…
14 0 Open
Modern tooling easy

How to Mock BugSnag Notify in Python

Use unittest.mock to simulate BugSnag notifications, verify calls, and test error handling without external dependencies.

mocking bugsnag testing
Python
import mock

bugsnag = mock.MagicMock()

def notify_error(message, severity="error"):
    bugsnag.notify(message, severity=severity)

if __name__ == "__main__":
    notify_error("Test error", severity="warning")
    bugsnag.notify.assert_called_once_with("Test error", severity="warning")
    print("Mocked BugSnag noti…
16 0 Open
Modern tooling easy

How to Mock Poetry pyproject.toml Dependencies Sections in Python

Parse and extract dependency lists from Poetry-style pyproject.toml text using Python's standard library.

pyproject poetry toml
Python
from pathlib import Path
import re


def parse_pyproject_dependencies(text):
    """Extract dependencies from a pyproject.toml style text."""
    lines = text.splitlines()
    sections = {
        "dependencies": [],
        "dev": [],
        "optional": [],
    }
    current_section = None

    patterns = {
        …
15 0 Open
Testing & modern typing medium

How to Use Stubs, Fakes, Spies, and Mocks in Python Testing

Implement four types of test doubles — stubs, fakes, spies, and mocks — as subclasses of a PaymentGateway interface to replace real dependencies during testing.

testing mocks stubs
Python
class PaymentGateway:
    def charge(self, amount):
        raise NotImplementedError


class StubPaymentGateway(PaymentGateway):
    """Returns a fixed response without any logic."""
    def charge(self, amount):
        return {"success": True, "transaction_id": "stub-12345"}


class FakePaymentGateway(PaymentGatewa…
12 0 Open
System design patterns medium

How to Mock a Timeout per Dependency Call in Python

This code demonstrates how to simulate and test per-call timeouts for external dependencies using Python's unittest.mock and a simple timing wrapper.

mock timeout unittest
Python
```python
import time
from unittest.mock import Mock, patch

def call_dependency(dependency, timeout):
    start = time.time()
    result = dependency.call()
    elapsed = time.time() - start
    if elapsed > timeout:
        raise TimeoutError(f"Dependency call took {elapsed:.2f}s, exceeding timeout {timeout}s")
    …
14 0 Open
Observability & SRE easy

How to Check Service Readiness Dependencies in Python

This code simulates a readiness check for external dependencies (database, cache, queue) with mock availability data and reports readiness status.

readiness dependencies health-check
Python
import sys
from datetime import datetime


def check_dependencies(config):
    results = []
    for dep, required in config.items():
        available = mock_availability(dep)
        status = "READY" if available >= required else "NOT READY"
        results.append((dep, available, required, status))
    return result…
11 0 Open
Observability & SRE medium

How to Check Uptime with a Synthetic HTTP Mock in Python

Run a mock HTTP server locally and probe it with urllib to measure synthetic uptime and response times, perfect for testing monitoring logic without external dependencies.

uptime http-server monitoring
Python
import http.server
import threading
import time
import urllib.request


class MockHandler(http.server.BaseHTTPRequestHandler):
    def do_GET(self):
        if self.path == "/health":
            self.send_response(200)
            self.send_header("Content-Type", "application/json")
            self.end_headers()
   …
14 0 Open
ML engineering pipelines easy

Load CSV Training Data Without Pandas in Python

This code loads a CSV file into a list of dictionaries using only the standard library, ideal for small ML training data without heavy dependencies.

csv data-loading standard-library
Python
import csv
from pathlib import Path

def load_csv(path):
    """Load CSV file into list of dicts without pandas."""
    rows = []
    with open(path, newline='', encoding='utf-8') as f:
        reader = csv.DictReader(f)
        for row in reader:
            rows.append(dict(row))
    return rows

if __name__ == "__m…
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.