Functions, Type Hints & Decorators

~15 min read

Typed Python functions with clear signatures are essential for AI codebases. Type hints enable IDE autocomplete and make LLM-assisted coding significantly more effective.

def process_text(text: str, max_length: int = 512) -> list[str]: is a typed Python function. Type hints are not enforced at runtime but enable IDE autocomplete and catch bugs. Decorators (@) wrap functions — @torch.no_grad() is the most common AI decorator, disabling gradient tracking during inference to save memory. @dataclass creates structured config objects with less boilerplate.

💻 Code example

from typing import Optional
from dataclasses import dataclass

@dataclass
class ModelConfig:
    model: str = "claude-opus-4-5"
    max_tokens: int = 1024
    temperature: float = 0.7

def chunk_text(
    text: str,
    chunk_size: int = 512,
    overlap: int = 50
) -> list[str]:
    """Split text into overlapping chunks for RAG."""
    words = text.split()
    return [
        " ".join(words[i:i + chunk_size])
        for i in range(0, len(words), chunk_size - overlap)
    ]

💬 Deep Dive with AI

Key points

  • Type hints: def fn(x: str, n: int = 10) -> list[str]
  • @dataclass for config objects — cleaner than plain dicts
  • @torch.no_grad() during inference — reduces memory by 30–50%
  • Optional[str] means the parameter can be str or None