Reference library

Python Code Samples

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

58 matches
Cloud + Python easy

Create a Data Helper Class for Beginners in Python

A simple Python class to read and write JSON and CSV files from a local directory, ideal for automating data workflows in cloud environments.

json csv file-io
Python
import json
from pathlib import Path

class DataHelper:
    """Simple helper for reading and writing common data files."""
    
    def __init__(self, directory="data"):
        self.directory = Path(directory)
        self.directory.mkdir(exist_ok=True)
    
    def save_json(self, filename, data):
        filepath =…
14 0 Open
Cloud + Python easy

How to Create a JSON Data Helper in Python

A beginner-friendly DataHelper class that safely reads and writes JSON files with timestamps to a local data directory.

json files data-helper
Python
from datetime import datetime
from pathlib import Path
import json


class DataHelper:
    """Simple helper for reading/writing JSON files safely."""

    def __init__(self, base_dir="data"):
        self.base_dir = Path(base_dir)
        self.base_dir.mkdir(exist_ok=True)

    def save(self, filename, data):
        …
12 0 Open
Modern tooling easy

How to Create a Mock Virtualenv with an Activation Script in Python

Create a mock virtualenv directory with a generated bash activation script using Python's standard library.

virtualenv mock subprocess
Python
import os
import subprocess
import sys
from pathlib import Path


def mock_virtualenv(name: str = "myenv") -> Path:
    """Create a mock virtualenv directory and activation script."""
    env_dir = Path(name)
    env_dir.mkdir(exist_ok=True)
    (env_dir / "bin").mkdir(exist_ok=True)

    activate_script = f"""#!/bin/…
13 0 Open
Testing & modern typing easy

How to Share Fixtures Across Tests with pytest conftest

Learn how to define pytest fixtures in conftest.py and control their scope (function, module, session) so every test in a directory reuses the same setup and teardown.

pytest fixtures conftest
Python
import pytest

@pytest.fixture
def sample_data():
    """Simple fixture available to all tests in this directory."""
    return {"name": "Alice", "age": 30}

@pytest.fixture(scope="session")
def session_data():
    """Fixture created once per test session."""
    return {"session_id": 12345}

@pytest.fixture(scope="mo…
13 0 Open
Testing & modern typing easy

How to Use the pytest tmp_path Fixture for Temporary Directories

Use pytest's built-in tmp_path fixture to create a unique temporary directory per test for clean file I/O testing.

pytest tmp_path fixtures
Python
import pytest


def test_write_and_read_file(tmp_path):
    # tmp_path is a pytest fixture that provides a temporary directory
    # unique to each test invocation
    data_file = tmp_path / "data.txt"
    data_file.write_text("hello world")
    assert data_file.read_text() == "hello world"


def test_multiple_tmp_pat…
15 0 Open
System design patterns easy

Create a Data Helper Class in Python

A reusable DataHelper class that saves and loads JSON and CSV files from a configurable base directory, with automatic header detection for CSV.

data-helper json csv
Python
import json
import csv
from pathlib import Path

class DataHelper:
    def __init__(self, base_path="."):
        self.base_path = Path(base_path)
        self.base_path.mkdir(exist_ok=True)

    def save_json(self, data, filename):
        path = self.base_path / filename
        with open(path, "w") as f:
          …
15 0 Open
Big data & Spark easy

How to Mock a File Source Watch Directory in Python

Poll a directory for new files and log changes, simulating a watch directory for data ingestion patterns.

file-watching polling etl
Python
import os
import time
from pathlib import Path


def watch_directory(dir_path: str, poll_interval: float = 1.0, max_iterations: int = 5):
    """
    Mock a file-source watch directory by polling for changes.
    Returns new files detected during each poll cycle.
    """
    directory = Path(dir_path)
    directory.mk…
15 0 Open
Database scaling & optimization easy

How to mock directory-based sharding in Python

Simulates distributing files into logical shards using a deterministic hash of each filename, mocking how a database might shard rows across nodes.

sharding hash partitioning
Python
import os
import hashlib
from collections import defaultdict
from pathlib import Path


def get_shard_for_key(key: str, num_shards: int) -> int:
    """Return a deterministic shard index (0..num_shards-1) for a key."""
    digest = hashlib.md5(key.encode('utf-8')).hexdigest()
    return int(digest, 16) % num_shards


…
14 0 Open
Production deployment patterns easy

How to Build a Simple Data Helper Class in Python

A beginner-friendly DataHelper class that safely saves and loads JSON files with automatic directory creation, perfect for production-style file handling.

json file-handling data-persistence
Python
from pathlib import Path
import json


class DataHelper:
    """Simple production-style helper for loading and saving JSON data."""

    def __init__(self, data_dir="data"):
        self.data_dir = Path(data_dir)
        self.data_dir.mkdir(exist_ok=True)

    def save(self, filename, data):
        filepath = self.da…
12 0 Open
Production deployment patterns medium

Mock ConfigMap Mount Environment Variables in Python

Simulate reading environment variables from a Kubernetes ConfigMap-mounted directory and test it with mocks.

kubernetes configmap mocking
Python
import os
import tempfile
from unittest.mock import patch

def load_config_from_mount(mount_path):
    """Simulate reading environment variables from a ConfigMap-mounted directory."""
    config = {}
    for filename in os.listdir(mount_path):
        file_path = os.path.join(mount_path, filename)
        if os.path.i…
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.