一个典型示例:
def surface_area_of_cube(edge_length: float) -> str:
return f"The surface area of the cube is {6 * edge_length ** 2}."
表示surface_area_of_cube()函数期望入参edge_length是float对象,函数返回值会是一个str对象。
typing模块文档:https://docs.python.org/zh-cn/3.13/library/typing.html
typing模块提供了更多提示类。
typing_extensions的pypi网址:https://pypi.org/project/typing-extensions/
typing_extensions提供了typing包向后兼容的能力。
以下内容主要根据我随时用到的就写点,会持续更新。
1. 定义类别别名
可以简化长定义。type语句是在Python 3.12之后才提出的,向下兼容代码见后文。
type Vector = list[float]
def scale(scalar: float, vector: Vector) -> Vector:
return [scalar * num for num in vector]
# 通过类型检查;浮点数列表是合格的 Vector。
new_vector = scale(2.0, [1.0, -4.2, 5.4])
简化效果示例:
from collections.abc import Sequence
type ConnectionOptions = dict[str, str]
type Address = tuple[str, int]
type Server = tuple[Address, ConnectionOptions]
def broadcast_message(message: str, servers: Sequence[Server]) -> None:
...
# 静态类型检查器会认为上面的类型签名
# 完全等价于下面这个写法。
def broadcast_message(
message: str,
servers: Sequence[tuple[tuple[str, int], dict[str, str]]]
) -> None:
...
type 语句是在 Python 3.12 中新增加的。 为了向下兼容,类型别名也可以通过简单的赋值来创建:
Vector = list[float]
或者用 TypeAlias 标记来显式说明这是一个类型别名,而非一般的变量赋值:
from typing import TypeAlias
Vector: TypeAlias = list[float]
2. 提示可调用(Callable)对象
因为直接将function类作为类型提示的话会报错,所以需要用typing库打的包才行。我之前撰写的对报错信息的讲解博文见:NameError: name ‘function’ is not defined
函数 – 或是其他 callable 对象 – 可以使用 collections.abc.Callable 或已被弃用的 typing.Callable 来标注。 Callable[[int], str]
表示一个接受 int 类型的单个形参并返回一个 str 的函数。
typing.Callable 示例:
from typing import Union, Callable
def extract_number_from_prediction(predict_function:Callable[[str], Union[int,float]],question:str,prediction:str):
...
collections.abc.Callable示例:
from collections.abc import Callable, Awaitable
def async_query(on_success: Callable[[int], None],
on_error: Callable[[int, Exception], None]) -> None:
...
3. Any 类型
Any 是一种特殊的类型。静态类型检查器认为所有类型均与 Any 兼容,同样,Any 也与所有类型兼容。
也就是说,可对 Any 类型的值执行任何操作或方法调用,并赋值给任意变量。
未指定返回值与参数类型的函数,都隐式地默认使用 Any。
示例:
from typing import Any
def foo(item: Any) -> int:
# 通过类型检查;'item' 可以为任意类型,
# 并且其类型会具有 'bar' 方法
item.bar()
...
注意,Any 类型的值赋给更精确的类型时,不执行类型检查。如下代码中,把 a 赋给 s,在运行时,即便 s 已声明为 str 类型,但接收 int 值时,静态类型检查器也不会报错:
from typing import Any
a: Any = None
a = [] # 可以
a = 2 # 可以
s: str = ''
s = a # 可以
4. 模块内容
1. 特殊形式
1. typing.Union
联合类型; Union[X, Y]
等价于 X | Y
,意味着满足 X 或 Y 之一。
要定义一个联合类型,可以使用类似 Union[int, str]
或简写 int | str
。建议使用这种简写。
2. typing.Optional
Optional[X]
等价于 X | None
(或 Union[X, None]
) 。
示例代码:
def foo(arg: Optional[int] = None) -> None:
...