Reference library

Python Code Samples

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

68 matches
Modern tooling easy

How to Parse Taskfile YAML in Python

Load a Taskfile.yaml with PyYAML and simulate task execution by returning each task's commands.

yaml taskfile pyyaml
Python
import yaml
from pathlib import Path

def load_taskfile(taskfile_path: str) -> dict:
    """Load and parse a Taskfile.yaml file into a dict."""
    data = Path(taskfile_path).read_text()
    return yaml.safe_load(data)

def run_task(taskfile: dict, task_name: str) -> dict:
    """Simulate running a task by returning i…
14 0 Open
Modern tooling easy

How to Use prompt_toolkit Autocomplete in Python

Demonstrates an interactive command-line prompt with autocomplete using prompt_toolkit's WordCompleter and a mock dataset.

cli autocomplete prompt-toolkit
Python
from prompt_toolkit import prompt
from prompt_toolkit.completion import WordCompleter

def main():
    """Demo of prompt_toolkit autocomplete with a mock dataset."""
    # A simple mock "database" of programming languages
    languages = [
        "Python", "Java", "JavaScript", "TypeScript", "C++", "C#",
        "Go"…
15 0 Open
Modern tooling easy

Makefile Targets for lint, test, and build in Python

This Python script defines common Makefile targets (lint, test, build) as subprocess commands, printing each target's command and executing them with error checking.

subprocess makefile tooling
Python
import subprocess

TARGETS = {
    "lint": ["ruff", "check", "."],
    "test": ["pytest", "-q"],
    "build": ["python", "-m", "build"],
}


def run(target: str) -> None:
    if target not in TARGETS:
        raise ValueError(f"Unknown target: {target}")
    print(f"Running {target}...")
    subprocess.run(TARGETS[tar…
14 0 Open
Modern tooling easy

Mock pdm build and publish in Python

Simulate pdm build and publish commands with unittest.mock to test packaging workflows without triggering real builds or uploads.

pdm mock unittest
Python
from unittest.mock import Mock, patch

import pdm


def build_package() -> str:
    """Simulate building a package with pdm."""
    build_mock = Mock(return_value="dist/mypackage-0.1.0-py3-none-any.whl")
    with patch.object(pdm, "build", build_mock):
        result = pdm.build()
    return result


def publish_packa…
12 0 Open
Testing & modern typing medium

How to Use Hypothesis Strategies for Lists of Text in Python

Generate random lists of non-empty strings with Hypothesis and verify that joining them with a comma-and-space separator meets expected length and containment invariants.

hypothesis property-based-testing strategies
Python
from hypothesis import given, strategies as st
from hypothesis import example


@given(st.lists(st.text(min_size=1, max_size=10), min_size=1, max_size=5))
def test_joined_string_length(items):
    """Each text is non-empty; a joined string should be at least as long
    as the number of items (separator adds character…
13 0 Open
System design patterns medium

How to Implement CQRS with Separate Read and Write Models in Python

Implements Command Query Responsibility Segregation (CQRS) by splitting data into separate write and read models with dedicated repositories, using dataclasses for structure.

cqrs dataclasses repositories
Python
from dataclasses import dataclass, field
from typing import List, Dict, Optional


@dataclass
class OrderWriteModel:
    order_id: int
    customer: str
    items: List[str] = field(default_factory=list)

    def add_item(self, item: str) -> None:
        self.items.append(item)


@dataclass
class OrderReadModel:
    …
14 0 Open
System design patterns easy

How to Implement a Data Helper Class in Python

Build a beginner-friendly DataHelper class using dataclasses and key system design patterns like Command, Strategy, and Map.

dataclass data-helper design-patterns
Python
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional


@dataclass
class DataHelper:
    """A beginner-friendly data utility with common system design patterns."""
    data: List[Dict[str, Any]] = field(default_factory=list)

    def add_record(self, r…
13 0 Open
Caching & Redis easy

How to Iterate Redis Keys with SCAN in Python

Iterate all Redis keys matching a pattern using the SCAN command with a mock client to simulate pagination.

redis scan keys
Python
import redis

def scan_keys(client, pattern="*", count=10):
    keys = []
    cursor = 0
    while True:
        cursor, batch = client.scan(cursor=cursor, match=pattern, count=count)
        keys.extend(batch)
        if cursor == 0:
            break
    return keys

if __name__ == "__main__":
    # Mock Redis clien…
15 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
Caching & Redis medium

How to Mock a Redis Transaction with MULTI/EXEC in Python

A minimal in-memory mock of Redis MULTI/EXEC transactions that queues commands and applies them atomically on EXEC.

redis mock transactions
Python
class RedisTransactionMock:
    def __init__(self):
        self.data = {}
        self.queue = []
        self.in_transaction = False

    def multi(self):
        self.in_transaction = True
        self.queue = []
        return "OK"

    def set(self, key, value):
        if self.in_transaction:
            self.qu…
14 0 Open
Caching & Redis easy

How to Use Redis HSET and HGET in Python

This code demonstrates how to store and retrieve hash data in Redis using Python's redis library with HSET, HGET, HGETALL, and HDEL commands.

redis hset hget
Python
import redis

# Connect to Redis (adjust host/port as needed)
r = redis.Redis(host='localhost', port=6379, db=0, decode_responses=True)

# Clear any existing data for demonstration
r.delete('user:1')

# HSET - Store a hash
r.hset('user:1', mapping={'name': 'Alice', 'age': 30, 'city': 'New York'})

# HGET - Retrieve a …
12 0 Open
Caching & Redis medium

How to mock Redis geospatial commands (GEOADD) in Python

Implement a lightweight Python mock of Redis geospatial commands (GEOADD, GEODIST, GEOSEARCH) using the Haversine formula for testing without a Redis server.

redis geospatial haversine
Python
import math
import heapq


class MockRedisGeo:
    def __init__(self):
        self.members = {}

    def geoadd(self, key, longitude, latitude, member):
        if key not in self.members:
            self.members[key] = {}
        self.members[key][member] = (longitude, latitude)

    def geodist(self, key, member1,…
13 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
Caching & Redis hard

Mock Redis Lua Script Atomic Execution in Python

A MockRedis class that simulates atomic Lua script execution via EVALSHA with a simplified parser for basic commands.

redis lua mock
Python
import hashlib

class MockRedis:
    def __init__(self):
        self.data = {}
        self.scripts = {}

    def script_load(self, script):
        sha = hashlib.sha1(script.encode()).hexdigest()
        self.scripts[sha] = script
        return sha

    def evalsha(self, sha, keys, args):
        if sha not in self…
16 0 Open
Caching & Redis easy

Redis GET SET EX TTL mock in Python

A thread-safe Python class mimicking Redis GET, SET with EX, and TTL commands for in-memory testing.

redis mock ttl
Python
import time
import threading
from typing import Optional, Callable


class RedisTTLMock:
    def __init__(self):
        self._store: dict[str, tuple[str, float]] = {}
        self._lock = threading.Lock()

    def set(self, key: str, value: str, ex: Optional[int] = None) -> bool:
        expiry = time.time() + ex if …
13 0 Open
Caching & Redis easy

Redis INCR DECR Counter Mock in Python

Simulate Redis INCR and DECR commands with a Python class to test counter logic without a live Redis server.

redis counter mock
Python
class RedisCounter:
    def __init__(self):
        self._store = {}

    def incr(self, key: str, amount: int = 1) -> int:
        if key not in self._store:
            self._store[key] = 0
        self._store[key] += amount
        return self._store[key]

    def decr(self, key: str, amount: int = 1) -> int:
     …
16 0 Open
Caching & Redis easy

Redis LPUSH RPOP List Queue Mock in Python

Implements a FIFO queue using Redis lists with LPUSH and RPOP commands, simulating task processing in Python.

redis queue fifo
Python
import redis
import time

r = redis.Redis(host='localhost', port=6379, db=0)
queue_key = 'task_queue'

# Push tasks onto the left side (LPUSH)
r.lpush(queue_key, 'task1')
r.lpush(queue_key, 'task2')
r.lpush(queue_key, 'task3')

# Mock processing: pop from the right side (RPOP) — FIFO order
while r.llen(queue_key) > 0:…
13 0 Open
Microservices patterns medium

CQRS with Separate Read and Write Repositories in Python

Implement CQRS in Python with separate write and read repositories, using commands for mutations and frozen DTOs for queries.

cqrs repositories microservices
Python
from dataclasses import dataclass
from typing import Dict, List, Optional


# --- Write side: commands mutate state ---
@dataclass
class CreateUserCommand:
    id: int
    name: str


class UserWriteRepository:
    def __init__(self) -> None:
        self._store: Dict[int, Dict[str, object]] = {}

    def create(self,…
14 0 Open
Production deployment patterns easy

Docker healthcheck CMD mock in Python

Runs a subprocess to curl a health endpoint and returns exit code 0 when healthy, 1 when unhealthy, mimicking a Docker HEALTHCHECK command.

docker healthcheck subprocess
Python
import subprocess
import sys


def run_healthcheck() -> int:
    result = subprocess.run(["curl", "-fsS", "http://localhost:8080/health"], capture_output=True, text=True)
    if result.returncode == 0:
        print("healthy")
        return 0
    print("unhealthy", file=sys.stderr)
    return 1


if __name__ == "__ma…
15 0 Open
Production deployment patterns easy

How to Mock Terraform Plan and Apply in Python

This code provides a lightweight Python mock of Terraform's plan and apply commands, helping you simulate infrastructure changes without real cloud resources.

terraform mock simulation
Python
class MockTerraform:
    def __init__(self):
        self.plans = [
            {"id": 1, "action": "create", "resource": "aws_instance.web"},
            {"id": 2, "action": "update", "resource": "aws_s3_bucket.data"},
            {"id": 3, "action": "destroy", "resource": "aws_iam_user.legacy"}
        ]
        sel…
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.