Reference library

Python Code Samples

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

64 matches
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 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 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
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 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
Caching & Redis easy

How to use Redis MGET MSET pipeline in Python

Store multiple keys atomically and read them efficiently with Redis MSET/MGET, then batch commands with a pipeline to cut round trips.

redis mget mset
Python
import redis  # v4.x+ required

r = redis.Redis(host="localhost", port=6379, db=0, decode_responses=True)

# Sample data to store
r.flushdb()
data = {"name": "Alice", "age": "30", "city": "Berlin"}

# MSET: store multiple key-value pairs in one command
r.mset(data)

# MGET: fetch multiple keys in one round trip
keys =…
15 0 Open
Big data & Spark easy

How to Implement MapReduce Word Count in Python Using a Dict

Simulate a MapReduce word count pipeline in Python with a mock dict, splitting text into words, shuffling, and reducing to frequency counts.

mapreduce word-count dictionary
Python
def map_reduce_word_count(text: str) -> dict:
    """Simulate a MapReduce pipeline to count word frequencies."""
    # MAP phase: split into words and emit (word, 1) pairs
    mapped = []
    for word in text.lower().split():
        # Clean word of punctuation
        clean_word = ''.join(char for char in word if cha…
16 0 Open
Big data & Spark easy

How to Mock a User-Defined Function (UDF) in Python

Wrap a real UDF implementation with call logging to simulate and track invocations in a data pipeline.

udf mock testing
Python
from typing import Any, Callable


# Mock a user-defined function (UDF) that was previously complex or external
def mock_udf(name: str, implementation: Callable[..., Any], *, calls: list[Any]) -> Callable[..., Any]:
    """Wrap a real implementation with call logging to simulate a UDF."""
    def wrapper(*args: Any, *…
13 0 Open
Big data & Spark easy

How to Truncate Lineage Back to a Checkpoint in Python

Walks a linked list of lineage nodes upward to find the nearest checkpoint and returns that node, truncating the lineage.

lineage checkpoint linked-list
Python
class LineageNode:
    def __init__(self, name, parent=None, checkpoint=None):
        self.name = name
        self.parent = parent
        self.checkpoint = checkpoint

    def truncate_at_checkpoint(self):
        """Truncate lineage back to the last checkpoint."""
        current = self
        while current.check…
16 0 Open
ML engineering pipelines easy

Build a Data Helper Class in Python for ML Pipelines

A beginner-friendly Python class that summarizes, filters, and exports ML dataset rows as JSON.

data-helper ml-pipeline json
Python
from typing import List, Dict, Any
import json

class DataHelper:
    """Beginner-friendly helpers for ML data pipelines."""
    
    def __init__(self, data: List[Dict[str, Any]]):
        self.data = data
        self.keys = list(data[0].keys()) if data else []
    
    def summary(self) -> Dict[str, Any]:
        "…
15 0 Open
ML engineering pipelines easy

How to Build a Data Validation Schema in Python

Create a lightweight validation schema using dataclasses and lambda validators to check fields in a dictionary.

validation dataclasses ml-pipelines
Python
import re
from dataclasses import dataclass, field
from typing import Any, Callable


@dataclass
class Field:
    name: str
    validator: Callable[[Any], bool]
    required: bool = True

    def validate(self, value: Any) -> bool:
        if not self.required and value is None:
            return True
        return …
12 0 Open
ML engineering pipelines easy

How to Build a Mock Offline Feature Store in Python

Build an in-memory mock of an offline feature store with a dict-based FeatureStore class for storing and retrieving ML features by entity ID.

feature-store ml-pipeline mock
Python
from datetime import datetime
from collections import defaultdict


class FeatureStore:
    """Simple in-memory mock of an offline feature store."""

    def __init__(self):
        self._features = defaultdict(dict)

    def ingest(self, entity_id, feature_name, value, timestamp=None):
        ts = timestamp or datet…
14 0 Open
ML engineering pipelines easy

How to Build a Mock TFX Pipeline in Python

Simulate a TFX-style ML pipeline with simple Python functions to understand component orchestration, data flow, and artifact passing.

tfx ml-pipeline orchestration
Python
# Mock TFX pipeline to illustrate component orchestration

def CsvExampleGen(data_path):
    """Mock component: Simulates reading CSV data."""
    print(f"ExampleGen: Reading from {data_path}")
    return {"records": 100, "name": "examples"}

def StatisticsGen(example_artifact):
    """Mock component: Simulates genera…
15 0 Open
ML engineering pipelines easy

How to Build a Simple ML Pipeline with ZenML in Python

Build a mock machine learning pipeline with ZenML steps for data loading, training, and evaluation, and run it to print the final accuracy.

zenml ml pipeline
Python
from zenml import pipeline, step


@step
def load_data() -> dict:
    """Simulate loading data from a source."""
    return {"accuracy": 0.0, "loss": 1.0}


@step
def train_model(data: dict) -> dict:
    """Simulate training a model."""
    data["accuracy"] = 0.95
    data["loss"] = 0.1
    return data


@step
def eva…
13 0 Open
ML engineering pipelines easy

How to Create a Mock Metaflow Flow in Python

Build a minimal Metaflow flow with two sequential steps that pass data between them using instance attributes.

metaflow ml-pipelines workflow
Python
from metaflow import FlowSpec, step, current


class MockFlow(FlowSpec):
    """A minimal Metaflow flow to demonstrate basic steps and branching."""

    @step
    def start(self):
        self.category = "mock"
        print(f"Start step for {self.category} flow")
        self.next(self.process)

    @step
    def pr…
15 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.