Reference library

Python Code Samples

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

17 matches
OOP & classes medium

Memento Pattern in Python: Save and Restore Object State

Implement the Memento design pattern to snapshot and restore an object's state, demonstrated with a text editor undo feature.

memento design-pattern undo
Python
class TextEditor:
    def __init__(self, text="", cursor_pos=0):
        self.text = text
        self.cursor_pos = cursor_pos

    def type_text(self, new_text):
        self.text += new_text
        self.cursor_pos += len(new_text)

    def move_cursor(self, pos):
        self.cursor_pos = max(0, min(pos, len(self.t…
14 0 Open
Automation & scripting easy

How to Save a VM Snapshot State to a JSON File in Python

Define a dataclass for a VM snapshot and serialize it to a JSON file, then reload it to verify the state.

json dataclass files
Python
import json
from dataclasses import dataclass, asdict
from pathlib import Path


@dataclass
class VMSnapshot:
    name: str
    memory_mb: int
    disk_gb: int
    state: str = "saved"

    def snapshot_to_file(self, path: Path) -> str:
        """Write snapshot state to a JSON file and return the filename."""
       …
13 0 Open
Automation & scripting medium

How to Track GitHub Stars, Forks, and Watchers in Python

Automatically fetch and track stars, forks, and watchers for multiple GitHub repositories, saving snapshots locally as JSON files for historical analysis.

github api automation
Python
import os
import time
import json
import requests
from pathlib import Path
from datetime import datetime

REPOS = [
    "psf/requests",
    "python/cpython",
    "pallets/flask",
]
DATA_DIR = Path("github_metrics")

def fetch_repo_stats(repo):
    url = f"https://api.github.com/repos/{repo}"
    resp = requests.get(ur…
39 0 Open
Data pipelines & processing easy

Generate a Mock CDC Changelog in Python

Simulate a CDC changelog with INSERT, UPDATE, and DELETE operations, timestamps, and record snapshots for testing data pipelines.

cdc changelog mock-data
Python
import json
from datetime import datetime, timedelta


def generate_mock_changelog(records, operations=("INSERT", "UPDATE", "DELETE")):
    """Simulate a CDC changelog from a list of record snapshots."""
    base_time = datetime(2025, 1, 1, 8, 0, 0)
    changelog = []
    for idx, record in enumerate(records):
       …
15 0 Open
Data pipelines & processing easy

How to Merge Incremental Snapshot Upsert Dict in Python

Merge a snapshot dict into a base dict, recursively updating nested dictionaries while preferring snapshot values on conflicts.

dict merge upsert
Python
def merge_upsert(base: dict, snapshot: dict) -> dict:
    """
    Merge a snapshot dict into a base dict, preferring snapshot values 
    on key conflicts (upsert semantics). Nested dicts are merged recursively.
    """
    result = dict(base)
    
    for key, value in snapshot.items():
        if key in result and i…
13 0 Open
Data pipelines & processing easy

How to create a dated snapshot path for a dataset in Python

Generate a versioned directory path combining a base directory, dataset name, and today's date, ready for creating snapshots in data pipelines.

date pathlib datasets
Python
import datetime
import os
from pathlib import Path


def snapshot_path(base_dir: str, dataset_name: str) -> Path:
    """Return a dated snapshot path for a dataset under a base directory."""
    today = datetime.date.today().isoformat()
    return Path(base_dir) / dataset_name / today


if __name__ == "__main__":
    …
15 0 Open
Data pipelines & processing easy

Rollback dataset to previous snapshot pointer in Python

A SnapshotManager class stores timestamped data snapshots and rolls back to the most recent snapshot at or before a target time.

snapshots rollback datetime
Python
from datetime import datetime, timedelta


class SnapshotManager:
    def __init__(self):
        self.snapshots = {}  # timestamp -> data
        self.current_pointer = None

    def create_snapshot(self, data):
        timestamp = datetime.now()
        self.snapshots[timestamp] = data
        self.current_pointer =…
13 0 Open
Cloud + Python medium

How to Mock RDS Snapshot Create and Restore in Python

Mock AWS RDS snapshot creation and restore operations in Python tests using moto and boto3 without hitting real AWS services.

boto3 moto rds
Python
import boto3
from moto import mock_rds


@mock_rds
def create_and_restore_snapshot():
    client = boto3.client("rds", region_name="us-east-1")
    client.create_db_instance(
        DBInstanceIdentifier="my-db",
        DBInstanceClass="db.t3.micro",
        Engine="postgres",
        AllocatedStorage=20,
        Mas…
14 0 Open
Concurrency & performance medium

Profile Memory Usage with tracemalloc Snapshot Diff in Python

Use tracemalloc to take two memory snapshots, compute a diff, and print the top changes (size and count) by line number.

tracemalloc memory-profile performance
Python
import tracemalloc

def profile_memory():
    tracemalloc.start()
    
    # Allocate some objects to track
    data = [i * 2 for i in range(10000)]
    text = "x" * 5000
    nested = {"key": [1, 2, 3], "value": (4, 5)}
    
    # Take first snapshot
    snapshot1 = tracemalloc.take_snapshot()
    
    # Free some mem…
11 0 Open
Testing & modern typing medium

How to Flag Unexpected Diff Changes in Python

Compares two snapshot lists, detects unexpected differences, and returns a flag indicating whether the snapshot should be updated.

diffing snapshot-testing difflib
Python
import difflib

def snapshot_diff(before, after, intentional_changes=None):
    """Compare snapshots and flag only unexpected differences."""
    intentional_changes = intentional_changes or set()
    diff = list(difflib.unified_diff(before, after, lineterm=""))
    has_unexpected = False

    for line in diff:
      …
16 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
System design patterns easy

How to Take Periodic Snapshots of Aggregate State in Python

Build a Python class that accumulates values and periodically captures immutable snapshots of total, count, and average for later analysis.

aggregation snapshots state-management
Python
import time
import random
from collections import defaultdict


class SnapshotAggregator:
    def __init__(self):
        self.total = 0
        self.count = 0
        self.history = []

    def add(self, value):
        self.total += value
        self.count += 1

    def snapshot(self):
        avg = self.total / se…
13 0 Open
Streaming & messaging medium

How to Aggregate Periodic Snapshot Data in Python

Generates mock snapshot data and groups values into periods to compute average aggregates with Python's standard library.

aggregation snapshots streaming
Python
import random
from collections import defaultdict

def snapshot_aggregate(n=10, period=3):
    data = defaultdict(list)
    for i in range(n):
        key = f"item_{i % period}"
        data[key].append(random.randint(1, 100))
    return dict(data)

def aggregate_periodic(snapshots, period=3):
    result = {}
    for …
14 0 Open
Observability & SRE easy

How to Build a Metrics Counter with Increment and Snapshot in Python

A simple dict-backed MetricsCounter class that increments named counters and returns a snapshot of the current values.

metrics counter observability
Python
class MetricsCounter:
    def __init__(self):
        self._metrics = {}

    def increment(self, key, delta=1):
        self._metrics[key] = self._metrics.get(key, 0) + delta

    def snapshot(self):
        return dict(self._metrics)


if __name__ == "__main__":
    counter = MetricsCounter()
    counter.increment("…
13 0 Open
Microservices patterns easy

Mock a Sidecar Logger with Python Metrics

Simulate a sidecar logger that tracks request counts, error rates, and endpoint hits, producing a metrics snapshot.

microservices monitoring metrics
Python
import random
import time
from collections import defaultdict


class SidecarLogger:
    def __init__(self):
        self.metrics = defaultdict(int)
        self.total_requests = 0
        self.error_count = 0

    def log_request(self, endpoint, status_code):
        """Simulate logging a request and updating metrics…
16 0 Open
Big data & Spark medium

How to Create a Mock Iceberg Snapshot Manifest in Python

Build a mock Iceberg snapshot manifest structure with metadata and data entries using Python dictionaries and JSON.

iceberg manifest snapshot
Python
import json
from datetime import datetime, timezone


def create_mock_manifest(snapshot_id: int, file_paths: list[str]) -> dict:
    """Create a mock Iceberg snapshot manifest structure."""
    manifest_file = {
        "manifest_path": f"/warehouse/table/metadata/snap-{snapshot_id}-m0.avro",
        "manifest_length"…
15 0 Open
Production deployment patterns easy

How to Simulate a Packer AMI Build in Python

A simple Python class that mimics a Packer AMI build lifecycle — creates a build object, transitions its state to completed, and prints a JSON snapshot.

packer ami mock
Python
import json


class PackerBuildMock:
    def __init__(self, name, ami_id, region="us-east-1", state="pending"):
        self.name = name
        self.ami_id = ami_id
        self.region = region
        self.state = state

    def build(self):
        if self.state == "pending":
            self.state = "completed"
  …
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.