一、基礎類型提示
1. 基本類型注解
# 變量類型注解
age: int = 30
name: str = "Alice"
is_student: bool = False
height: float = 1.75
2. 函數注解
def greet(name: str, age: int) -> str:return f"Hello {name}, you are {age} years old!"
二、組合類型
1. 聯合類型(Union)
from typing import Union# value 可以是整數或浮點數
def format_number(value: Union[int, float]) -> str:return f"{value:.2f}"# 或者使用簡寫 |(Python 3.10+)
def format_number(value: int | float) -> str:return f"{value:.2f}"
2. 可選類型(Optional)
from typing import Optionaldef find_user(id: int) -> Optional[str]:# 返回值可以是字符串或 Nonereturn user_db.get(id, None)
三、容器類型
1. 列表(List)
from typing import List# 整數列表
scores: List[int] = [90, 85, 95]# 混合類型列表(不推薦,盡量避免)
values: List[Union[int, str]] = [1, "two", 3]
2. 元組(Tuple)
from typing import Tuple# 固定結構元組
point: Tuple[float, float] = (3.5, 7.2)# 可變長度元組
points: Tuple[float, ...] = (1.0, 2.5, 3.7)
3. 字典(Dict)
from typing import Dict# 鍵為字符串,值為整數的字典
student_grades: Dict[str, int] = {"Alice": 90, "Bob": 85}# 復雜字典
person: Dict[str, Union[str, int]] = {"name": "Alice", "age": 30}
四、特殊類型
1. 字面值類型(Literal)
from typing import Literal# 參數只能是特定值
def set_direction(direction: Literal["up", "down", "left", "right"]) -> None:print(f"Moving {direction}")set_direction("up") # 正確
set_direction("north") # 類型檢查錯誤
# 注意:Python 的類型注解(包括 Literal)只對類型檢查工具有效,不會影響實際運行,所以兩個輸出都正常。
2. 類型別名(TypeAlias)
# 創建類型別名(Python 3.10+)
from typing import TypeAliasCoordinate: TypeAlias = Tuple[float, float]def distance(a: Coordinate, b: Coordinate) -> float:return ((a[0]-b[0])**2 + (a[1]-b[1])**2)**0.5
五、泛型與高級類型
1. 可調用對象(Callable)
from typing import Callable# 簡單函數類型
Adder: Callable[[int, int], int] = lambda x, y: x + ydef add(x: int, y: int) -> int:return x + ydef apply_twice(func: Callable[[int, int], int], x: int, y: int) -> int:return func(func(x, y), func(x, y))print(apply_twice(add, 2, 3)) # Output: 10
def create_adder(n: int) -> Callable[[int, int], int]:def add(x: int, y: int) -> int:return x + y + nreturn addprint(create_adder(5)(2, 3)) # Output: 10
2. Iterable, Sequence, Mapping
from typing import Iterable, Sequence, Mapping# Iterable(可迭代對象)
def sum_all(values: Iterable[int]) -> int:return sum(values)# Sequence(支持索引的集合)
def get_middle(items: Sequence[str]) -> str:return items[len(items)//2]# Mapping(類似字典的結構)
def find_value(data: Mapping[str, int], key: str) -> int:return data.get(key, 0)
六、結構化類型
1. TypedDict(類型化字典)
from typing import TypedDict, Listclass Person(TypedDict):name: strage: inthobbies: List[str]alice: Person = {"name": "Alice","age": 30,"hobbies": ["reading", "hiking"]
}
2. NamedTuple(命名元組)
from typing import NamedTupleclass Point(NamedTuple):x: floaty: floatz: float = 0.0 # 默認值p = Point(1.5, 2.5)
print(p.x, p.y) # 1.5 2.5
七、動態類型相關
1. Any(任意類型)
from typing import Anydef process_data(data: Any) -> Any:# 此函數接受和返回任何類型的值if isinstance(data, list):return data[0]return data
2. Type(類類型)
from typing import Type, TypeVarT = TypeVar('T')def create_instance(cls: Type[T]) -> T:return cls()class Widget: pass
widget = create_instance(Widget)
十、Python 3.10+ 改進
Python 3.10 引入了更簡潔的類型提示語法:
# 聯合類型簡化
def format_value(value: int | float | str) -> str:return str(value)# 類型別名簡化
type Coordinate = tuple[float, float]# 參數化泛型
def first(items: list[T]) -> T:return items[0]