Modern tooling
uv, ruff, pyproject.toml, packaging, and current Python project workflows.
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.
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 /…
How to Mock BugSnag Notify in Python
Use unittest.mock to simulate BugSnag notifications, verify calls, and test error handling without external dependencies.
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…
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.
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…
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.
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
…
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.
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")):
…
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.
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…
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.
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…
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.
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…
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.
```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…
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.
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)
…
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.
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…
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.
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…
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.