类型注解
类型注解用来标注变量、参数和返回值的类型。它不会影响运行,但能让编辑器给出更准确的提示,也方便用工具提前发现错误。
def greet(name: str, times: int = 1) -> str:
return ("你好," + name + "!") * times
count: int = 0
names: list[str] = ["a", "b"]
scores: dict[str, float] = {"math": 95.5}
可选值与联合类型
def find_user(user_id: int) -> dict | None:
...
def parse(value: int | str) -> int:
return int(value)
自定义类型
from typing import TypedDict
class User(TypedDict):
name: str
age: int
def show(u: User) -> None:
print(u["name"], u["age"])
静态检查
$ pip install mypy
$ mypy app.py
app.py:12: error: Argument 1 to "greet" has incompatible type "int"; expected "str"
建议从新写的函数开始逐步加注解,不必一次性给整个项目补齐。
练习题
学完本节后,试着独立完成下面的练习,再展开参考答案对照。
练习 1 为函数 average(nums) 添加类型注解:参数是浮点数列表,空列表时返回 None。
查看参考答案
def average(nums: list[float]) -> float | None:
if not nums:
return None
return sum(nums) / len(nums)
print(average([1.5, 2.5, 3.0]), average([]))参考输出:
2.3333333333333335 None