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
- 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 importingOptional,Union,List, orDictfromtyping. - Annotate every function you write — parameters and return type. Pick a concrete type first; resort to
Anyonly 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
- Reach for
@dataclassbefore hand-writing__init__,__repr__, or__eq__. - Give mutable fields a
default_factory, validate in__post_init__, addfrozen=Truefor value objects, andslots=Truewhen 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
- Use
Literalfor closed sets of values,TypedDictfor dictionary shapes, andProtocolwhen you want duck-typed interfaces without inheritance. For generic code, useTypeVar, or the 3.12 inline[T]syntax when targeting 3.12+, and subclassGeneric[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 NoneBuild decorators that preserve signatures
- Apply
functools.wrapsto every inner function so names, docstrings, and introspection survive. Type decorators withParamSpecand a returnTypeVar. 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 decorateHandle concurrency with asyncio
- Mark I/O-bound work
async defand run it concurrently withasyncio.gather; cap parallelism with aSemaphore. - Pass
return_exceptions=Truetogatherwhen partial failure is tolerable, then filter the outcome. - 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
- Use the generator form from
contextlib.contextmanagerfor short resource lifetimes; write a class with__enter__/__exit__when the resource carries state you must expose. Reach forasynccontextmanagerinside coroutines. Always release the resource in afinallyblock.
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
- Write generators (
yield) when consumers iterate once. Slice withitertools.islicerather than truncating lists. Sort the input beforeitertools.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 pieceDesign errors on purpose
- Define a small exception hierarchy rooted in one project base class and attach machine-readable context as attributes.
- Chain failures with
raise NewError(...) from causewhen translating exceptions, so the original traceback survives. - Reserve an
Ok | Err-style tagged union for internal APIs wheretry/exceptnoise 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 causeGuardrails — 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
Anyto 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.
| File | Size | SHA-256 |
|---|---|---|
| SKILL.md | 7.6 kB | 1ea640e54152 |
| examples.json | 942 B | 778d900c27a7 |
Published verbatim from the pinned commit. Nothing is rewritten.
| Version | Pinned commit | Signed | |
|---|---|---|---|
| 0.1.1 Current | Not recorded | 2 Oct 2026 | |
| 0.1.0 | Not recorded | 3 Oct 2026 |
Locking a skill to one version needs Pro.