查阅Python 中 typing 模块和类型注解的使用 | 静觅得知typing里的Dict是用来让python能像C++一样强申明变量类型的。
names: list = ['Germey', 'Guido']
version: tuple = (3, 7, 4)
operations: dict = {'show': False, 'sort': True}
以上代码:只知道 names 是一个列表 list 类型,但是不知道 names 里面的元素是str类型还是int类型;也不知道 operations这个字典的key和value是什么类型的。只能知道operations是一个字典。
但如果用typing 模块,它提供了非常 “强 “的明确类型申明,比如 List[str]
表示由 str 类型的元素组成的列表,Tuple[int, int, int]
是由 int 类型的元素组成的长度为 3 的元组。所以用typing申明以上字典的代码如下:
from typing import List, Tuple, Dict
names: List[str] = ['Germey', 'Guido']
version: Tuple[int, int, int] = (3, 7, 4)
operations: Dict[str, bool] = {'show': False, 'sort': True}