Hints are documentation a tool can check
Python is dynamically typed: a variable can hold anything, and a wrong type shows up only when the line runs, perhaps in the middle of a trading day. Type hints let you write down what a function expects and returns: def mid_price(bid: float, ask: float) -> float. Python itself ignores them when running. Their value is that an editor and a static checker such as mypy or pyright read them and warn you about a wrong call before the code ever runs, and that they document the function better than a comment that goes stale.
# Hints describe the function; Python does not enforce them when it runs
def mid_price(bid: float, ask: float) -> float:
return (bid + ask) / 2
print(mid_price(100.0, 100.5)) # 100.25
print(mid_price.__annotations__) # {'bid': <class 'float'>, 'ask': <class 'float'>, 'return': <class 'float'>}
print(mid_price(10, 12)) # 11.0 an int is accepted where float is hinted
try:
mid_price("a", "b") # a checker flags this line before the code runs
except TypeError as error:
print("only fails when it runs:", error) # only fails when it runs: unsupported operand type(s) for /Containers, None and unions
Built-in containers take their element types in brackets: list[float], dict[str, float], tuple[str, float] (one type per position). A value that may be missing is float | None, which forces the caller to handle None; the checker complains if they use the result as a number without checking first. Inside the function, an if x is None: return narrows the type so the rest is known to be a float. For arguments you only read, prefer a general type such as Sequence[float] (lists, tuples) over list[float], so more callers fit; return a concrete type, like list[float].
# Containers, an optional result, and narrowing with an is None check
def best_quote(quotes: list[tuple[str, float]]) -> tuple[str, float] | None:
if not quotes:
return None
return min(quotes, key=lambda quote: quote[1])
def describe(quotes: list[tuple[str, float]]) -> str:
best = best_quote(quotes)
if best is None: # after this check the checker knows best is a tuple
return "no quotes"
venue, price = best
return f"{venue} at {price:.2f}"
print(describe([("XNAS", 100.02), ("ARCX", 100.01)])) # ARCX at 100.01
print(describe([])) # no quotesShapes of data, and the checker at work
A dictionary with fixed keys, such as an order, is better described than left as dict. A TypedDict or a dataclass names every field and its type, so a typo like order["quantiy"] is an error in your editor instead of a KeyError at 15:59. You run the checker from the command line (mypy main.py); it prints each place where the code contradicts its hints and exits non-zero, so it fits in the automated checks you will meet later. Hints can be added gradually: Any turns checking off for a value, and untyped code is simply skipped. The hints are also data, so tools can read them at runtime with typing.get_type_hints, which is exactly how this lab checks them.
# A TypedDict names the fields of an order; the checker would flag order["quantiy"]
from typing import TypedDict
class Order(TypedDict):
symbol: str
quantity: int
price: float
def notional(order: Order) -> float:
return order["quantity"] * order["price"]
order: Order = {"symbol": "AAPL", "quantity": 100, "price": 184.5}
print(notional(order)) # 18450.0
print(Order.__annotations__) # {'symbol': <class 'str'>, 'quantity': <class 'int'>, 'price': <class 'float'>}# The hints can be read at run time, which is how tools (and this lab) inspect a function
import typing
def apply_fee(prices: typing.Sequence[float], fee_rate: float = 0.001) -> list[float]:
return [price * (1 + fee_rate) for price in prices]
hints = typing.get_type_hints(apply_fee)
print(hints["fee_rate"], hints["return"]) # <class 'float'> list[float]
print(typing.get_origin(hints["prices"]).__name__) # Sequence
print(apply_fee((100.0, 200.0))) # a tuple is accepted: [100.1, 200.2]- Hints (
bid: float,-> float) document a function and are ignored when Python runs it; a checker like mypy reads them. - Containers take element types (
list[tuple[str, float]]); a missing value isfloat | None; read-only arguments can be a generalSequence[float]. - Use
TypedDictordataclassfor records, run the checker in your automated checks, and still validate external data and test the numbers.
Next up: testing with pytest, fixtures, parametrised cases and the checks that keep a strategy honest.
Lab · what's graded
- Annotate numbers with
mid_price25 pts - Type a container with
best_quote25 pts - Admit a missing value in
safe_ratio25 pts - Accept any sequence in
apply_fee25 pts