SkilVaultSign inStart free

Catalogue / pythonic-patterns

pythonic-patterns

Older skill: source not recordedSignedGuides the writing of modern, fully type-annotated Python — annotated signatures, dataclasses for data modeling, signature-preserving decorators, asyncio concurrency, context managers, lazy generators, and deliberate exception design. Trigger when the agent writes, reviews, or refactors Python code…
---
name: pythonic-patterns
description: Guides the writing of modern, fully type-annotated Python — annotated signatures, dataclasses for data modeling, signature-preserving decorators, asyncio concurrency, context managers, lazy generators, and deliberate exception design. Trigger when the agent writes, reviews, or refactors Python code involving type hints, data modeling, decorator construction, async/await, or error handling. Not intended for other languages or general Python environment troubleshooting.
---

Pythonic Patterns

Apply these rules whenever you create or modify Python source files.

Start from a modern baseline

  1. Assume Python 3.10 or newer unless the user says otherwise. Use built-in generic aliases (list[str], dict[str, int]) and the pipe union operator (str | None) instead of importing Optional, Union, List, or Dict from typing.
  2. Annotate every function you write — parameters and return type. Pick a concrete type first; resort to Any only at true dynamic boundaries (raw JSON, plugins) and narrow it immediately afterward.
def format_amount(cents: int, currency: str = "USD") -> str:
    return f"{cents / 100:.2f} {currency}"

def lookup_order(order_id: str) -> Order | None:
    return orders.get(order_id)

Model data with dataclasses

  1. Reach for @dataclass before hand-writing __init__, __repr__, or __eq__.
  2. Give mutable fields a default_factory, validate in __post_init__, add frozen=True for value objects, and slots=True when many small instances exist.
from dataclasses import dataclass, field

@dataclass(frozen=True, slots=True)
class Coordinate:
    lat: float
    lon: float

@dataclass
class Playlist:
    title: str
    tracks: list[str] = field(default_factory=list)

    def __post_init__(self) -> None:
        if not self.title.strip():
            raise ValueError("playlist title cannot be empty")

Use advanced typing tools deliberately

  1. Use Literal for closed sets of values, TypedDict for dictionary shapes, and Protocol when you want duck-typed interfaces without inheritance. For generic code, use TypeVar, or the 3.12 inline [T] syntax when targeting 3.12+, and subclass Generic[T] for generic classes.
from typing import Literal, Protocol, TypedDict

SortDir = Literal["asc", "desc"]

class Serializable(Protocol):
    def to_json(self) -> str: ...

class Forecast(TypedDict):
    city: str
    high_c: float

def head[T](items: list[T]) -> T | None:
    return items[0] if items else None

Build decorators that preserve signatures

  1. Apply functools.wraps to every inner function so names, docstrings, and introspection survive. Type decorators with ParamSpec and a return TypeVar. For decorators that take arguments, write a factory that returns the actual decorator.
from functools import wraps
from typing import Callable, ParamSpec, TypeVar
import time

P = ParamSpec("P")
R = TypeVar("R")

def timed(func: Callable[P, R]) -> Callable[P, R]:
    @wraps(func)
    def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
        started = time.perf_counter()
        try:
            return func(*args, **kwargs)
        finally:
            print(f"{func.__name__}: {time.perf_counter() - started:.3f}s")
    return wrapper

def announce(prefix: str) -> Callable[[Callable[P, R]], Callable[P, R]]:
    def decorate(func: Callable[P, R]) -> Callable[P, R]:
        @wraps(func)
        def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
            print(f"{prefix}{func.__name__} starting")
            return func(*args, **kwargs)
        return wrapper
    return decorate

Handle concurrency with asyncio

  1. Mark I/O-bound work async def and run it concurrently with asyncio.gather; cap parallelism with a Semaphore.
  2. Pass return_exceptions=True to gather when partial failure is tolerable, then filter the outcome.
  3. Never run blocking calls (CPU-heavy loops, synchronous file or network libraries) directly inside an event loop — offload them with asyncio.to_thread.
import asyncio

async def load_user(user_id: int) -> dict[str, str]: ...

async def load_all(user_ids: list[int], cap: int = 8) -> list[dict[str, str] | None]:
    gate = asyncio.Semaphore(cap)

    async def guarded(uid: int) -> dict[str, str] | None:
        async with gate:
            try:
                return await load_user(uid)
            except KeyError:
                return None

    return list(await asyncio.gather(*(guarded(u) for u in user_ids)))

Wrap setup and teardown in context managers

  1. Use the generator form from contextlib.contextmanager for short resource lifetimes; write a class with __enter__/__exit__ when the resource carries state you must expose. Reach for asynccontextmanager inside coroutines. Always release the resource in a finally block.
from collections.abc import Iterator
from contextlib import contextmanager

@contextmanager
def connected(uri: str) -> Iterator[Session]:
    session = Session.open(uri)
    try:
        yield session
    finally:
        session.close()

Prefer lazy generation over materializing lists

  1. Write generators (yield) when consumers iterate once. Slice with itertools.islice rather than truncating lists. Sort the input before itertools.groupby, because it only groups adjacent equal keys.
from collections.abc import Iterable, Iterator
from itertools import count, islice

def row_ids(start: int = 1) -> Iterator[int]:
    yield from count(start)

sample = list(islice(row_ids(), 50))

def chunked(items: Iterable[int], size: int) -> Iterator[list[int]]:
    stream = iter(items)
    while (piece := list(islice(stream, size))):
        yield piece

Design errors on purpose

  1. Define a small exception hierarchy rooted in one project base class and attach machine-readable context as attributes.
  2. Chain failures with raise NewError(...) from cause when translating exceptions, so the original traceback survives.
  3. Reserve an Ok | Err-style tagged union for internal APIs where try/except noise would dominate; do not force it everywhere.
class AppFailure(Exception):
    code: str = "APP_FAILURE"

class ConfigMissing(AppFailure):
    code = "CONFIG_MISSING"

def read_config(path: str) -> dict[str, str]:
    try:
        return parse(read_text(path))
    except OSError as cause:
        raise ConfigMissing(f"cannot read {path}") from cause

Guardrails — what you must never do

  • Never write a mutable default argument (a list or dict literal as a parameter default); always use a factory.
  • Never catch a bare, unnamed exception merely to silence it, and never discard the original context when re-raising.
  • Never present code as "typed" while scattering Any to dodge the type checker.
  • Never execute the project's scripts, run its test suite, or install and add dependencies while applying these patterns unless the user explicitly asks; before any step that modifies files, contacts the network, or touches credentials, stop and get the user's confirmation.
  • Never fetch code from the network and run it in a shell to "verify" a pattern, and never read, print, or copy secrets into examples or logs.

Self-check before finishing

  • Every new signature annotated, with no legacy container imports from typing.
  • Data shaped by dataclasses; mutable defaults created via factories.
  • Decorators preserve metadata through wraps.
  • Async paths never block the event loop.
  • Errors are specific, chained, and never swallowed silently.