python模块typing的作用


一、介绍

Python是一门弱类型的语言,很多时候我们可能不清楚函数参数类型或者返回值类型,很有可能导致一些类型没有指定方法,在写完代码一段时间后回过头看代码,很可能忘记了自己写的函数需要传什么参数,返回什么类型的结果,就不得不去阅读代码的具体内容,降低了阅读的速度,typing模块可以很好的解决这个问题

typing模块的作用:

自python3.5开始,PEP484为python引入了类型注解(type hints)

  • 类型检查,防止运行时出现参数和返回值类型不符合。
  • 作为开发文档附加说明,方便使用者调用时传入和返回参数类型。
  • 该模块加入后并不会影响程序的运行,不会报正式的错误,只有提醒pycharm目前支持typing检查,参数类型错误会黄色提示

二、常用类型

  • int,long,float: 整型,长整形,浮点型;

  • bool,str: 布尔型,字符串类型;

  • List, Tuple, Dict, Set:列表,元组,字典, 集合;

  • Iterable,Iterator:可迭代类型,迭代器类型;

  • Generator:生成器类型;

三、常用代码

from typing import List, Union

def func(a: int, string: str) -> List[int or str]:
    list1 = []
    list1.append(a)
    list1.append(string)
    return list1

# 使用or关键字表示多种类型,也可以用Union
def get_next_id(id:int) -> Union[int, None]:
    if not isinstance(id ,int):
        return
    if id>1:
        return id
    return None

print(func(88,"999"))
print(get_next_id(999))

#pycharm会在传入的参数上黄色提示
print(func(88,["999"]))
print(get_next_id('999'))


原文链接:https://www.cnblogs.com/angelyan/p/11121859.html