05
Python Idioms That Win Points
Type hints
from typing import Callable, Optional
def retry(fn: Callable[[], dict], max_attempts: int = 3) -> Optional[dict]:
for attempt in range(max_attempts):
try: return fn()
except Exception:
if attempt == max_attempts - 1: raise
time.sleep(2 ** attempt)
Dataclasses
from dataclasses import dataclass
@dataclass
class ToolCall:
name: str
arguments: dict
id: str
result: Optional[str] = None
defaultdict & Counter
from collections import defaultdict, Counter
calls_per_user = defaultdict(list)
calls_per_user[user_id].append(call)
popular = Counter(c.name for c in calls)
top3 = popular.most_common(3)