Reference library

Python Code Samples

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

8 matches
Automation & scripting easy

Resize Disk Partitions in Python (Mock Script)

A mock disk partition resize script that uses dataclasses to model partitions, validate new sizes, and output the updated layout as JSON.

disk partition dataclass
Python
#!/usr/bin/env python3
"""Mock script to demonstrate disk partition resize logic."""
import json
from dataclasses import dataclass
from typing import Dict


@dataclass
class Partition:
    name: str
    size_gb: int
    mount_point: str

    def to_dict(self) -> Dict[str, object]:
        return {
            "name": …
16 0 Open
Data pipelines & processing easy

How to Compress Pipeline Output Gzip Per Partition in Python

Compress each partition of pipeline output into a separate gzip file and verify the compressed data by reading it back.

gzip compression pipeline
Python
import gzip
import io
import random
from pathlib import Path


def compress_partition(partition_data: list[str], output_path: Path) -> int:
    """Compress a partition of data to a gzip file, returns bytes written."""
    with gzip.open(output_path, 'wt', encoding='utf-8') as f:
        f.writelines(partition_data)
  …
13 0 Open
Streaming & messaging easy

How to Mock Kafka Topic Partitions with a Python dict of lists

Mocks a Kafka topic and its partitions using a defaultdict of lists to simulate message production, consumption, and per-partition counts.

kafka mock partitions
Python
from collections import defaultdict

class KafkaTopicPartitionMock:
    """A simple mock for Kafka topic-partition assignment using dict of lists."""

    def __init__(self, topic):
        self.topic = topic
        self.partitions = defaultdict(list)  # partition_id -> list of messages

    def produce(self, message…
15 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

How to Mock a Kafka Rebalance Listener in Python

Simulate Kafka consumer rebalance callbacks (on_partitions_revoked and on_partitions_assigned) with a mock consumer to test listener logic.

kafka rebalance mocking
Python
import time
from collections import defaultdict


class MockKafkaConsumer:
    def __init__(self):
        self.assignments = defaultdict(list)
        self.rebalances = 0

    def assign(self, partitions):
        self.rebalances += 1
        self.assignments.clear()
        for partition in partitions:
            s…
15 0 Open
Big data & Spark easy

How to Mock Partition Pruning in Python

A dataclass-based mock that filters partitions by year and month to emulate Spark's partition pruning logic.

spark partition dataclass
Python
from dataclasses import dataclass
from typing import List


@dataclass(frozen=True)
class Partition:
    id: int
    year: int
    month: int


class PartitionPruner:
    """Mock partition pruning: only keep partitions that match the filter."""
    def __init__(self, partitions: List[Partition]):
        self._partiti…
15 0 Open
Big data & Spark medium

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.

spark rdd big-data
Python
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
           …
13 0 Open
Big data & Spark easy

Partition Data by Hash Key Mod N in Python

Returns a partition index for a string key by hashing it with MD5 and taking modulo N, then groups sample keys into partitions.

hashing partitioning hashlib
Python
import hashlib


def partition_key(key: str, num_partitions: int) -> int:
    """Return partition index for key using MD5 hash mod N."""
    digest = hashlib.md5(key.encode()).hexdigest()
    return int(digest, 16) % num_partitions


if __name__ == "__main__":
    keys = ["alice", "bob", "carol", "dave", "eve"]
    nu…
12 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.