Reference library

Python Code Samples

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

86 matches
Data pipelines & processing medium

How to Implement Slowly Changing Dimension Type 2 History in Python

Build a type-2 slowly changing dimension pipeline that closes old records and opens new ones when customer data changes.

scd dimension history
Python
from datetime import datetime, timedelta

def apply_scd_type2(records, current_date):
    """Returns active records after inserting new records with type-2 history."""
    history = []
    active = {}

    for record in records:
        key = record["customer_id"]
        if key in active:
            active[key]["end…
13 0 Open
Data pipelines & processing easy

How to List Failed Records in a Dead Letter Queue Mock in Python

A mock Dead Letter Queue stores failed processing records with error details and timestamps, lists them, and exports to JSON.

dead-letter-queue json logging
Python
import json
from datetime import datetime, timedelta
import random


class DeadLetterQueue:
    def __init__(self):
        self.failed_records = []

    def add_failed_record(self, record_id, payload, error_message):
        self.failed_records.append({
            "record_id": record_id,
            "payload": paylo…
13 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 Merge Multiple Data Sources in Python

A beginner-friendly helper that merges lists of dictionaries from multiple sources into one combined list using key filtering.

merge pipelines dicts
Python
import json

def merge_pipeline_data(*data_sources, keys=()):
    """Merge multiple data sources (list of dicts) into a single list of merged dicts.
    
    Args:
        *data_sources: One or more lists of dictionaries.
        keys: Tuple of keys to include from each source (empty means all keys).
    Returns:
    …
14 0 Open
Data pipelines & processing easy

How to Process CSV Data in Python with a Data Helper

Build a beginner-friendly data helper in Python that loads a CSV file, filters rows by a condition, and summarizes numeric fields.

csv data-processing pathlib
Python
import csv
from pathlib import Path

DATA = [
    {"name": "Alice", "score": 88, "passed": True},
    {"name": "Bob", "score": 42, "passed": False},
    {"name": "Carol", "score": 95, "passed": True},
]


def load_csv(file_path: Path) -> list[dict]:
    with file_path.open(newline="", encoding="utf-8") as f:
        r…
13 0 Open
Data pipelines & processing easy

How to Run a Mock Cron Pipeline Scheduler in Python

This code schedules a mock pipeline job to run every 2 seconds and hourly at :30 using the schedule library, then runs pending tasks for 10 seconds.

schedule cron pipeline
Python
import time
import schedule
from datetime import datetime


def run_pipeline():
    print(f"{datetime.now().strftime('%Y-%m-%d %H:%M:%S')} - Pipeline executed")


schedule.every(2).seconds.do(run_pipeline)
schedule.every().hour.at(":30").do(run_pipeline)

print("Scheduler started. Press Ctrl+C to stop.")
end_time = ti…
13 0 Open
Data pipelines & processing easy

How to Sort a List of Dictionaries by Key in Python

A reusable helper function that sorts a list of dictionaries by a specified key, with optional descending order support.

sorting dictionaries data-pipelines
Python
from typing import List

def sort_records(records: List[dict], key: str, descending: bool = False) -> List[dict]:
    """Sort a list of dictionaries by a specified key."""
    return sorted(records, key=lambda record: record[key], reverse=descending)


def demonstrate_sorting() -> None:
    users = [
        {"name": …
12 0 Open
Data pipelines & processing medium

How to Stream a Large JSONL File Line by Line in Python

Process a large JSON-lines file incrementally using streaming techniques to avoid loading the entire file into memory.

streaming jsonl large-files
Python
import json

def process_large_file(filepath, chunk_size=8192):
    """
    Stream a large JSON-lines file line by line, processing each record
    without loading the entire file into memory.
    """
    total_count = 0
    total_sum = 0
    
    with open(filepath, 'r') as f:
        while True:
            chunk = …
13 0 Open
Data pipelines & processing easy

How to Validate Data in a Python Pipeline

A helper module to validate common record types — email, positive integer, and non-empty string list — before processing data in a pipeline.

data-validation pipelines type-checking
Python
from typing import Any, Iterable


def is_valid_email(email: str) -> bool:
    """Basic email check: one '@', no spaces, dot after '@'."""
    if "@" not in email or " " in email:
        return False
    local, _, domain = email.partition("@")
    return bool(local) and "." in domain


def is_positive_int(value: Any)…
12 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

How to route late-arriving data to a side output in Python

Separate late-arriving events from a streaming data batch into a dead-letter side output list using a timestamp threshold.

data pipelines streaming dead-letter
Python
from collections import defaultdict

def late_arriving_side_output(events, late_threshold_ts):
    """
    Mock a streaming pipeline that separates late-arriving data events
    into a side output list (e.g., for dead-letter analysis).

    events: list of (timestamp, data) tuples, timestamps as ints.
    late_thresho…
12 0 Open
Data pipelines & processing easy

Idempotent Pipeline Dedupe by Record ID Set in Python

Filters records against a persistent set of seen IDs, returning only new ones and the updated set for idempotent pipeline processing.

deduplication idempotency pipelines
Python
def dedupe_records(records, seen_ids=None):
    """Return records whose id has not been seen before."""
    if seen_ids is None:
        seen_ids = set()
    unique = []
    for record in records:
        record_id = record.get("id")
        if record_id not in seen_ids:
            seen_ids.add(record_id)
           …
12 0 Open
Data pipelines & processing medium

Map Partition Over Chunks in Python with Multiprocessing and Mock

Process data in chunks across multiple CPU cores using multiprocessing Pool.map, and mock the chunk function to test partitioning behavior without heavy computation.

multiprocessing chunking parallel
Python
from multiprocessing import Pool
from unittest.mock import patch, Mock

def process_chunk(chunk):
    return [x * x for x in chunk]

def map_partition_over_chunks(data, chunk_size, process_func=process_chunk):
    chunks = [data[i:i + chunk_size] for i in range(0, len(data), chunk_size)]
    with Pool() as pool:
     …
12 0 Open
Data pipelines & processing easy

Pipeline stage compose functions left to right in Python

Compose multiple functions into a left-to-right pipeline so each stage receives the output of the previous one.

composition pipeline functional
Python
def compose(*funcs):
    """Compose functions left to right: compose(f, g, h)(x) == h(g(f(x)))"""
    def composed(arg):
        result = arg
        for func in funcs:
            result = func(result)
        return result
    return composed

if __name__ == "__main__":
    def add_one(x):
        return x + 1

    …
16 0 Open
Data pipelines & processing easy

Test a Python Pipeline with Fixture Sample Rows

Test pipeline functions with sample rows provided by a pytest fixture, verifying required keys and value constraints.

pytest fixtures data-pipelines
Python
import pytest


def get_value(data: dict, key: str):
    return data.get(key)


def sample_rows():
    return [
        {"name": "Alice", "age": 30, "city": "London"},
        {"name": "Bob", "age": 25, "city": "Paris"},
        {"name": "Charlie", "age": 35, "city": "Berlin"},
    ]


@pytest.fixture
def sample_data(…
16 0 Open
Data pipelines & processing easy

Trigger a Pipeline When a New File Appears in a Directory

Poll a directory every 0.5 seconds and return the name of the first new file that appears, or None after a timeout.

polling filesystem file-watcher
Python
import time
from pathlib import Path


def watch_for_file(directory: str, interval: float = 0.5, timeout: float = 10.0) -> str | None:
    """Poll a directory and trigger when a new file appears."""
    watch_dir = Path(directory)
    watch_dir.mkdir(exist_ok=True)
    
    known_files = set(watch_dir.iterdir())
    s…
13 0 Open
Data pipelines & processing easy

Validate dict schema at pipeline boundary in Python

This code validates a dictionary against a TypedDict schema at a pipeline boundary, enforcing required fields and types with custom error messages.

validation dict typeddict
Python
from typing import Any, TypedDict


class Person(TypedDict):
    name: str
    age: int
    email: str


def validate_person(data: dict[str, Any]) -> Person:
    errors: list[str] = []

    if not isinstance(data.get("name"), str) or not data["name"].strip():
        errors.append("name must be a non-empty string")
  …
13 0 Open
System design patterns medium

How to Build a Pipe and Filter Text Processing Chain in Python

A functional pipe-and-filter chain that transforms text through uppercase, whitespace normalization, number removal, stopword filtering, and file export.

pipeline text-processing functional
Python
import re
import sys


def pipe_filter_chain(stream):
    def uppercase(text):
        return text.upper()

    def strip_whitespace(text):
        return " ".join(text.split())

    def remove_numbers(text):
        return re.sub(r"\d+", "", text)

    def remove_stopwords(text, stopwords={"the", "and", "of", "in"}):…
15 0 Open
Streaming & messaging easy

Dead Letter Queue Failed Messages List Mock in Python

Implements a simple in-memory dead letter queue to collect, list, and retry failed messages, with JSON serialization for inspection in streaming pipelines.

dead-letter-queue messaging retry
Python
import json
from collections import deque


class Message:
    def __init__(self, message_id, payload, attempts=0):
        self.message_id = message_id
        self.payload = payload
        self.attempts = attempts

    def __repr__(self):
        return f"Message(id={self.message_id}, attempts={self.attempts})"


c…
15 0 Open
Streaming & messaging medium

How to Build a Flow Control Credit Window in Python

A Python class that reserves, confirms, releases, and settles credit to limit message flow and prevent overload in streaming pipelines.

flow-control credit-window streaming
Python
class CreditWindow:
    def __init__(self, max_credit=1000):
        self.max_credit = max_credit
        self.used_credit = 0
        self.pending_credit = 0
    
    def try_reserve(self, amount):
        available = self.max_credit - self.used_credit - self.pending_credit
        if available >= amount:
           …
14 0 Open
Streaming & messaging easy

How to Build a Mock Change Data Capture Event Stream in Python

Generate a deterministic list of mock CDC events with event IDs, stream positions, payloads, and timestamps for testing streaming pipelines.

cdc mock event-stream
Python
from itertools import count
from random import choice, randint, seed
from datetime import datetime, timedelta

seed(42)  # Make output deterministic
event_types = ["INSERT", "UPDATE", "DELETE"]
table_names = ["users", "orders", "products", "payments"]
counter = count(1)

def mock_cdc_event(stream_index: int) -> dict:
…
12 0 Open
Streaming & messaging medium

How to Mock a Kafka Producer Batch Send in Python

Simulate a Kafka producer in Python that sends batched JSON events with mock partitions and latency for testing streaming pipelines without a real broker.

kafka mock streaming
Python
import json
import random
import time
from datetime import datetime


class MockKafkaProducer:
    def __init__(self, topic):
        self.topic = topic
        self.sent_messages = []

    def send(self, value, key=None):
        message = {
            "topic": self.topic,
            "key": key,
            "value"…
13 0 Open
Streaming & messaging medium

Mock Watermark Late Event Side Output in Python

Simulates watermarking in a streaming pipeline by classifying events as on-time or late using timestamps and delays.

watermark streaming side output
Python
from datetime import datetime, timedelta
from typing import List, Tuple


def watermark_mock(
    events: List[Tuple[datetime, str]], watermark_delay: timedelta, max_delay: timedelta
) -> Tuple[List[Tuple[datetime, str]], List[Tuple[datetime, str]]]:
    """Simulate watermarking: events arriving on time vs. late by ch…
11 0 Open
Caching & Redis medium

How to Mock Redis Pipeline Batch Commands in Python

Create a lightweight MockRedis class that simulates Redis pipeline batching with SET, GET, and DELETE operations for testing without a live server.

redis pipeline mock
Python
import redis
import time


class MockRedis:
    def __init__(self):
        self.data = {}

    def pipeline(self):
        return MockPipeline(self)

    def execute(self, commands):
        results = []
        for cmd in commands:
            op, args = cmd[0], cmd[1:]
            if op == "SET":
                se…
14 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.