Reference library

Python Code Samples

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

7 matches
Data pipelines & processing easy

How to Implement Incremental Load with Watermark by updated_at in Python

Load only new or changed rows into SQLite by comparing an updated_at timestamp against a stored watermark, returning counts and the new watermark.

incremental-load watermark sqlite
Python
import sqlite3
from datetime import datetime, timedelta


def watermark_incremental_load(db_path, table_name, last_watermark, source_data):
    """Load only rows with updated_at greater than the last watermark."""
    conn = sqlite3.connect(db_path)
    cursor = conn.cursor()

    # Create table if it doesn't exist
  …
11 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…
12 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"…
14 0 Open
Big data & Spark medium

How to Mock a Catalyst Logical Plan in Python

Build a small Python class that mimics Spark Catalyst's logical plan tree for teaching or testing query optimizations.

apache-spark logical-plan catalyst
Python
from typing import Any, Dict, List, Optional


class CatalystLogicalPlan:
    """A minimal mock of Catalyst's logical plan for teaching purposes."""
    
    def __init__(self, node_type: str, **kwargs: Any) -> None:
        self.node_type = node_type
        self.attributes: Dict[str, Any] = kwargs
        self.child…
12 0 Open
Big data & Spark medium

Mock Predicate Pushdown in Python for Big Data Queries

Simulate predicate pushdown by applying filters at the storage layer before materializing rows, showing how big data engines optimize queries.

big-data query-optimization predicate-pushdown
Python
class Query:
    def __init__(self, table, rows):
        self.table = table
        self.rows = rows

    def filter(self, predicate):
        return Query(
            self.table,
            [row for row in self.rows if all(predicate(row) for predicate in predicate)]
        )

    def filter_pushdown(self, predica…
14 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…
14 0 Open
Database scaling & optimization easy

Broadcast a Small Reference Table in Python

Simulates SQL-style broadcasting of a small lookup table against a larger fact table in memory for mockups or load tests.

broadcast mock-data data-engineering
Python
import random

def broadcast_mock(target, source, columns):
    result = {}
    for col in columns:
        if col in target and col in source:
            result[col] = target[col] + [source[col][i % len(source[col])] for i in range(len(target[col]))]
        elif col in target:
            result[col] = target[col]
…
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.