sagelearnai

The Python You Actually Need

Python is the lingua franca of AI. You don't need to be a Python expert, but a handful of language features show up in nearly every AI codebase. This lesson covers the ones you'll use daily.

Data structures you'll use constantly

python
# Lists: ordered, mutable. Message histories, batches of documents.
messages = [{"role": "user", "content": "Hi"}]
messages.append({"role": "assistant", "content": "Hello!"})

# Dicts: key → value. JSON payloads, configs, metadata.
chunk = {"id": "doc1#3", "text": "Refunds take 5 days.", "meta": {"source": "faq.md"}}
source = chunk["meta"].get("source", "unknown")   # .get avoids KeyError

# Sets: fast membership, dedup.
seen_ids = set()
if chunk["id"] not in seen_ids:
    seen_ids.add(chunk["id"])

# Tuples: immutable, often returned from functions.
score, doc_id = 0.83, "doc1#3"

Comprehensions are the idiomatic way to transform collections:

python
texts = [c["text"] for c in chunks if len(c["text"]) > 20]
by_id = {c["id"]: c for c in chunks}

Functions, type hints and dataclasses

Type hints don't change runtime behavior, but they make code readable and let editors and tools catch bugs. AI code passes lots of nested data around, so they pay off quickly.

python
from dataclasses import dataclass, field

@dataclass
class Chunk:
    id: str
    text: str
    score: float = 0.0
    meta: dict = field(default_factory=dict)   # never use a mutable default directly

def top_k(chunks: list[Chunk], k: int = 5) -> list[Chunk]:
    return sorted(chunks, key=lambda c: c.score, reverse=True)[:k]

For data coming from outside your program (API responses, LLM JSON output), prefer Pydantic models, which validate as well as describe (Lesson 4).

Files and paths

python
from pathlib import Path
docs = {p.name: p.read_text(encoding="utf-8") for p in Path("docs").glob("**/*.md")}
Path("out").mkdir(exist_ok=True)
Path("out/summary.txt").write_text("done\n", encoding="utf-8")

Always pass encoding="utf-8". LLM work is full of non-ASCII text.

Generators: process big data lazily

python
import json
def read_jsonl(path):
    with open(path, encoding="utf-8") as f:
        for line in f:
            if line.strip():
                yield json.loads(line)          # one record at a time, constant memory

def batched(items, n):
    batch = []
    for x in items:
        batch.append(x)
        if len(batch) == n:
            yield batch; batch = []
    if batch:
        yield batch

for batch in batched(read_jsonl("corpus.jsonl"), 64):
    embed(batch)                                # e.g. embed 64 documents per API call

Concurrency: async for many API calls

LLM calls spend most of their time waiting on the network. Running them one by one wastes time; asyncio lets you run many concurrently, while a semaphore caps concurrency so you stay under rate limits.

python
import asyncio

async def classify(client, text, sem):
    async with sem:                                  # at most N in flight
        resp = await client.chat.completions.create(
            model="gpt-4o-mini",
            messages=[{"role": "user", "content": f"Sentiment of: {text}\nAnswer positive/negative."}])
        return resp.choices[0].message.content

async def main(texts):
    from openai import AsyncOpenAI
    client, sem = AsyncOpenAI(), asyncio.Semaphore(8)
    return await asyncio.gather(*(classify(client, t, sem) for t in texts))

results = asyncio.run(main(["great!", "awful", "fine I guess"]))
WorkloadTool
Many network calls (APIs)asyncio or a ThreadPoolExecutor
CPU-heavy work (parsing big PDFs)multiprocessing / ProcessPoolExecutor
Numeric arraysNumPy (vectorized, written in C)

NumPy in 60 seconds

Embeddings are just arrays of floats, and NumPy is how you work with them fast:

python
import numpy as np
E = np.random.rand(10_000, 384).astype("float32")      # 10k embeddings
E /= np.linalg.norm(E, axis=1, keepdims=True)           # normalize rows
q = E[42]                                               # a query vector
scores = E @ q                                          # 10k cosine similarities, one line
top5 = np.argsort(-scores)[:5]

Vectorized operations like E @ q are often 100× faster than Python loops.

Error handling you'll actually need

python
try:
    data = json.loads(model_output)
except json.JSONDecodeError as e:
    log.warning("bad JSON from model: %s", e)
    data = None

Catch specific exceptions. A bare except: hides bugs such as typos, and even Ctrl-C.

Last reviewed 2026-11-05.