Reference library

Modern tooling

uv, ruff, pyproject.toml, packaging, and current Python project workflows.

10 matches
Modern tooling easy

Data Conversion Helper Functions in Python

A set of beginner-friendly helper functions to convert between JSON strings and Python data, parse dates, and read/write files using pathlib.

json datetime pathlib
Python
from datetime import datetime
from pathlib import Path
import json

def to_json(data, indent=2):
    """Convert Python data to pretty-printed JSON string."""
    return json.dumps(data, indent=indent, default=str)

def from_json(json_string):
    """Parse JSON string back into Python data."""
    return json.loads(jso…
13 0 Open
Modern tooling easy

How to Format Data with Python's datetime and JSON Helpers

A beginner-friendly set of helper functions to format dates and safely read/write JSON files in Python.

datetime json files
Python
from datetime import datetime
from pathlib import Path
import json


def format_today(pattern: str = "%Y-%m-%d") -> str:
    """Return today's date formatted with the given pattern."""
    return datetime.now().strftime(pattern)


def load_json(file_path: str) -> dict:
    """Read and parse a JSON file safely."""
    …
12 0 Open
Modern tooling easy

How to Load and Inspect CSV Data with a Dataclass Helper in Python

This code defines a DataHelper dataclass that reads a CSV file into a list of dictionaries and prints basic dataset information.

csv dataclass pathlib
Python
from pathlib import Path
from dataclasses import dataclass
from typing import Any


@dataclass
class DataHelper:
    """Simple helper for loading and inspecting CSV data."""
    filepath: Path

    def load_csv(self, *, delimiter: str = ",") -> list[dict[str, Any]]:
        """Read CSV into a list of dictionaries."""
…
16 0 Open
Modern tooling easy

How to Mock OpenTelemetry Tracer Setup in Python

Set up a mock OpenTelemetry tracer with an in-memory span exporter to capture spans for testing and debugging.

opentelemetry testing tracing
Python
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import SimpleSpanProcessor
from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter


def setup_tracer():
    provider = TracerProvider()
    exporter = InMemorySpanExpo…
13 0 Open
Modern tooling easy

How to Mock setuptools_scm get_version in Python

This code demonstrates how to mock setuptools_scm.get_version in Python using unittest.mock.patch to test version retrieval logic without installing or relying on the actual package.

setuptools-scm mock unittest
Python
```python
from unittest.mock import patch

def get_version_from_scm():
    try:
        import setuptools_scm
        return setuptools_scm.get_version()
    except (ImportError, LookupError):
        return None

if __name__ == "__main__":
    with patch("setuptools_scm.get_version", return_value="1.2.3"):
        pr…
14 0 Open
Modern tooling easy

How to Parametrize Tests in Python with pytest

This code demonstrates how to use pytest's @pytest.mark.parametrize decorator to run a single test function against multiple input sets, ensuring comprehensive coverage with minimal code duplication.

pytest parametrize testing
Python
import pytest


def multiply(a, b):
    return a * b


@pytest.mark.parametrize("x, y, expected", [
    (2, 3, 6),
    (4, 5, 20),
    (0, 10, 0),
    (7, 1, 7),
])
def test_multiply(x, y, expected):
    result = multiply(x, y)
    assert result == expected, f"multiply({x}, {y}) = {result}, expected {expected}"


if _…
15 0 Open
Modern tooling easy

How to Read the Python Path from VS Code settings.json in Python

This code loads VS Code's settings.json file and extracts the python.defaultInterpreterPath value, with a mock demonstration for testing.

vscode settings json
Python
import json
from pathlib import Path
from unittest.mock import patch

def read_vscode_python_path(settings_path: Path) -> str:
    """Extract python.defaultInterpreterPath from VS Code settings.json."""
    with open(settings_path, "r") as f:
        settings = json.load(f)
    return settings.get("python", {}).get("d…
13 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

How to Use pytest Fixtures and conftest.py for Shared Setup in Python

Learn how to define reusable pytest fixtures for shared setup and use them to keep tests clean and maintainable.

pytest fixtures conftest
Python
import pytest

class Calculator:
    def add(self, a, b):
        return a + b

    def multiply(self, a, b):
        return a * b


@pytest.fixture
def calc():
    return Calculator()


@pytest.fixture
def sample_numbers():
    return (3, 5)


def test_add(calc, sample_numbers):
    a, b = sample_numbers
    assert c…
13 0 Open
Modern tooling easy

How to Validate Data with a Simple Dict-Based Rules Helper in Python

Validates a dictionary against a set of callable rules, printing pass/fail per field and returning an overall boolean.

validation dictionary helper
Python
import json
from pathlib import Path
from typing import Any, Callable


def validate_data(
    data: dict[str, Any],
    rules: dict[str, Callable[[Any], bool]],
    path: Path | None = None,
) -> bool:
    """Validate a dict against a set of simple rules."""
    all_valid = True
    for field, validator in rules.item…
15 0 Open

Browse by section

Each section groups closely related Python snippets.

Modern tooling — Python code examples

What you will find here

This page collects modern tooling snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.

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.