Read Code Fast
Lesson 8 Types as a table of contents
read the types and signatures before the code
What you'll learn
- Read signatures and field lists before reading any body
- Say what an optional or nullable type asks of the caller
- Find the places where a type is only a claim: casts, any and outside data
Before you read a function body, read its signature. In typed code, the types are a table of contents, and they cost you nothing.
The idea
A signature tells you what goes in, what comes out, and what can go wrong, without reading one line of the body. In TypeScript these are the parameter and return types. In Python they are type hints and dataclasses. Order | undefined or Order | None says "the caller must handle not found". Promise<...> says "this is async". A list of fields says what an order is.
But types are a claim, not a proof. TypeScript types vanish when the code runs, and Python never checks hints at all. A cast (as, **data) or any turns the checking off. So read the types first, then ask where they could be lying: data from outside, and casts.
1from dataclasses import dataclass, field23@dataclass4class OrderLine:5 sku: str6 qty: int7 price: float89@dataclass10class Order:11 id: str12 lines: list[OrderLine] = field(default_factory=list)13 coupon_code: str | None = None1415def find_order(order_id: str) -> Order | None:16 data = repo.get(order_id)17 if data is None:18 return None19 return Order(**data)
- Line 10 The table of contents: an order has an id, a list of lines, and maybe a coupon code. No function read yet.
- Line 13
str | Nonesays the coupon may be missing. Every use of it must cope with that. - Line 15 The signature: the answer may be
None. So callers must check before they use it. - Line 19 Python never checks hints.
Order(**data)accepts any value types, and only complains about unknown field names.
Take away
- Read signatures and field lists first: they say what goes in, what comes out, and what can be missing.
| undefined,| Noneand?mean "handle the missing case".- Types are a claim: ask what checks them when data comes from outside, or goes through a cast.
Quiz: test yourself
7 questions: a quick quiz, then a review drill. Pick an answer to see why it's right.