Python 標準庫之 typing (類型標註)

PEP 3107引入了功能註釋的語法,PEP 484 加入了類型檢查

標準庫 typing 爲類型提示指定的運行時提供支持。
示例:

def f(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 typing import Callable

def f(a: int) -> str:
    return str(a)

def callback(a: int, func: Callable[[int], str]) -> str:
    return func(a)

print(callback(1, f))

泛型

爲容器元素添加預期的類型

from typing import Mapping
a: Mapping[str, str]

在這裏插入圖片描述
通過 TypeVar 進行參數化來約束一個類型集合:

from typing import 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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章