明白了,你是 Python 3.9+ 版本。这意味着你可以直接使用内置泛型,无需从 typing 导入 List、Dict、Tuple、Set 等,写法更简洁。
下面针对 Python 3.9+ 重新整理类型注解的核心内容。
Python 3.9+ 类型注解(简洁版)
一、内置泛型(直接使用)
| 旧写法(需导入) | Python 3.9+ 推荐写法 |
|---|---|
from typing import Listnames: List[str] | names: list[str] |
from typing import Dictinfo: Dict[str, int] | info: dict[str, int] |
from typing import Tuplepair: Tuple[int, str] | pair: tuple[int, str] |
from typing import Setunique: Set[int] | unique: set[int] |
from typing import FrozenSet | frozenset[int] |
from typing import Iterable, Sequence | collections.abc.Iterable[int](仍需导入,但推荐用 abc) |
示例:
def process_items(items: list[str], mapping: dict[str, int]) -> tuple[bool, str]:
...
二、仍需从 typing 导入的类型
部分类型尚未成为内置泛型,仍需要导入:
Optional、Union、Any、Callable、TypeVar、Generic、Protocol等
但 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+ 的简洁语法,让类型注解更易读、更现代。