Python basics FAQ¶
Short answers, with pointers to the code. Only questions that matter for the AI labs. New questions are added as they come up.
Scope¶
How much Python do I need before starting the labs?¶
- Enough to read a list of dicts, write a function with type hints, and explain
fn(**args). - Scripts 01 and 02 cover that. Do 03–05 before
llm-api's later examples, 06 beforemcp-server, and 08 beforeagents/07_langgraph.py. - This folder is grown from what the labs use. When a new topic adds a Python feature, it gets added here.
Why Python and not TypeScript for the labs?¶
- Most AI libraries (Ollama, Chroma, Pydantic, eval tools) ship Python first.
- Even the MCP server is Python, so one venv runs every lab. The mcp-server FAQ shows the same tool in TypeScript.
Data and functions¶
Why is everything a dict?¶
- The model's API is JSON, and JSON objects map one-to-one to Python dicts. Messages, tool calls and tool results are all dicts.
- Inside your own code, prefer typed objects (
@dataclass, Pydantic) once data is validated. See05_classes_and_pydantic.py.
What does ** do in fn(**args)?¶
It spreads a dict into keyword arguments: get_price(**{"sku": "X", "quantity": 2}) is get_price(sku="X", quantity=2). This is how the agent loop calls the tool the model asked for. See 02_functions.py.
Does Python check my type hints?¶
- No, not at run time. They are documentation for people, editors and the model (Ollama builds the tool schema from them).
- To enforce types on model input, use Pydantic. See
02_functions.pyand05_classes_and_pydantic.py.
What does @something above a def do?¶
@tooloverdef get_stockrunsget_stock = tool(get_stock)once, when the file loads.- A registering decorator files the function and returns it unchanged:
@mcp.tool()inmcp-server,@app.post("/ask")inship. See02_functions.py. - A wrapping decorator returns a new function around the old one, like the retry in
04_errors_and_retries.py.
What does := do?¶
It assigns and tests in one step: if (p := find_product(sku)) is None: looks the product up once and keeps it. The guards and checks use it often. See 02_functions.py.
Model output¶
Why not just json.loads the model's reply?¶
- The reply can include a
<think>block, markdown fences, extra sentences or Python-style quotes. - Strip and extract first (
parse_model_jsonin03_json.py), or better, constrain the output with a schema (schema=in09_putting_it_together.py).
Pydantic accepted the model's output. Is it correct?¶
- It has the right shape and types, not the right facts. A well-formed SKU may not exist.
- Check facts in your code (
price_orderin09_putting_it_together.pyreports "Unknown SKU").
LangGraph¶
Why is LangGraph in a Python basics folder?¶
- LangGraph itself is taught in
agents. This folder covers only the Python it is built on:TypedDict,Annotatedreducers, partial updates and closures. - Those four make
lg_agent.pyreadable; without them it looks like magic. See08_state_and_graphs.py.
What does Annotated[list, operator.add] do?¶
- It tells LangGraph how to combine a node's update with the current state:
operator.addappends lists instead of replacing them. - Keys without a reducer are simply overwritten.
- Forget it on
messagesand every node wipes the conversation.merge()in08_state_and_graphs.pyis the same logic in 6 lines.
Async¶
When do I need async?¶
- When code waits on the network and several waits can overlap: parallel tool calls, MCP clients, streaming servers.
- For a simple script making one model call at a time, plain sync code is fine (
llm-apiis mostly sync). - See
06_async_and_parallel.py.
What is the difference between async and threads?¶
async / gather |
ThreadPoolExecutor |
|
|---|---|---|
| Works with | async libraries (await ...) |
any blocking function |
| Used in | mcp-server |
llm-api/02_parallel_calls.py |
| Common mistake | a blocking call inside async def freezes everything |
sharing mutable state between threads |