类型注解

4 阅读2分钟

明白了,你是 Python 3.9+ 版本。这意味着你可以直接使用内置泛型,无需从 typing 导入 ListDictTupleSet 等,写法更简洁。

下面针对 Python 3.9+ 重新整理类型注解的核心内容。


Python 3.9+ 类型注解(简洁版)

一、内置泛型(直接使用)

旧写法(需导入)Python 3.9+ 推荐写法
from typing import List
names: List[str]
names: list[str]
from typing import Dict
info: Dict[str, int]
info: dict[str, int]
from typing import Tuple
pair: Tuple[int, str]
pair: tuple[int, str]
from typing import Set
unique: Set[int]
unique: set[int]
from typing import FrozenSetfrozenset[int]
from typing import Iterable, Sequencecollections.abc.Iterable[int](仍需导入,但推荐用 abc

示例

def process_items(items: list[str], mapping: dict[str, int]) -> tuple[bool, str]:
    ...

二、仍需从 typing 导入的类型

部分类型尚未成为内置泛型,仍需要导入:

  • OptionalUnionAnyCallableTypeVarGenericProtocol

但 Python 3.10+ 中 Union 可以用 | 代替,Optional 可以用 T | None 代替。

Python 3.10+ 进一步简化(联合类型)

# 旧写法
from typing import Optional, Union
def get_value(key: str) -> Optional[int]: ...
def parse(data: Union[str, int]) -> float: ...

# Python 3.10+ 推荐
def get_value(key: str) -> int | None: ...
def parse(data: str | int) -> float: ...

你用的是 Python 3.9,还不能使用 X | Y 语法(3.10 引入),但可以使用 typing.Union 或等到升级。


三、Python 3.9+ 类型注解完整示例

# 不需要导入 List, Dict, Tuple
def greet_all(names: list[str]) -> None:
    for name in names:
        print(f"Hello, {name}")

def get_user_info(user_id: int) -> dict[str, str | int]:
    return {"id": user_id, "name": "Alice", "age": 30}

def split_name(full_name: str) -> tuple[str, str] | None:
    parts = full_name.split()
    if len(parts) == 2:
        return (parts[0], parts[1])
    return None

四、类中的类型注解(3.9+)

class Student:
    name: str
    scores: list[float]

    def __init__(self, name: str, scores: list[float]) -> None:
        self.name = name
        self.scores = scores

    def average(self) -> float:
        return sum(self.scores) / len(self.scores) if self.scores else 0.0

五、类型别名(依然清晰)

UserId = int
UserInfo = dict[str, str | int]   # Python 3.9 中 Union 需从 typing 导入,或用 typing.Union

def get_user(uid: UserId) -> UserInfo | None:
    ...

六、总结(Python 3.9+ 最佳实践)

  • ✅ 用 list[str] 代替 List[str]
  • ✅ 用 dict[str, int] 代替 Dict[str, int]
  • ✅ 用 tuple[int, str] 代替 Tuple[int, str]
  • ✅ 用 set[float] 代替 Set[float]
  • ✅ 用 type[N] 表示类对象(Python 3.9+ 也支持)
  • ⚠️ Union, Optional, Callable 等仍需从 typing 导入(除非升级到 3.10+ 用 | 语法)
  • ⚠️ collections.abc.Iterable 等仍需导入,但推荐使用标准库 collections.abc

充分利用 Python 3.9+ 的简洁语法,让类型注解更易读、更现代。