Modern tooling
uv, ruff, pyproject.toml, packaging, and current Python project workflows.
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.
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…
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.
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…
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.
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 …
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 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.
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
…
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.
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…
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.
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,
…
How to build a tox multi-env matrix with mock config in Python
Simulate a tox multi-environment matrix by validating environment names and grouping extras into a readable matrix structure.
```python
import tox
def run_tox_matrix(mock_envs):
"""Simulate a tox multi-env configuration and verify mock choices."""
config = {
"tox": {
"envlist": mock_envs,
"config": {
"basepython": "python3.9",
"deps": ["pytest", "mock"],
},
…
Makefile Targets for lint, test, and build in Python
This Python script defines common Makefile targets (lint, test, build) as subprocess commands, printing each target's command and executing them with error checking.
import subprocess
TARGETS = {
"lint": ["ruff", "check", "."],
"test": ["pytest", "-q"],
"build": ["python", "-m", "build"],
}
def run(target: str) -> None:
if target not in TARGETS:
raise ValueError(f"Unknown target: {target}")
print(f"Running {target}...")
subprocess.run(TARGETS[tar…
Mock pdm build and publish in Python
Simulate pdm build and publish commands with unittest.mock to test packaging workflows without triggering real builds or uploads.
from unittest.mock import Mock, patch
import pdm
def build_package() -> str:
"""Simulate building a package with pdm."""
build_mock = Mock(return_value="dist/mypackage-0.1.0-py3-none-any.whl")
with patch.object(pdm, "build", build_mock):
result = pdm.build()
return result
def publish_packa…
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.