使用方式
from typing import List
T1 = List[str]
def test(t1: T1, t2: List[str]):
print(t1[0].title())
print(t2[0].title())
创建新类型 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
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
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
from typing import Union, Sequence
# int
def t1(t: Sequence[int]):
pass
可调用类型 Callable
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
from typing import Union
# str或int
def t1(t: Union[str, int]):
pass
可选类型 Optional
from typing import Optional
# t的类型可以是int
def t1(t: Optional[int] = None):
pass