typing使用

官方文檔: typing
注: typing是python3.5(PEP484)開始的
可用於: 類型檢查器、集成開發環境、靜態檢查器等, 但是不強制使用

使用方式

兩種使用方式

  1. 別名: 先定義=, 再使用:
  2. 直接使用: :
from typing import List

T1 = List[str]


def test(t1: T1, t2: List[str]):
    print(t1[0].title())
    print(t2[0].title())

創建新類型 NewType

主要用於類型檢測
NewType(name, tp) 返回其原本的值
靜態類型檢查器會將新類型看作是原始類型的一個子類
即: name是新的類型 tp是原始類型
注: 在python3.10之前NewType是普通的函數, 之後是一個類, 會產生一個類, 返回的原來的值, 故不會對常規函數產生影響

from typing import NewType, NoReturn

# 創建int的子類, 名為UserId
UserIdType = NewType('UserId', int)


# 使用
def name_by_id(user_id: UserIdType) -> NoReturn:
    print(user_id)


# 類型檢測錯誤
UserIdType('user')

# 類型檢測成功, 返回原類型 "int"
num = UserIdType(5)

# 類型檢測錯誤, 需要傳入UserIdType, 而不是int
name_by_id(42)
# 類型檢測成功
name_by_id(UserIdType(42))  # OK

類型變數 TypeVar

類型變數主要用於泛型類型與泛型函數定義的參數
第一個參數是名稱, 其他參數是類型

from typing import TypeVar, Sequence

# 任意類型
T = TypeVar('T')
# 必須是str或bytes
A = TypeVar('A', str, bytes)


# (any, int) -> [any, ...]
def repeat(x: T, n: int) -> Sequence[T]:
    return [x] * n


# (str/bytes, str/bytes) -> str/bytes
def longest(x: A, y: A) -> A:
    return x if len(x) >= len(y) else y

元祖 Tuple

使用場景

  1. 有限元素: Tuple[X, Y], 即第一個元素類型為X, 第二個元素類型為Y
  2. 空元組: Tuple[()]
  3. 可用...指定任意個同類: Tuple[int, ...]即多個int元素的元組
  4. 不指定時(Tuple)等價於Tuple[Any, ...]
from typing import Tuple


# 任意類型元組
def t1(t: Tuple):
    pass


# 全為字元串的元組
def t2(t: Tuple[str, ...]):
    pass


# 多個類型有 "..." 時為任意類型
def t3(t: Tuple[str, int, ...]):
    pass

列表 List

使用方式如上的Tuple

from typing import List


# 任意類型
def t1(t: List):
    pass


# 全為字元串
def t2(t: List[str, ...]):
    pass


# 多個類型有 "..." 時為任意類型
def t3(t: List[str, int, ...]):
    pass

字典 Dict

定義形式: Dict[key類型, val類型]

from typing import Dict


# key為字元串 value為int
def t1(t: Dict[str, int]):
    pass
	

集合 Set

不能使用...
最多只能有一個參數, 即只能有一種類型

from typing import Set


# 任意類型
def t1(t: Set):
    pass


# 字元串
def t2(t: Set[str]):
    pass

序列類型 Sequence

使用注意點與Set相同

from typing import Union, Sequence


# int
def t1(t: Sequence[int]):
    pass

可調用類型 Callable

即可調用對象
定義形如: Callable[[Arg1Type, Arg2Type], ReturnType], 第一個參數是列表 值為可調用對象的參數類型, 第二個參數是返回值

from typing import Callable


def test(c: Callable[[int, str], str]):
    res = c(1, "a")
    # 1a <class 'str'>
    print(res, type(res))


def func(a: int, b: str) -> str:
    return str(a) + b


test(func)

任意類型 Any

任意類型

from typing import Any


# 任意類型
def t1(a: Any, b: ...):
    pass


t1(1, 2)
t1("a", "b")

無返回值 NoReturn

標記沒有返回值的函數

from typing import NoReturn

def stop() -> NoReturn:
    raise RuntimeError('no way')
	

聯合類型 Union

即必須是指定的類型

聯合中的聯合會被展平: Union[Union[int, str], float] == Union[int, str, float]
單參數即本身: Union[int] == int
冗餘參數跳過: Union[int, str, int] == Union[int, str] == int | str
無順序: Union[int, str] == Union[str, int]

from typing import Union


# str或int
def t1(t: Union[str, int]):
    pass

python3.10之後可以寫成X | Y, 不需要額外導入Union

可選類型 Optional

即可以是指定的類型

含默認值的可選參數不需要在類型註解上添加 Optional 限定符
默認值為None時, 可以用Optional

from typing import Optional


# t的類型可以是int
def t1(t: Optional[int] = None):
    pass

Tags: