SkilVaultSign inStart free

Catalogue / typed-python-playbook

typed-python-playbook

Older skill: source not recordedSignedWrites typed, idiomatic Python and diagnoses it: modern annotations, pattern matching, resource-safe context managers, generators, decorators, async concurrency with explicit failure policies, debugging and profiling workflows, and a reviewable project-quality setup. Use when the user says "write a…
---
name: typed-python-playbook
description: >-
  Writes typed, idiomatic Python and diagnoses it: modern annotations, pattern
  matching, resource-safe context managers, generators, decorators, async
  concurrency with explicit failure policies, debugging and profiling
  workflows, and a reviewable project-quality setup. Use when the user says
  "write a Python function", "use type hints", "debug this Python script",
  "profile slow Python code", "set up ruff and pytest", or "migrate from
  Poetry to uv".
  Not for installing or upgrading dependencies, publishing packages, or
  exposing debug servers without separately approved scope.
---

Typed Python, implemented and diagnosed

Read the project's Python requirement, lockfile, layout and quality commands before touching code. Stay inside the chosen interpreter and tool versions, and prefer the smallest coherent change that solves the stated problem.

Confirm scope before side effects

A direct implementation request covers exactly that implementation. Ask separately before: dependency changes, environment or interpreter installs, file generation, migrations, network calls, service access, or publication. An isolated test run the user requested needs no repeated approval. Profiling and debugging execute real code — establish its side effects and data scope before choosing a command.

Never

  • Enable a debugger endpoint reachable from outside, or relax its safeguards
  • Treat type hints as validation, or Python 3.12 syntax as 3.10-safe
  • Optimize before measuring, or pass swallowed exceptions off as success
  • Strip dependency pins, delete lockfiles or backups, or float unreviewed CI tools
  • Claim a tool ran when it did not — record what was actually checked

Language features, version-checked

| Feature | Since | Note | | --- | --- | --- | | list[str], dict[str, int], tuple[bool, str] generics | 3.10 | replaces typing.List etc. | | str \| None unions | 3.10 | replaces Optional[str] | | structural match/case | 3.10 | see caveats below | | type Alias = ... statement | 3.12 | on 3.10 use X: TypeAlias = ... |

match caveats:

  • Match a known data contract, guard conditional cases, and give unknown shapes a clear fallback.
  • Mapping patterns tolerate extra keys — matching required keys is not strict validation.
  • An annotation never validates at runtime; validate external input explicitly.

Idioms to reach for:

  • comprehensions for simple transforms; generators for streaming; plain loops when side effects or error handling would make a comprehension unreadable
  • immutable transformations over in-place mutation, unless mutation is the contract
  • no mutable default arguments
  • catch only errors you can meaningfully handle
  • dependency injection through Protocol when the contract earns its keep; a factory that rejects unsupported choices
  • decorators that preserve metadata with functools.wraps; time with perf_counter and report in finally so failures still log
  • an async function needs an async wrapper — a sync decorator that only times coroutine creation is useless
  • separate responsibilities that change for different reasons — without splitting one honest function into hollow classes to claim SOLID

One worked example

Dependency-free; validates readings, selects a formatter, injects a sink, and owns a resource with a context manager. It shows modern annotations, guarded patterns, comprehensions, a bounded generator and a wrapped timing decorator:

from contextlib import contextmanager
from functools import wraps
from time import perf_counter
from typing import Callable, Iterator, Protocol, TypeAlias, TypeVar
import json

Reading: TypeAlias = dict[str, str | int]
T = TypeVar('T')

class Sink(Protocol):
    def emit(self, payload: str) -> None: ...
    def close(self) -> None: ...

def timed(report: Callable[[float], None]):
    def decorate(function):
        @wraps(function)
        def wrapped(*args, **kwargs):
            start = perf_counter()
            try:
                return function(*args, **kwargs)
            finally:
                report(perf_counter() - start)
        return wrapped
    return decorate

@contextmanager
def owned_sink(create: Callable[[], Sink]) -> Iterator[Sink]:
    sink = create()
    try:
        yield sink
    finally:
        sink.close()

def parse_reading(value: object) -> Reading:
    match value:
        case {'station': str(station), 'count': int(count)} if station and count >= 0:
            if isinstance(count, bool):
                raise ValueError('bool is not a count')
            return {'station': station, 'count': count}
        case _:
            raise ValueError('need a nonempty station and a nonnegative count')

def formatter(kind: str) -> Callable[[Reading], str]:
    match kind:
        case 'json':
            return lambda item: json.dumps(item, sort_keys=True)
        case 'text':
            return lambda item: f"{item['station']}: {item['count']}"
        case _:
            raise ValueError(f'unsupported format: {kind}')

def batches(values: list[T], width: int) -> Iterator[list[T]]:
    if width < 1:
        raise ValueError('batch width must be positive')
    for start in range(0, len(values), width):
        yield values[start:start + width]

def deliver(raw: list[object], sink: Sink, kind: str = 'json') -> int:
    validated = [parse_reading(item) for item in raw]
    render = formatter(kind)
    for payload in (render(item) for item in validated):
        sink.emit(payload)
    return len(validated)

Notes: everything validates before the first emit, but that is not a transaction — if a real sink fails midway, earlier emissions stay. Test that distinction. Dictionary and set comprehensions can derive station lookups and distinct counts from validated records; decide duplicate-key behavior deliberately. A real sink's writes or calls stay inside approved scope.

Async with an explicit failure policy

Rules before the code:

  • Await async work; asyncio.gather runs independent operations concurrently but is not a concurrency limit — pair it with a semaphore or bounded pool.
  • asyncio.wait_for supplies a timeout and cancels the wrapped work; cancellation does not undo external effects.
  • asyncio.run belongs at a synchronous entry point, never inside a running loop.
  • Blocking sync clients and CPU-bound work must not run on the loop.
  • Any HTTP client needs a clear owner, timeouts, status validation and authorized destinations; do not build a new client per request without cause.
import asyncio
from typing import Awaitable, Callable, TypeVar

R = TypeVar('R')

async def bounded_map(values: list[str], work: Callable[[str], Awaitable[R]],
                      limit: int, timeout: float) -> list[R | BaseException]:
    if limit < 1 or timeout <= 0:
        raise ValueError('need positive concurrency and timeout')
    gate = asyncio.Semaphore(limit)

    async def one(value: str) -> R:
        async with gate:
            return await asyncio.wait_for(work(value), timeout=timeout)

    return await asyncio.gather(*(one(v) for v in values), return_exceptions=True)

This returns results or exceptions in input order, so one failure does not discard successful siblings. Fail-fast sibling cancellation is the opposite policy — pick what the project needs and test it. Huge inputs still create one task each here; reach for a bounded queue instead. Close async clients, and never treat a suppressed CancelledError as success. On 3.11+, structured task groups are an option when the support matrix allows.

Investigate before optimizing

Reproduce the smallest failing input against deterministic state first. Tools:

| Need | Command | Note | | --- | --- | --- | | Interactive pause | breakpoint() / pdb.set_trace() | guard with a condition to hit only the bad case | | Debug a script | python -m pdb <script> | approved scripts only | | Debug a failing test | pytest --pdb | --pdbcls=IPython.terminal.debugger:TerminalPdb if IPython is installed | | CPU hot spots | python -m cProfile -s cumulative <script> | read high-cost callers before changing algorithms | | Python allocations | tracemalloc | traced Python memory only — not native or whole-process memory | | Hot lines | line-profiler / kernprof | verify locally installed help first | | Sampling views | py-spy, Scalene | different CPU/memory sampling angles |

Post-mortem debugging belongs inside an active exception handler; preserve the traceback with traceback.format_exc() or logging's exception support after redacting secrets. A reusable allocation-snapshot and call-tracing pair:

import sys
import tracemalloc
from contextlib import contextmanager

@contextmanager
def allocation_snapshot():
    already = tracemalloc.is_tracing()
    if not already:
        tracemalloc.start()
    try:
        yield lambda: tracemalloc.take_snapshot().statistics('lineno')
    finally:
        if not already:
            tracemalloc.stop()

@contextmanager
def call_trace(callback):
    prior = sys.gettrace()
    def trace(frame, event, arg):
        if event == 'call':
            callback(frame.f_code.co_name)
        return trace
    sys.settrace(trace)
    try:
        yield
    finally:
        sys.settrace(prior)

Tracing perturbs timing and can surface private names — keep its output private and scope it narrowly. Under uv, uv run --with <tool> ... and uvx <tool> ... can fetch temporary tools, which still counts as the approved dependency/network scope; uv run --offline covers cached project commands but never makes a missing dependency appear.

Framework debug settings — Django's toolbar, DEBUG, INTERNAL_IPS, Flask's debug/PROPAGATE_EXCEPTIONS — belong only in an approved, isolated local configuration. Keep the debugger unreachable externally and never disable Werkzeug's PIN. Do not touch production settings to reproduce a bug.

Reviewable project setup

Prefer a src layout: src/<package>/__init__.py plus cohesive modules, and tests/ beside a pyproject.toml and README. Match imports and build-backend discovery to the real package name. A starting template — fill real metadata, dependencies and URLs only from the project; a license is the owner's call:

[project]
name = "station-ledger"
version = "0.1.0"
description = "Validates and formats station readings"
requires-python = ">=3.10"
readme = "README.md"
dependencies = []

[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"

[tool.hatch.build.targets.wheel]
packages = ["src/station_ledger"]

[tool.ruff]
target-version = "py310"

[tool.ruff.lint]
select = ["E", "F", "I", "B", "UP"]

[tool.pytest.ini_options]
testpaths = ["tests"]
addopts = ["--strict-markers", "--strict-config"]
markers = ["integration: needs approved external boundaries"]

Tool selection guidance:

  • Pin the versions actually compatible with the project, from its lockfile — not copied example numbers.
  • Add dev/test/type-check groups, docs tooling (e.g. Sphinx), and security scanners (Bandit, Safety) only when used; runtime libraries likewise.
  • Ruff can grow W, C4, ARG, SIM, type-checking and pathlib rule groups, justified per-file ignores, first-party isort names and formatting policy. Rule names drift between releases — inspect the installed set.
  • Keep read-only checks separate from --fix and formatting; never enable unconditional auto-fix in CI.
  • Do not blanket-ignore unused imports in every __init__.py or silence security asserts in production code.
  • Type-checker config: use the installed tool's current schema (older keys may be gone); keep cache/venv exclusions only where justified.

Preview shortened. The full SKILL.md is in the pack.