Reference library

Python Code Samples

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

8 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…
14 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
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
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
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.