Reference library

Modern tooling

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

50 matches
Modern tooling easy

Build a Recipe Runner Mock in Python

A Python script that mocks a command runner recipe system: maps recipe names to shell commands, executes them with subprocess, and prints the output and exit code.

subprocess command-runner recipes
Python
import subprocess
import sys


def run_recipe(recipe: str) -> None:
    """Simulate a command runner recipe by printing the command and exit code."""
    print(f"Running recipe: {recipe}")
    result = subprocess.run(recipe, shell=True, capture_output=True, text=True)
    print(f"Exit code: {result.returncode}")
    i…
13 0 Open
Modern tooling easy

Build a Textual TUI App Skeleton in Python

Create a minimal Textual terminal UI app with a header, label, button, and footer, ready for interactive mock demonstrations.

textual tui terminal
Python
from textual.app import App, ComposeResult
from textual.widgets import Header, Footer, Button, Label

class MockApp(App):
    """A minimal Textual TUI app skeleton."""

    BINDINGS = [("q", "quit", "Quit")]

    def compose(self) -> ComposeResult:
        """Create child widgets."""
        yield Header()
        yie…
14 0 Open
Modern tooling easy

Configure ruff linter rules in pyproject.toml with Python

Reads an existing pyproject.toml and merges common ruff linter rules into the tool.ruff section using Python's tomllib.

ruff pyproject.toml tomllib
Python
import tomllib
from pathlib import Path

def configure_ruff_linter_rules(project_path: str = ".") -> dict:
    """Add common ruff linter rules to pyproject.toml if missing."""
    pyproject_path = Path(project_path) / "pyproject.toml"
    
    # Default config for ruff linter with practical rules
    ruff_config = {
 …
12 0 Open
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…
12 0 Open
Modern tooling easy

How to Build a Chainable Filter Helper in Python

A beginner-friendly dataclass helper that chains filters, uniqueness, and slicing on any sequence, returning a plain list at the end.

dataclass chaining filter
Python
from dataclasses import dataclass
from typing import Callable, Iterator, Sequence, TypeVar

T = TypeVar("T")


@dataclass
class FilterAssistant:
    """Beginner-friendly helper to filter any collection."""

    data: Sequence[T]

    def where(self, predicate: Callable[[T], bool]) -> "FilterAssistant":
        return …
14 0 Open
Modern tooling easy

How to Build a Wheel with Hatchling in Python

Build a Python wheel using the hatchling build backend and the build package, handling missing project metadata automatically.

hatchling wheel packaging
Python
import subprocess
import sys
import tempfile
from pathlib import Path


def build_wheel_with_hatchling(project_dir: str) -> str:
    """Build a wheel using hatchling and return the wheel file path."""
    project_path = Path(project_dir)

    # Simulate a minimal project structure if missing
    if not (project_path /…
13 0 Open
Modern tooling easy

How to Create Interactive CLI Prompts in Python with questionary

Build mock interactive command-line prompts using questionary's select and text widgets with graceful handling of user cancellation.

cli questionary interactive
Python
import questionary

def main():
    # Mock interactive prompts using questionary's select and text
    choice = questionary.select(
        "What is your favorite programming language?",
        choices=["Python", "JavaScript", "Go", "Rust"]
    ).ask()

    # ask() returns None if user cancels; handle gracefully
    …
14 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
Modern tooling easy

How to Create a Rich Console Progress Bar Mock in Python

This code uses Rich's Console and Progress API to build a simulated progress bar for a long-running task, updating progress and printing status messages.

rich progress-bar cli
Python
import time
from rich.console import Console
from rich.progress import Progress, BarColumn, TextColumn, PercentageColumn

console = Console()

def run_simulation():
    console.print("[bold cyan]Starting simulated task...[/bold cyan]")
    
    with Progress(
        TextColumn("[bold blue]{task.description}[/bold blu…
11 0 Open
Modern tooling easy

How to Define Nox Sessions in Python

Automate repetitive tasks like testing and linting with reusable Nox sessions.

nox automation task-runner
Python
import nox


@nox.session(python=["3.9", "3.10"])
def tests(session):
    session.install("pytest")
    session.run("pytest")


@nox.session(python="3.9")
def lint(session):
    session.install("ruff")
    session.run("ruff", "check", ".")


if __name__ == "__main__":
    print("Nox sessions defined: tests, lint")
   …
12 0 Open
Modern tooling easy

How to Export a Conda Environment YAML File in Python

Generate a mock conda environment YAML export with a reusable Python function and the PyYAML library.

conda yaml environment
Python
import yaml


def conda_env_mock(name="demo_env", channels=None, packages=None):
    channels = channels or ["defaults"]
    packages = packages or [
        "python=3.11",
        "pip",
        "numpy=1.24.3",
        "pandas=2.0.3",
    ]
    env_dict = {
        "name": name,
        "channels": channels,
        …
17 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."""
    …
11 0 Open
Modern tooling easy

How to Generate a Mock Rollbar Error Report in Python

Create a realistic fake Rollbar error report with random timestamps, levels, messages, and counts for testing and demos.

rollbar mock-data error-reporting
Python
import json
import random
import time
from datetime import datetime, timedelta


def mock_rollbar_report(n_errors=5):
    messages = [
        "TypeError: unsupported operand type(s) for +: 'int' and 'str'",
        "KeyError: 'user_id'",
        "ValueError: invalid literal for int() with base 10: 'abc'",
        "At…
13 0 Open
Modern tooling easy

How to Generate a Mock devcontainer.json Config in Python

Build a reproducible devcontainer.json file with Python, composing name, image, extensions, forwarded ports, and a post-create command as a dict.

devcontainer json config
Python
import json
from pathlib import Path


def create_devcontainer_config(
    image: str = "mcr.microsoft.com/devcontainers/python:3.11",
    name: str = "python-dev-container",
    ports: list[int] | None = None,
    post_create: str | None = None,
) -> dict:
    config = {
        "name": name,
        "image": image,
…
14 0 Open
Modern tooling easy

How to Initialize Sentry SDK with a Mock DSN in Python

Initialize the Sentry SDK in Python with a mock DSN to test error tracking without sending real events, then verify the DSN configuration.

sentry sdk dsn
Python
import sentry_sdk

# Initialize Sentry SDK with a mock DSN (no real events will be sent)
sentry_sdk.init(
    dsn="https://mock-public@mock-host/mock-project",
    traces_sample_rate=1.0,
    environment="development",
)

# Capture a test message to confirm SDK is configured
sentry_sdk.capture_message("Test message fr…
12 0 Open
Modern tooling easy

How to List Pre-commit Hooks from YAML Config in Python

Parse a .pre-commit-config.yaml file with PyYAML and print every hook ID paired with its source repository.

pre-commit yaml pyyaml
Python
import yaml

pre_commit_config = """
repos:
  - repo: https://github.com/pre-commit/pre-commit-hooks
    rev: v4.5.0
    hooks:
      - id: trailing-whitespace
      - id: end-of-file-fixer
      - id: check-yaml
  - repo: https://github.com/psf/black
    rev: 23.11.0
    hooks:
      - id: black
"""

def list_hooks(c…
15 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 Load and Inspect Data Files in Python

A beginner-friendly DataLoader dataclass that loads JSON or text files and provides methods to preview and inspect the data.

dataclasses file-io json
Python
from dataclasses import dataclass, field
from pathlib import Path
import json
from typing import Any, Dict, List


@dataclass
class DataLoader:
    """Simple helper to load and inspect data files for beginners."""
    path: Path
    data: Any = field(init=False, default=None)

    def __post_init__(self) -> None:
    …
15 0 Open
Modern tooling easy

How to Load and Save CSV and JSON Files in Python

A beginner-friendly data helper that loads or saves CSV and JSON files using only the Python standard library, with automatic format detection from the file extension.

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


def load_data(file_path):
    """Load CSV or JSON data from disk based on file extension."""
    path = Path(file_path)
    if path.suffix == ".json":
        with path.open() as f:
            return json.load(f)
    elif path.suffix == ".csv":
        with path.open(…
13 0 Open
Modern tooling easy

How to Load envrc Files in Python

Parse and apply direnv-style envrc files to the current environment, with proper handling of variables, comments, and quotes.

envrc environment config
Python
import os
import tempfile
from pathlib import Path
from unittest.mock import patch


def load_envrc(envrc_path):
    """Parse an envrc-style file and apply it to the current environment."""
    env_changes = {}
    with open(envrc_path, "r") as f:
        for line in f:
            line = line.strip()
            if l…
15 0 Open
Modern tooling easy

How to Mock BugSnag Notify in Python

Use unittest.mock to simulate BugSnag notifications, verify calls, and test error handling without external dependencies.

mocking bugsnag testing
Python
import mock

bugsnag = mock.MagicMock()

def notify_error(message, severity="error"):
    bugsnag.notify(message, severity=severity)

if __name__ == "__main__":
    notify_error("Test error", severity="warning")
    bugsnag.notify.assert_called_once_with("Test error", severity="warning")
    print("Mocked BugSnag noti…
16 0 Open
Modern tooling easy

How to Mock Click CLI App Subcommands in Python

Simulate Click-style CLI subcommand calls in Python by using argparse with subparsers and mocking sys.argv in tests or scripts.

cli argparse mocking
Python
import sys
import argparse


def do_greet(args):
    print(f"Hello, {args.name}!")


def do_goodbye(args):
    print(f"Goodbye, {args.name}!")


def main():
    parser = argparse.ArgumentParser(prog="clickapp")
    subparsers = parser.add_subparsers(dest="command", required=True)

    greet_parser = subparsers.add_par…
13 0 Open
Modern tooling easy

How to Mock Commitizen Version Bump in Python

Simulate commitizen's version bump logic and mock the subprocess call to avoid real execution in tests.

commitizen mock subprocess
Python
import subprocess
from unittest.mock import patch, MagicMock


def bump_version(current_version: str, increment: str = "patch") -> str:
    """Simulate commitizen's version bump logic."""
    major, minor, patch = map(int, current_version.split("."))
    if increment == "major":
        major += 1
        minor = 0
  …
14 0 Open
Modern tooling easy

How to Mock Fabric Connections in Python for Task Testing

Create a lightweight MockConnection class to replace fabric.Connection and test task functions without SSH.

fabric mocking testing
Python
from fabric import Connection


class MockConnection:
    """Minimal mock of fabric.Connection for task testing."""

    def __init__(self):
        self.commands = []

    def run(self, command, **kwargs):
        self.commands.append(command)
        return f"OK: {command}"


def deploy(conn):
    """Deploy the app:…
13 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.