类型提示是工具可以检查的文档
Python 是动态类型的:变量可以保存任何东西,错误的类型只有在那一行运行时才暴露,也许正在交易日中途。类型提示让你写下函数期望什么、返回什么:def mid_price(bid: float, ask: float) -> float。Python 运行时会忽略它们。它们的价值在于:编辑器和 mypy、pyright 这样的静态检查器会读取它们,在代码运行之前就警告错误的调用;而且它们比容易过时的注释更好地说明了函数。
# 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 /容器、None 与联合类型
内置容器在方括号中给出元素类型:list[float]、dict[str, float]、tuple[str, float](每个位置一个类型)。可能缺失的值写成 float | None,这迫使调用者处理 None;如果不先检查就把结果当数字用,检查器会报错。在函数内部,if x is None: return 会收窄类型,后面的代码就知道它是 float。对于只读的参数,宁可用 Sequence[float](列表、元组)这样的通用类型而非 list[float],这样适配更多调用者;返回值则用具体类型,如 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 quotes数据的形状与检查器的工作
像订单这样键固定的字典,最好把它描述清楚,而不是只写 dict。TypedDict 或 dataclass 为每个字段及其类型命名,这样像 order["quantiy"] 这样的拼写错误会在编辑器里报错,而不是在 15:59 变成 KeyError。检查器从命令行运行(mypy main.py),它会打印代码与提示相矛盾的每个位置并以非零状态退出,因此能融入你之后会遇到的自动化检查。提示可以逐步添加:Any 会关闭对某个值的检查,没有类型的代码会被直接跳过。提示本身也是数据,工具可在运行时用 typing.get_type_hints 读取,本实验正是这样检查它们的。
# 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]- 提示(
bid: float、-> float)为函数提供文档,运行时被忽略;mypy 这样的检查器会读取它们。 - 容器带元素类型(
list[tuple[str, float]]);缺失值是float | None;只读参数可用通用的Sequence[float]。 - 记录用
TypedDict或dataclass,在自动化检查中运行检查器,同时仍要校验外部数据并测试数字。
下一节:用 pytest 测试,包括 fixture、参数化用例,以及让策略保持诚实的检查。
实验:评分内容
- 在
mid_price中为数字加类型提示25 分 - 在
best_quote中为容器标注类型25 分 - 在
safe_ratio中允许缺失值25 分 - 让
apply_fee接受任意序列25 分