Python 标准库之 typing (类型标注)

2022-10-03 08:25:59

PEP 3107引入了功能注释的语法,PEP 484 加入了类型检查

标准库 typing 为类型提示指定的运行时提供支持。
示例:

deff(a:str, b:int)->str:return a* b

在这里插入图片描述
如果实参不是预期的类型:
在这里插入图片描述

但是,Python运行时不强制执行函数和变量类型注释。使用类型检查器,IDE,lint等才能帮助代码进行强制类型检查。

使用NewType 创建类型

NewType() 是一个辅助函数,用于向类型检查器指示不同的类型,在运行时,它返回一个函数,该函数返回其参数。

import typing

Id= typing.NewType("Id",int)
a= Id(2020)

使用NewType() 创建的类型会被类型检查器视为它的原始类型的子类。

回调(Callable)

将回调函数类型标注为Callable[[Arg1Type, Arg2Type], ReturnType]

from typingimport Callabledeff(a:int)->str:returnstr(a)defcallback(a:int, func: Callable[[int],str])->str:return func(a)print(callback(1, f))

泛型

为容器元素添加预期的类型

from typingimport Mapping
a: Mapping[str,str]

在这里插入图片描述
通过TypeVar 进行参数化来约束一个类型集合:

from typingimport TypeVar

T= TypeVar('T')# 可以是任何东西。
A= TypeVar('A',str,bytes)# 必须是 str 或 bytes

在这里插入图片描述
使用TypeVar 约束一个类型集合,但不允许单个约束
例如:

T= TypeVar('T',str)

这样会抛出一个异常TypeError: A single constraint is not allowed

typing 包含的类型

AbstractSet = typing.AbstractSet
Any = typing.Any
AnyStr = ~AnyStr
AsyncContextManager = typing.AbstractAsyncContextManager
AsyncGenerator = typing.AsyncGenerator
AsyncIterable = typing.AsyncIterable
AsyncIterator = typing.AsyncIterator
Awaitable = typing.Awaitable
ByteString = typing.ByteString
Callable = typing.Callable
ClassVar = typing.ClassVar
Collection = typing.Collection
Container = typing.Container
ContextManager = typing.AbstractContextManager
Coroutine = typing.Coroutine
Counter = typing.Counter
DefaultDict = typing.DefaultDict
Deque = typing.Deque
Dict = typing.Dict
FrozenSet = typing.FrozenSet
Generator = typing.Generator
Hashable = typing.Hashable
ItemsView = typing.ItemsView
Iterable = typing.Iterable
Iterator = typing.Iterator
KeysView = typing.KeysView
List = typing.List
Mapping = typing.Mapping
MappingView = typing.MappingView
MutableMapping = typing.MutableMapping
MutableSequence = typing.MutableSequence
MutableSet = typing.MutableSet
NoReturn = typing.NoReturn
Optional = typing.Optional
Reversible = typing.Reversible
Sequence = typing.Sequence
Set = typing.Set
Sized = typing.Sized
TYPE_CHECKING = False
Tuple = typing.Tuple
Type = typing.Type
Union = typing.Union
ValuesView = typing.ValuesView
  • 作者:Jairoguo
  • 原文链接:https://blog.csdn.net/Jairoguo/article/details/105184509
    更新时间:2022-10-03 08:25:59