typing

官网

测试

tutorial

注意这个annotation只是起到一个提示的作用,并不会对函数的执行,参数的校验起到真正的效果

def f(ham: str, eggs: str='eggs') -> str:

callable

官网

测试代码

from collections.abc import Callable

def call_int(x: str) -> str:
    return x + '1'

f: Callable[[float], float]

f = call_int

Literal

Mode: TypeAlias = Literal['r', 'rb', 'w', 'wb']
def open(file: str, mode: Mode):
    pass

基础

可以直接用圆括号

from typing import Tuple, List, Dict, Set
def get_tuple() -> Tuple[int, int]:
    pass
def get_list() -> List[int]:
    pass
def get_dict() -> Dict[int: int]:
    pass
def get_set() -> Set[int]:
    pass

返回List

def add(number: int) -> int:
    return number + 1
## 数字构成的数组
list[int]  # python3 >= 3.10
from typing import List
List[int]  # python3 <= 3.8

多选

from typing import Literal
GenderType = Literal["male", "female"]

Union

from typing import Union
Union[User, None]

NetType

VersionName = NewType("VersionName", str)
version: VersionName = VersionName("1.1.1")
  • 区分两种int

from typing import NewType
UserId = NewType("UserId", int)
AttackPoint = NewType("AttackPoint", int)

def attack(target: UserId, atk: AttackPoint):
    if not atk:
        atk = AttackPoint(1)
    user = User.objects.get(id=UserId)
    user.healph -= atk
    user.save()

TypedDict

官网

class Point2D(TypedDict):
    x: int
    y: int
    label: str

overload

函数重载, 示例

from typing import overload
@overload
def process(response: None) -> None:
    ...
@overload
def process(response: int) -> tuple[int, str]:
    ...
@overload
def process(response: bytes) -> str:
    ...
def process(response):
    ...  # actual implementation goes here

ClassVar

classvar可以防止覆盖类型和类型错误。但是无法防止不赋值

class A:
    count: ClassVar[int]

函数和装饰器

cast

运行时不做任何转化,只是用来给编辑器进行提示

typing.cast(List[int], py_(tasks).filter(lambda x: isinstance(x, int)).value())

assert_type

运行时没啥用,只是给编辑器提示

assert_type(name, str)