Python Idioms
Pythonic idioms and patterns every AI engineer should know: comprehensions, generators, context managers, and clean code.
Last updated
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