类型注解
自python3.5开始,PEP484为python引入了类型注解(type hints)。类型检查,防止运行时出现参数和返回值类型、变量类型不符合。作为开发文档附加说明,方便使用者调用时传入和返回参数类型。该模块加入后并不会影响程序的运行,不会报正式的错误,只有提醒pycharm目前支持typing检查,参数类型错误会黄色提示。
常见类型
- int,long,float: 整型,长整形,浮点型
- bool,str: 布尔型,字符串类型
- List, Tuple, Dict, Set:列表,元组,字典, 集合
- Iterable,Iterator:可迭代类型,迭代器类型
- Generator:生成器类型
通用示例
from typing import List
Vector = List[float]
def scale(scalar: float, vector: Vector) -> Vector:
return [scalar * num for num in vector]
# typechecks; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])
泛型示例
from typing import Sequence, TypeVar, Union
T = TypeVar('T') # Declare type variable
def first(l: Sequence[T]) -> T: # Generic function
return l[0]
T = TypeVar('T') # Can be anything
A = TypeVar('A', str, bytes) # Must be str or bytes
A = Union[str, None] # Must be str or None