Mock RDD in Python: Simulate Spark RDD Lazy Transformations

Simulate Apache Spark RDD behavior in Python with lazy maps, filters, partitions, and a collect action.

Medium Python 3.9+ Aug 9, 2026 Big data & Spark 13 views 0 copies

Python code

52 lines
Python 3.9+
import random

def mock_rdd(data, num_slices=2):
    """
    A simple simulation of Spark RDD behavior with lazy evaluation,
    transformations, and an action.
    """
    class SimpleRDD:
        def __init__(self, data, num_slices=2):
            self.data = data
            self.num_slices = num_slices
            self.transformations = []

        def map(self, func):
            new_rdd = SimpleRDD(self.data, self.num_slices)
            new_rdd.transformations = self.transformations + [("map", func)]
            return new_rdd

        def filter(self, func):
            new_rdd = SimpleRDD(self.data, self.num_slices)
            new_rdd.transformations = self.transformations + [("filter", func)]
            return new_rdd

        def _slices(self):
            random.shuffle(self.data)
            slice_size = max(1, len(self.data) // self.num_slices)
            return [self.data[i:i + slice_size] for i in range(0, len(self.data), slice_size)]

        def collect(self):
            result = self.data
            for op, func in self.transformations:
                if op == "map":
                    result = [func(x) for x in result]
                elif op == "filter":
                    result = [x for x in result if func(x)]
            return result

    return SimpleRDD(data, num_slices)


if __name__ == "__main__":
    original_list = list(range(1, 11))

    rdd = mock_rdd(original_list, num_slices=3)
    mapped = rdd.map(lambda x: x * 2)
    filtered = mapped.filter(lambda x: x > 10)
    sliced = filtered._slices()

    print("Original:", original_list)
    print("Mapped (x*2):", mapped.collect())
    print("Filtered (x>10):", filtered.collect())
    print("Number of slices:", len(sliced))

Output

stdout
Original: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Mapped (x*2): [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
Filtered (x>10): [12, 14, 16, 18, 20]
Number of slices: 3

How it works

This class models Spark's RDD lazy evaluation: map and filter only record transformations without executing them. The actual computation happens when collect() is called, emulating Spark's action trigger. _slices() simulates partitioning by shuffling data and splitting it into contiguous chunks. Transformations chain by copying the transformation history into a new RDD instance, mirroring Spark's immutable RDD design. This pattern helps understand core distributed data concepts without a cluster.

Common mistakes

  • Forgetting that transformations are lazy and don't run until `collect()`.
  • Mutating the original list during `_slices()` without copying, breaking reproducibility.
  • Assuming slice count always equals `num_slices` when data is smaller than slices.

Variations

  1. Add `reduce()` or `take(n)` actions to mimic more Spark operations.
  2. Use tuple labels (e.g., `('map', func)`) to replay the DAG from the original data.

Real-world use cases

  • Teaching/learning Spark RDD concepts in a local environment without installing PySpark.
  • Unit-testing distributed data pipelines by mocking RDD behavior for small datasets.
  • Prototyping map/filter logic before deploying it to a real Spark cluster.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Big data & Spark

Related tutorials and quizzes for this topic.