Section 87.1: 为函数添加类型
让我们以一个函数为例,该函数接收两个参数,并返回一个表示这两个参数之和的值:
def two_sum(a, b):
return a + b
通过观察这段代码,我们无法确定函数 twoo_sum 的参数类型。当提供 int 值时,它都能工作:
print(two_sum(2, 1)) # result: 3
和字符串
print(two_sum("a", "b")) # result: "ab"

和其他值,如 lists、tuples 等。
由于 python 类型的动态性质,许多类型都适用于给定的操作,因此任何类型检查程序都无法合理地断言是否允许调用此函数。
为了帮助类型检查程序,我们现在可以在函数定义中提供类型提示,说明我们允许的类型。
为了表明我们只允许使用 int 类型,我们可以将函数定义修改如下
def two_sum(a: int, b: int):
return a + b
注释跟在参数名称后面,并用“: ”字符分隔。
同样,如果只允许使用 str 类型,我们可以修改函数来指定它:
def two_sum(a: str, b: str):
return a + b
除了指定参数类型外,还可以指明函数调用的返回值。具体做法是在参数列表的结尾括号之后、函数声明的结尾“: ”之前添加“->”字符,后面跟上类型:
def two_sum(a: int, b: int) -> int:
return a + b
现在,我们已经指出调用 two_sum 时的返回值应为 int 类型。同样,我们也可以为 str、float、list、set 等定义适当的值。
虽然类型提示主要由类型检查程序和集成开发环境使用,但有时您可能需要检索它们。这可以使用 __annotations__特殊属性来实现:
two_sum.__annotations__
# {'a': <class 'int'>, 'b': <class 'int'>, 'return': <class 'int'>}

Section 87.2: 命名元组
使用 typing 模块中的函数 NamedTuple 可以创建带有类型提示的命名元组:
import typing
Point = typing.NamedTuple('Point', [('x', int), ('y', int)])

请注意,结果类型的名称是函数的第一个参数,但应将其赋值给一个同名变量,以方便类型检查程序的工作。
Section 87.3: 通用类型
typeping.TypeVar 是一个通用类型工厂。它的主要目标是作为泛型函数/类/方法注解的参数/占位符:
import typing
T = typing.TypeVar("T")
def get_first_element(l: typing.Sequence[T]) -> T:
"""Gets the first element of a sequence."""
return l[0]

Section 87.4: 变量和属性
使用注释对变量进行注释:
x = 3 # type: int
x = negate(x)
x = 'a type-checker might catch this error'
Python 3.x Version ≥ 3.6
从 Python 3.6 开始,变量注解也有了新的语法。上面的代码可能使用
x: int = 3
与注释不同的是,也可以只为一个未声明的变量添加类型提示,而不为其设置值:
y: int
此外,如果在模块或类级别使用了这些提示,则可使用 typing.get_type_hints(class_or_module) 获取类型提示:
class Foo:
x: int
y: str = 'abc'
print(typing.get_type_hints(Foo))
# ChainMap({'x': <class 'int'>, 'y': <class 'str'>}, {})

另外,也可以使用 __annotations__ 专用变量或属性来访问它们:
x: int
print(__annotations__)
# {'x': <class 'int'>}
class C:
s: str
print(C.__annotations__)
# {'s': <class 'str'>}

Section 87.5: 类成员和方法
class A:
x = None # type: float
def __init__(self, x: float) -> None:
"""
不应注解 self
init 应注释为返回 None
"""
self.x = x
@classmethod
def from_int(cls, x: int) -> 'A':
"""
cls 不应加注释
使用前向引用,以字符串字面意义 “A ”来引用当前类
"""
return cls(float(x))

由于注释是在定义函数时进行评估的,因此需要对当前类进行前向引用。
当引用一个类时,如果导入该类会导致循环导入,也可以使用前向引用。
Section 87.6: 关键字参数的类型提示
def hello_world(greeting: str = 'Hello'):
print(greeting + ' world!')

注意等号周围的空格,这与关键字参数通常的样式不同。