Reference library

Modern tooling

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

12 matches
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 /…
14 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…
14 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
  …
15 0 Open
Modern tooling easy

How to Mock Twine Upload to TestPyPI in Python

Simulate a twine upload to TestPyPI with a dry-run mock function that validates distribution files and prints the intended upload action without any network call.

twine testpypi mock
Python
import subprocess
import sys

# Mock twine upload to TestPyPI using subprocess dry-run
def mock_twine_upload(dist_file: str, repo_url: str = "https://test.pypi.org/legacy/") -> None:
    """Simulate twine upload by checking dist file and printing intended action."""
    if not dist_file.endswith((".whl", ".tar.gz")):
…
12 0 Open
Modern tooling easy

How to Mock a Fast uv pip sync in Python

Simulate a fast uv pip sync by mocking file operations and subprocess calls to test dependency installation workflows.

uv mocking pip
Python
import os
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path

def uv_pip_sync_fast_install_mock(requirements_text: str) -> dict:
    """Simulate a fast uv pip sync by mocking file operations and subprocess calls."""
    mock_dir = Path(tempfile.mkdtemp(prefix="uv_mock_"))
    req_lines…
14 0 Open
Modern tooling medium

How to Mock a PEP 517 Build Backend in Python

Use unittest.mock.Mock to simulate a PEP 517 backend interface, stub build hooks, and verify calls for package build automation.

pep517 unittest.mock packaging
Python
import json
from unittest.mock import Mock

# Simulate a PEP 517 backend interface
class Pep517Backend:
    def build_wheel(self, wheel_directory, config_settings=None, metadata_directory=None):
        return f"{wheel_directory}/mock_package-1.0.0-py3-none-any.whl"

    def get_requires_for_build_wheel(self, config_s…
14 0 Open
Modern tooling easy

How to Mock a pipx Install Command in Python

Simulate a pipx install step by validating tool names and printing the exact command output a real pipx run would produce.

pipx cli mocking
Python
import subprocess
import sys


def install_with_pipx(tool_name: str) -> str:
    """
    Mock a pipx install step by validating the tool name and
    simulating the installation command output.
    """
    allowed_tools = {"black", "flake8", "mypy", "ruff"}
    if tool_name not in allowed_tools:
        raise ValueErr…
15 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 medium

How to Mock subprocess.run for Black Formatter in Python

Use unittest.mock to simulate subprocess.run calls in a Python function that runs the Black formatter, allowing isolated testing without executing external commands.

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

def run_black_formatter(file_path: str, check_only: bool = False) -> dict:
    """Run black formatter on a file via subprocess."""
    cmd = ["black", "--check" if check_only else "-", file_path]
    result = subprocess.run(cmd, capture_output=True, text=True)
 …
15 0 Open
Modern tooling easy

How to Type Check a Mock with pyright in Python

Shows how pyright validates a mock function against a TypedDict and Callable signature before runtime.

pyright type-checking mocking
Python
from typing import TypedDict, Callable


class User(TypedDict):
    id: int
    name: str


def get_user_name(user_id: int, get_user: Callable[[int], User]) -> str:
    user = get_user(user_id)
    return user["name"]


def mock_get_user(user_id: int) -> User:
    return {"id": user_id, "name": f"User {user_id}"}


if…
15 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.