1. 基础类型
-
指定参数类型和返回值类型:
def greeting(name: str) -> str: return 'hello ' + name
-
序列
def scale(scalar: float, vector: list) -> list: return [scalar * num for num in vector] >> scale(3, [1, 2, 3]) [3, 6, 9]
但 list 本身是一个容器,对其内的元素是没有类型限制的,如果我们想指定元素类型为 float 的 list;
2. List、Tuple 与 Dict
-
元素类型为 float 的 list;
from typing import List, Tuple, Dict def scale(scalar: float, vector: List[float]) -> List[float]: return [scalar * num for num in vector]
-
使用别名以简化复杂函数签名:
from typing import Dict, Tuple, List ConnectionOptions = Dict[str, str] # str 类型的 key,str 类型的 value Address = Tuple[str, int] # 二元 tuple Server = Tuple[Address, ConnectionOptions] def broadcast_message(message: str, servers: List[Server]) -> None: ... # The static type checker will treat the previous type signature as # being exactly equivalent to this one. def broadcast_message( message: str, servers: List[Tuple[Tuple[str, int], Dict[str, str]]]) -> None: ...