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…
How to Define Nox Sessions in Python
Automate repetitive tasks like testing and linting with reusable Nox sessions.
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")
…
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.
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:…
Lint a Dockerfile with a Mock Hadolint in Python
A lightweight Python script that simulates hadolint by scanning Dockerfile text for common lint rules and printing violations.
import subprocess
import tempfile
from pathlib import Path
def lint_dockerfile(content: str) -> list[str]:
"""Mock hadolint by checking a few rules and returning violations."""
violations = []
lines = content.splitlines()
for idx, line in enumerate(lines, start=1):
stripped = line.strip()
…
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…
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.