本文阅读量 次
1. Python 的类型系统
1.1 概述
名称 | 解释 | 备注 |
TypeVar | 定义或声明类型变量 | |
Type | 声明目标是一个类,而不是实例 | |
TypedDict | | |
TypeAlias | 对已有类型声明一个别名 | |
TypeGuard | | |
Generic | 在类、函数或数据中声明使用了类型变量 | |
1.2 不同版本的差异
特性 | Python 3.8 | Python 3.9 | Python 3.10+ |
Annotated | 声明在 typing_extensions 中 | 声明在 typing 中 | |
Union | 声明在 typing 中 | 声明在 typing 中 | 直接使用 | |
List | 声明在 typing 中 | 声明在 typing 中 | 直接使用 list |
Optional | | | |
1.3 TypeVar
from typing import List, TypeVar
T = TypeVar('T')
def first_and_last(items: List[T]) -> T:
return items[0]
result = first_and_last([1, 2, 3, 4]) # result: int
1.4 Type
from typing import Type
class Animal:
@classmethod
def make_sound(cls):
pass
def mimic(animal_class: Type[Animal]): # animal_class is a class, not an instance
animal_class.make_sound()
mimic(Animal)
1.5 TypeGuard
from typing import Any, TypeGuard
def is_integer(value: Any) -> TypeGuard[int]:
return isinstance(value, int)
from typing import List, Union, TypeGuard
def is_string_list(values: List[Union[int, str]]) -> TypeGuard[List[str]]:
return all(isinstance(value, str) for value in values)
def process(values: List[Union[int, str]]):
if is_string_list(values):
# Within this block, 'values' is treated as List[str] by the type checker
concatenated = " ".join(values)
print(concatenated)
else:
# Here, 'values' is still List[Union[int, str]]
print("List contains non-string values.")
1.6 Generic
from typing import Generic, TypeVar
T = TypeVar('T')
class Box(Generic[T]):
def __init__(self, item: T):
self.item = item
class Container(Generic[T]):
def __init__(self, value: T):
self.value = value
box_int = Box(5) # box_int: Box[int], class Box(item: int)
box_str = Box("Hello") # box_str: Box[str], class Box(item: str)
# This allows for type-safe operations on the container
int_container = Container[int](5)
str_container = Container[str]("Hello")
1.7 参考