Reference library

Python Code Samples

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

22 matches
Comprehensions & generators medium

Build a Generator Pipeline in Python: Filter Then Map

Create a lazy data pipeline by chaining generator functions that read, filter, map, and write data step by step.

generators pipeline lazy-evaluation
Python
def read_data():
    return ["a", "bb", "ccc", "dd", "eeeee", "f"]


def filter_short(words):
    return (word for word in words if len(word) >= 2)


def map_to_upper(words):
    return (word.upper() for word in words)


def write_data(words):
    for word in words:
        print(word)


if __name__ == "__main__":
   …
12 0 Open
AI & LLM integration patterns medium

How to Build a Data Helper for LLM Prompts in Python

A beginner-friendly helper class that flattens nested dictionaries, formats prompt templates, and safely parses JSON for AI/LLM pipelines.

llm prompt-engineering data-prep
Python
import json
from typing import Any, Dict, List, Optional


class DataHelper:
    """Simple helper class for working with data in AI/LLM pipelines."""
    
    def __init__(self, data: Optional[Dict[str, Any]] = None) -> None:
        self.data = data or {}
    
    def flatten(self, prefix: str = "") -> Dict[str, Any]…
17 0 Open
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 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 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
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 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 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
Big data & Spark medium

How to Implement a Mock MapReduce for Word Count in Python

Simulates a MapReduce word count pipeline with mapper, shuffle, and reducer phases using Python dicts and standard library modules.

mapreduce word-count big-data
Python
from collections import defaultdict
import re

def mapper(text):
    """Split text into words and emit (word, 1) pairs."""
    words = re.findall(r'\b\w+\b', text.lower())
    return [(word, 1) for word in words]

def reducer(pairs):
    """Group word-count pairs and sum counts."""
    counts = defaultdict(int)
    fo…
15 0 Open
Big data & Spark medium

How to Simulate a MapReduce Mock with Combine Phase in Python

Simulates a MapReduce pipeline with a combiner that aggregates local counts per reducer to reduce network and compute overhead.

mapreduce combiner hadoop
Python
from collections import defaultdict

def map_phase(lines):
    intermediate = defaultdict(list)
    for line in lines:
        for word in line.strip().lower().split():
            intermediate[word].append(1)
    return dict(intermediate)

def combine_phase(intermediate, num_reducers=3):
    combined = defaultdict(li…
14 0 Open
Big data & Spark medium

Lazy Evaluation Transform Lineage Mock in Python

Build a mock lineage tracker for data transforms using lazy evaluation and function wrappers in Python.

lazy-evaluation lineage decorator
Python
import functools


def lazy_transform(pipeline):
    """Build a mock lineage tracker using lazy evaluation."""
    lineage = []

    def wrap(func):
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            result = func(*args, **kwargs)
            lineage.append({"transform": func.__name__, "a…
16 0 Open
ML engineering pipelines medium

How to Build a Mock ML Pipeline with Prefect in Python

Create a lightweight Prefect flow with mock preprocessing, training, and evaluation tasks to prototype an ML pipeline end-to-end.

prefect machine-learning pipeline
Python
from prefect import task, flow
from datetime import datetime


@task
def preprocess_data(raw_value: float) -> float:
    """Mock preprocessing: normalize the input value."""
    return raw_value / 100.0


@task
def train_model(features: float) -> dict:
    """Mock training: return a fake model artifact."""
    return …
12 0 Open
ML engineering pipelines medium

How to Build an sklearn Pipeline with ColumnTransformer in Python

A mock example showing how to chain preprocessing and a regression model into a single sklearn Pipeline, scaling numeric features and one-hot encoding categorical features with ColumnTransformer.

sklearn pipeline columntransformer
Python
import numpy as np
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.pipeline import Pipeline
from sklearn.linear_model import LinearRegression

# Mock dataset
X = np.array([[1, 'red'], [2, 'blue'], [3, 'red'], [4, 'green'], [5, 'blue']], dtype=o…
13 0 Open
ML engineering pipelines medium

How to Detect Data Drift with PSI in Python

Calculate the Population Stability Index (PSI) in Python to compare expected vs actual distributions and detect data drift in machine learning pipelines.

data drift psi monitoring
Python
import numpy as np

def calculate_psi(expected, actual, buckets=10):
    """Calculate Population Stability Index (PSI) between two distributions."""
    # Create bucket edges based on expected distribution percentiles
    edges = np.percentile(expected, np.linspace(0, 100, buckets + 1))
    edges[-1] = np.inf  # Ensur…
13 0 Open
ML engineering pipelines medium

How to Mock Kedro Pipeline Nodes in Python

Create a modular Kedro pipeline with node functions, namespacing, and input/output mapping to mock pipeline execution locally.

kedro pipeline modular
Python
from kedro.pipeline import Pipeline, node
from kedro.pipeline.modular_pipeline import pipeline as modular_pipeline


def preprocess(data: list) -> list:
    """Clean data by removing None values."""
    return [item for item in data if item is not None]


def transform(data: list) -> list:
    """Add 1 to each numeric…
15 0 Open
ML engineering pipelines medium

How to Mock a Kubeflow Pipeline in Python

Build a minimal in-memory mock of a Kubeflow pipeline DAG using dataclasses and OrderedDict to chain component functions.

kubeflow pipelines mlops
Python
from typing import Dict, Any
from dataclasses import dataclass, field
from collections import OrderedDict


@dataclass
class KubeflowPipelineMock:
    """A minimal mock of a Kubeflow pipeline DAG."""
    name: str
    components: OrderedDict[str, callable] = field(default_factory=OrderedDict)

    def add_component(se…
14 0 Open
ML engineering pipelines medium

How to Stage ML Model Workflows with Python Classes

Defines a Stage class to model ML pipeline stages with variants and mocks, printing grammar for Model, Staging, and Production stages.

ml-pipelines stages model-deployment
Python
class Stage:
    def __init__(self, name):
        self.name = name
        self.mocks = []
        self.variants = []

    def add_mock(self, mock_name):
        self.mocks.append(mock_name)

    def add_variant(self, variant_name, productions=()):
        self.variants.append((variant_name, list(productions)))

    …
12 0 Open
ML engineering pipelines medium

How to mock an artifact store with local paths in Python for ML pipelines

Create a temporary local artifact store with dummy files and metadata to test ML pipeline code without real storage.

ml-pipelines mock tempfile
Python
import tempfile
from pathlib import Path
import json


def create_artifact_store_mock(base_path: Path = None):
    """Create a local artifact store mock directory structure."""
    if base_path is None:
        base_path = Path(tempfile.mkdtemp())

    store_layout = {
        "artifacts": [
            {"name": "mode…
13 0 Open
ML engineering pipelines medium

Mock a Flyte ML workflow in Python

Build a lightweight mock of a Flyte ML pipeline with dataclasses and a simple execution loop that passes outputs between tasks.

flyte ml-pipeline dataclass
Python
from dataclasses import dataclass, field
from typing import List, Dict, Optional
import time


@dataclass
class FlyteTask:
    name: str
    inputs: Dict = field(default_factory=dict)
    outputs: Dict = field(default_factory=dict)

    def run(self) -> Dict:
        time.sleep(0.1)  # simulate work
        return sel…
16 0 Open
ML engineering pipelines medium

Training Pipeline Orchestration Mock DAG in Python

Build a mock DAG orchestrator that runs ML pipeline stages in dependency order using topological sorting (Kahn's algorithm).

dag pipeline topological-sort
Python
from collections import deque
from dataclasses import dataclass, field


@dataclass
class DAGNode:
    name: str
    task: callable
    dependencies: list[str] = field(default_factory=list)


class MockDAG:
    def __init__(self, nodes: list[DAGNode]):
        self.nodes = {n.name: n for n in nodes}
        self.execu…
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.