python-typing模块

typing 是在 python 3.5 才有的模块

常用类型提示

前两行小写的不需要 import,后面三行都需要通过 typing 模块 import 

  • int,long,float: 整型,长整形,浮点型;
  • bool,str: 布尔型,字符串类型;
  • List, Tuple, Dict, Set:列表,元组,字典, 集合;
  • Iterable,Iterator:可迭代类型,迭代器类型;
  • Generator:生成器类型;

 注意:当List[str]时里面有多个时只有写一个即可,当为Tuple[str, ...]里面有多个时需要添加 ...

 

Union

联合类型

Union[int, str] 表示既可以是 int,也可以是 str 。没有顺序的说法

 

Optional

可选类型,参数可传可不传,注意 Optional[] 里面只能写一个数据类型。

t: Optional[int] = None

和默认参数有什么不一样

  • 官方原话:可选参数具有默认值,具有默认值的可选参数不需要在其类型批注上使用 Optional,因为它是可选的
  • 不过 Optional 和默认参数其实没啥实质上的区别,只是写法不同
  • 使用 Optional 是为了让 IDE 识别到该参数有一个类型提示,可以传指定的类型和 None,且参数是可选非必传的

 

Callable

是一个可调用对象类型

查看对象是否可调用语法

isinstance(对象, Callable)

Callable type; Callable[[int], str] is a function of (int) -> str.
  • 第一个类型(int)代表参数类型
  • 第二个类型(str)代表返回值类型

栗子

get_func: Callable[[str], None]

 

TypeVar 泛型

T = TypeVar['T',str, int]

def __init__(self, name, *constraints, bound=None,
covariant=False, contravariant=False):

Type

 

Type[Union[类对象]]  只能时Union中的类对象

A special construct usable to annotate class objects.

For example, suppose we have the following classes::

class User: ... # Abstract base for User classes
class BasicUser(User): ...
class ProUser(User): ...
class TeamUser(User): ...

And a function that takes a class argument that's a subclass of
User and returns an instance of the corresponding class::

U = TypeVar('U', bound=User)
def new_user(user_class: Type[U]) -> U:
user = user_class()
# (Here we could write the user object to a database)
return user

joe = new_user(BasicUser)

At this point the type checker knows that joe has type BasicUser.


posted @ 2021-10-20 13:01  mik99  阅读(650)  评论(0编辑  收藏  举报