Appendix A: Cheat Sheet
Tested with Python 3.14.8, uv 0.9.26, ruff 0.17, pytest 9.1, mypy
2.4, typer 0.27, httpx 0.28, pydantic 2.14, openai 3.28, mcp 2.3 and
Ollama (ministral-3:3b, all-minilm). Every
Python block runs on its own with
uv run python datei.py.
Syntax and idioms
# f-strings: alignment, thousands, percent, date, debug with =
n, rate, name = 1234567, 0.0842, "logsum"
print(f"{name:<8}|{n:>12,}|{rate:.1%}|{n=}")
# Comprehensions: list, dict, set, generator (lazy)
squares = [x * x for x in range(5) if x % 2 == 0]
lengths = {w: len(w) for w in ("vault", "bao")}
total = sum(x * x for x in range(1_000_000))
# Walrus: assign and test in one expression
if (m := len(squares)) > 2:
print(m, squares, lengths, total)
# Unpacking, collecting the rest, swapping
first, *rest = [1, 2, 3]
a, b = 1, 2
a, b = b, a
# match: check and destructure a structure
match {"status": 503, "path": "/api"}:
case {"status": 200}:
print("ok")
case {"status": s, "path": p} if s >= 500:
print(f"Serverfehler {s} auf {p}")
# dict.get with default, setdefault, merge with |
cfg = {"timeout": 5} | {"retries": 3}
print(cfg.get("proxy", "kein Proxy"), first, rest, a, b)
# dataclass: value object with defaults, immutable and lean
from dataclasses import dataclass, field
@dataclass(frozen=True, slots=True)
class Target:
host: str
port: int = 443
tags: tuple[str, ...] = ()
@dataclass
class Report:
targets: list[Target] = field(default_factory=list) # never: = []
r = Report()
r.targets.append(Target("vault.lab", 8200, ("prod",)))
print(r)
# Type hints: union with |, optional, Callable, generics (PEP 695), TypedDict
from collections.abc import Callable, Iterator
from typing import TypedDict
class Row(TypedDict):
name: str
cost: float
def first[T](items: list[T], default: T | None = None) -> T | None:
return items[0] if items else default
def apply(fn: Callable[[int], int], xs: list[int]) -> Iterator[int]:
yield from (fn(x) for x in xs)
row: Row = {"name": "EC2", "cost": 12.5}
print(first([3, 4]), first([]), list(apply(lambda x: x * 2, [1, 2])), row)
# Errors: custom exception, attach cause, multiple types, finally
class ToolError(Exception):
"""Fachlicher Fehler des Tools."""
def load(path: str) -> str:
try:
with open(path, encoding="utf-8") as f:
return f.read()
except FileNotFoundError as err:
raise ToolError(f"fehlt: {path}") from err
except PermissionError, IsADirectoryError: # 3.14: no parentheses (without as)
raise ToolError(f"nicht lesbar: {path}") from None
try:
load("/gibt/es/nicht")
except ToolError as err:
print(err, "| Ursache:", type(err.__cause__).__name__)
Standard library for tools
| Module |
For |
Day |
pathlib |
paths, glob, read_text,
Path.move() (3.14) |
1, 3 |
argparse |
CLI without a dependency |
2 |
subprocess |
system commands: run([...], check=True) |
3 |
logging |
diagnostics to stderr, level via option |
4 |
json, tomllib, csv |
reading formats (TOML read-only) |
3, 8 |
sqlite3 |
embedded database |
8 |
re |
regex: compile, named groups |
2 |
collections |
Counter, defaultdict |
2, 15 |
datetime |
time, always with a time zone (UTC) |
2, 4 |
hashlib, secrets |
checksums, secure random values |
9, 15 |
concurrent.futures |
thread and process pools |
7, 14 |
asyncio |
many concurrent network calls |
7 |
functools |
cache, lru_cache,
partial |
14 |
cProfile, tracemalloc,
timeit |
measure instead of guessing |
14 |
zipapp |
a tool as a single executable file |
14 |
# The moves that show up in almost every tool
import hashlib
import json
import logging
import os
import secrets
import subprocess
from collections import Counter
from datetime import UTC, datetime
from pathlib import Path
log = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s: %(message)s")
here = Path.cwd()
pys = sorted(p.name for p in here.glob("*.py"))
r = subprocess.run(["uname", "-s"], capture_output=True, text=True, check=True)
digest = hashlib.sha256(b"lab").hexdigest()[:12]
token = secrets.token_urlsafe(16) # lab token, e.g. for tests
now = datetime.now(UTC).isoformat(timespec="seconds")
words = Counter("abaca").most_common(1)
debug = os.environ.get("TOOL_DEBUG", "0") == "1"
log.info("%s Dateien, OS %s", len(pys), r.stdout.strip())
print(json.dumps({"sha": digest, "now": now, "top": words, "debug": debug}))
uv
# Python and projects
uv python install 3.14
uv init -p 3.14 --package --name tool tool # src layout + console script
uv add httpx 'typer>=0.27' # runtime dependency
uv add --dev pytest ruff mypy # development only
uv remove httpx
uv sync --locked # CI: lockfile must match
uv lock --upgrade-package httpx
uv tree --depth 1
# Running
uv run tool --help # project venv, package editable
uv run --with polars script.py # extra package for this run only
uv run --no-project -p 3.14t python cpu.py # free-threaded build
uvx ruff check # tool without installation
uvx --from actionlint-py actionlint # package name != command
# Version, building, installing
uv version --bump minor # 0.1.0 => 0.2.0
uv version --short
uv build # dist/*.whl + dist/*.tar.gz
uv tool install dist/tool-0.2.0-py3-none-any.whl
uv tool install --editable . # during development
uv tool list
uv tool uninstall tool
ruff, pytest, mypy
uv run ruff check # lint (exit 1 on findings)
uv run ruff check --fix # apply safe fixes
uv run ruff format # format; --check only checks
uv run ruff rule S602 # have a rule explained
uv run pytest -q # all tests
uv run pytest -q -k parse -x # matching ones only, stop at first failure
uv run pytest -v --lf # only the last failed ones
uv run pytest --cov=tool --cov-report=term-missing --cov-fail-under=85
uv run mypy # with [tool.mypy] strict = true, files = ["src"]
uv run --with mypy mypy --strict src # without a dev dependency
[tool.ruff.lint]
extend-select = ["E501", "B", "UP", "SIM", "I", "S"]
[tool.ruff.lint.per-file-ignores]
"tests/*" = ["S101"]
[tool.mypy]
strict = true
files = ["src"]
[[tool.mypy.overrides]]
module = ["sklearn.*", "joblib.*"] # packages without type information
ignore_missing_imports = true
[tool.pytest.ini_options]
testpaths = ["tests"]
# pytest: fixture, parametrize, tmp_path, monkeypatch, raises, mock
from unittest.mock import MagicMock
import pytest
def parse_port(s: str) -> int:
port = int(s)
if not 0 < port < 65536:
raise ValueError(f"Port außerhalb: {port}")
return port
@pytest.fixture
def config(tmp_path):
path = tmp_path / "tool.toml"
path.write_text('port = "8200"\n', encoding="utf-8")
return path
@pytest.mark.parametrize(("raw", "port"), [("80", 80), ("8200", 8200)])
def test_parse_port(raw, port):
assert parse_port(raw) == port
def test_parse_port_fehler():
with pytest.raises(ValueError, match="außerhalb"):
parse_port("70000")
def test_env_und_mock(config, monkeypatch):
monkeypatch.setenv("TOOL_PORT", "8200")
client = MagicMock()
client.get.return_value.status_code = 200
assert client.get("/health").status_code == 200
client.get.assert_called_once_with("/health")
assert config.read_text(encoding="utf-8").startswith("port")
To run it: save as tests/test_spick.py, then
uv run pytest -q tests/test_spick.py.
typer
# CLI with subcommands, argument/option via Annotated, exit codes
from pathlib import Path
from typing import Annotated
import typer
app = typer.Typer(help="Lab-Tool", no_args_is_help=True, add_completion=False)
Dir = Annotated[Path, typer.Argument(exists=True, file_okay=False)]
@app.command()
def scan(
directory: Dir,
limit: Annotated[int, typer.Option("--limit", "-n", min=1)] = 10,
dry_run: Annotated[bool, typer.Option(help="nichts ändern")] = True,
) -> None:
"""Listet Dateien. Exit 1, wenn keine gefunden wurden."""
files = sorted(p for p in directory.iterdir() if p.is_file())[:limit]
for p in files:
typer.echo(p.name)
if not files:
typer.echo("nichts gefunden", err=True) # to stderr
raise typer.Exit(1)
@app.command()
def version() -> None:
typer.echo("lab 0.1.0")
if __name__ == "__main__":
app()
| Exit code |
Convention in this book |
| 0 |
all good |
| 1 |
functional finding (duplicates, conflicts, errors found) |
| 2 |
usage error (typer/argparse, typer.BadParameter) |
| 3 |
environment broken (network, system command, Nagios: UNKNOWN) |
httpx
# Client with timeout, base URL, headers; retry with backoff; tests without network
import random
import time
import httpx
def backoff(attempt: int, base: float = 0.5, cap: float = 8.0) -> float:
return min(cap, base * 2**attempt) * random.uniform(0.5, 1.0)
def get_json(client: httpx.Client, path: str, retries: int = 3) -> object:
for attempt in range(retries + 1):
try:
r = client.get(path)
if r.status_code not in (429, 500, 502, 503, 504):
r.raise_for_status() # 4xx: fail immediately, no retry
return r.json()
except httpx.TransportError: # timeout, DNS, connection
if attempt == retries:
raise
time.sleep(backoff(attempt))
r.raise_for_status()
return r.json()
def handler(request: httpx.Request) -> httpx.Response:
return httpx.Response(200, json={"path": request.url.path})
client = httpx.Client(
base_url="https://api.lab",
timeout=httpx.Timeout(5.0, connect=2.0),
headers={"User-Agent": "lab-tool/0.1"},
transport=httpx.MockTransport(handler), # only in tests
)
print(get_json(client, "/v1/status"))
pydantic
# Validate at the boundary: JSON in, checked object out
from datetime import datetime
from pydantic import BaseModel, Field, HttpUrl, ValidationError
class Release(BaseModel):
tag: str = Field(alias="tag_name")
url: HttpUrl = Field(alias="html_url")
published: datetime = Field(alias="published_at")
prerelease: bool = False
raw = (
'{"tag_name": "v1.2.0", "html_url": "https://github.com/lab/x",'
' "published_at": "2026-10-01T12:00:00Z", "extra": 1}'
)
rel = Release.model_validate_json(raw) # unknown fields are ignored
print(rel.tag, rel.published.year, rel.model_dump(mode="json")["url"])
print(Release.model_json_schema()["required"])
try:
Release.model_validate({"tag_name": "v1", "html_url": "kein-url"})
except ValidationError as err:
print(err.error_count(), "Fehler:", err.errors()[0]["loc"])
asyncio
# Many network calls at once, limited, with a timeout per call
import asyncio
import httpx
async def check(client: httpx.AsyncClient, sem: asyncio.Semaphore, url: str) -> str:
async with sem:
try:
async with asyncio.timeout(2):
r = await client.get(url)
return f"{r.status_code} {url}"
except (TimeoutError, httpx.TransportError) as err:
return f"ERR {url} {type(err).__name__}"
async def main(urls: list[str], concurrency: int = 20) -> list[str]:
sem = asyncio.Semaphore(concurrency)
async with httpx.AsyncClient() as client, asyncio.TaskGroup() as tg:
tasks = [tg.create_task(check(client, sem, u)) for u in urls]
return [t.result() for t in tasks] # same order as the input
print(asyncio.run(main(["http://127.0.0.1:9/a", "http://127.0.0.1:9/b"])))
| Load |
Tool |
| lots of waiting (network, disk) |
asyncio + httpx.AsyncClient |
| waiting, sync-only library |
ThreadPoolExecutor |
| CPU load |
ProcessPoolExecutor (guard
if __name__ == "__main__") |
| CPU load, 3.14t |
threads, if all C extensions play along |
Measuring and shipping
hyperfine -w 1 -r 5 'uv run tool big.log' 'uv run tool big.log -w 0'
uv run python -m cProfile -s tottime -m tool big.log 2>&1 | head -20
uv run python -m cProfile -o prof.out -m tool big.log # then pstats
uv run --with line_profiler python scripts/lineprof.py big.log
uv run python -m timeit -s 'import re; rx = re.compile("a+")' 'rx.match("aaa")'
uvx py-spy top --pid 4711 # macOS: sudo
uv run python -m zipapp build/pyz -p '/usr/bin/env python3' -c -o dist/tool.pyz
# Memory: peak and culprits with tracemalloc
import tracemalloc
tracemalloc.start()
data = [str(i) * 10 for i in range(100_000)]
current, peak = tracemalloc.get_traced_memory()
top = tracemalloc.take_snapshot().statistics("lineno")[0]
print(f"Spitze {peak / 2**20:.1f} MiB; größter Posten: {top.size / 2**20:.1f} MiB")
AI: OpenAI-compatible against Ollama and the cloud
# One client for everything: only base_url, key and model change
import os
from openai import OpenAI
BASE_URL = os.environ.get("ASK_BASE_URL", "http://127.0.0.1:11434/v1")
MODEL = os.environ.get("ASK_MODEL", "ministral-3:3b")
client = OpenAI(
base_url=BASE_URL,
api_key=os.environ.get("ASK_API_KEY", "ollama"), # Ollama ignores the key
timeout=120,
max_retries=1,
)
resp = client.chat.completions.create(
model=MODEL,
messages=[
{"role": "system", "content": "Antworte in einem Satz auf Deutsch."},
{"role": "user", "content": "Was ist ein Inode?"},
],
temperature=0,
)
print(resp.choices[0].message.content)
print(resp.usage.prompt_tokens if resp.usage else "-", "Tokens im Prompt")
| Target |
base_url |
Key from |
| Ollama locally |
http://127.0.0.1:11434/v1 |
doesn’t matter (ollama) |
| vLLM in the cluster |
http://vllm.lab:8000/v1 |
secret store |
| Mistral |
https://api.mistral.ai/v1 |
MISTRAL_API_KEY |
| OpenAI |
default (omit) |
OPENAI_API_KEY |
# Streaming with token counting
from openai import OpenAI
client = OpenAI(base_url="http://127.0.0.1:11434/v1", api_key="ollama")
stream = client.chat.completions.create(
model="ministral-3:3b",
messages=[{"role": "user", "content": "Zähle von 1 bis 5."}],
stream=True,
stream_options={"include_usage": True},
)
for chunk in stream:
if chunk.choices and chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="", flush=True)
if chunk.usage:
print(f"\n[{chunk.usage.completion_tokens} Tokens]")
# Structured output: pydantic schema in, validated object out
from typing import Literal
from openai import OpenAI
from pydantic import BaseModel
class Triage(BaseModel):
severity: Literal["ok", "warn", "crit"]
reason: str
client = OpenAI(base_url="http://127.0.0.1:11434/v1", api_key="ollama")
resp = client.chat.completions.parse(
model="ministral-3:3b",
messages=[{"role": "user", "content": "Disk 97 % voll auf db-0. Bewerte."}],
response_format=Triage,
temperature=0,
)
triage = resp.choices[0].message.parsed
print(triage)
# Embeddings + cosine similarity with numpy
import numpy as np
from openai import OpenAI
client = OpenAI(base_url="http://127.0.0.1:11434/v1", api_key="ollama")
docs = ["Vault entsiegeln mit Unseal-Keys", "Pod hängt in CrashLoopBackOff"]
query = "how to unseal vault"
resp = client.embeddings.create(model="all-minilm", input=[*docs, query])
vecs = np.array([d.embedding for d in resp.data])
vecs /= np.linalg.norm(vecs, axis=1, keepdims=True) # normalize
scores = vecs[:-1] @ vecs[-1] # cosine = dot product of normalized vectors
best = int(np.argmax(scores))
print(vecs.shape, [round(float(s), 2) for s in scores], docs[best])
# Tool calling: the model picks a function, you execute it (allowed ones only!)
import json
import os
from openai import OpenAI
def disk_free_gb(path: str = "/") -> float:
st = os.statvfs(path)
return round(st.f_bavail * st.f_frsize / 1e9, 1)
TOOLS = {"disk_free_gb": disk_free_gb}
SCHEMA = [
{
"type": "function",
"function": {
"name": "disk_free_gb",
"description": "Freier Platz in GB für einen Pfad",
"parameters": {
"type": "object",
"properties": {"path": {"type": "string"}},
"required": ["path"],
},
},
}
]
client = OpenAI(base_url="http://127.0.0.1:11434/v1", api_key="ollama")
messages = [{"role": "user", "content": "Wie viel Platz ist auf / frei?"}]
for _ in range(3): # hard upper limit for the loop
msg = client.chat.completions.create(
model="ministral-3:3b", messages=messages, tools=SCHEMA, temperature=0
).choices[0].message
if not msg.tool_calls:
print(msg.content)
break
messages.append(msg.model_dump(exclude_none=True))
for call in msg.tool_calls:
fn = TOOLS.get(call.function.name) # allowlist instead of eval
args = json.loads(call.function.arguments)
result = fn(**args) if fn else "unbekanntes Tool"
messages.append(
{"role": "tool", "tool_call_id": call.id, "content": json.dumps(result)}
)
# MCP server (mcp >= 2: MCPServer instead of FastMCP) and client in the same process
import asyncio
import shutil
from mcp import Client
from mcp.server.mcpserver import MCPServer
from mcp.types import ToolAnnotations
server = MCPServer("lab-tools", instructions="Read-only Infos.")
def disk_usage(path: str = "/") -> dict[str, float]:
"""Belegung des Dateisystems in GB."""
u = shutil.disk_usage(path)
return {"total_gb": round(u.total / 1e9, 1), "free_gb": round(u.free / 1e9, 1)}
server.add_tool(disk_usage, annotations=ToolAnnotations(read_only_hint=True))
async def main() -> None:
async with Client(server) as client:
tools = await client.list_tools()
result = await client.call_tool("disk_usage", {"path": "/"})
print([t.name for t in tools.tools], result.structured_content)
asyncio.run(main()) # as a service instead: server.run() (stdio)
Security: LLM output is data, never commands. Tools
only from an allowlist, validate arguments, never pass anything to
subprocess with shell=True, loops with an
upper limit. Keys only from the environment or a secret store.