1:1 mentoring with Big Tech AI engineers
Python

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

defaultdict & Counter

Related

More in Python

Get full access to all 87+ sections with code examples, diagrams, and interactive animations.

Unlock Premium