Typing 模块

979 字
5 分钟
Typing 模块

1. 概述#

  Python 的 typing 模块是用于类型提示(Type Hints)的标准库,自 Python 3.5 起引入。它不会在运行时强制类型检查,但可以配合工具(如 mypy、IDE 等)提升代码可读性、健壮性和开发效率。

  从 Python 3.9 开始,标准库对内置容器类型(如 listdictsettuple 等)进行了增强,使其原生支持泛型语法(即可以直接写成 dict[str, int] 这样的形式),而不再需要从 typing 模块导入对应的 DictListSetTuple 等。

2. 快速查阅#

推荐语法是否可直接用内置名?替代方案(新语法)说明
容器类型(Collections)
list[T]✅ 是(≥3.9)内置泛型,无需导入 typing.List
dict[K, V]✅ 是(≥3.9)内置泛型,替代 typing.Dict
set[T]✅ 是(≥3.9)内置泛型,替代 typing.Set
tuple[T, ...]tuple[A, B, C]✅ 是(≥3.9)内置泛型,替代 typing.Tuple
frozenset[T]✅ 是(≥3.9)内置泛型
联合与可选类型
T | None✅ 是(≥3.10)推荐替代 Optional[T]
Optional[T]❌ 否T | NonePython 3.10+ 起建议用 `
A | B✅ 是(≥3.10)推荐替代 Union[A, B]
Union[A, B, C]❌ 否A | B | C旧写法,兼容性好但冗长
通用类型
Any❌ 否表示任意类型,需 from typing import Any
Callable[[A, B], R]❌ 否描述函数签名,仍需从 typing 导入
泛型与类型变量
TypeVar('T')❌ 否from typing import TypeVar,用于泛型函数/类
Generic[T]❌ 否from typing import Generic(但 typing.Generic 在 ≥3.9 可配合内置泛型使用)
字面量与结构化类型
Literal['read', 'write']❌ 否from typing import Literal(或 typing_extensions for <3.8)
TypedDict❌ 否from typing import TypedDict,用于带键类型约束的字典
新类型与协议
NewType('UserId', int)❌ 否from typing import NewType,创建语义不同的类型别名
Protocol❌ 否from typing import Protocol(≥3.8),用于结构子类型(鸭子类型)
其他
Iterable[T], Iterator[T]❌ 否抽象基类(如 collections.abc 中的类型)仍需从 typing 导入(尽管部分在 ≥3.9 可用 collections.abc 直接泛型化,但 typing 版本更常用)

2.1. 基本容器类型#

用于标注列表、字典、元组等容器中元素的类型。

from typing import List, Dict, Tuple, Set
# 列表:元素必须是 int
def process_numbers(nums: List[int]) -> None:
for n in nums:
print(n)
# 字典:键为 str,值为 int
scores: Dict[str, int] = {"Alice": 95, "Bob": 87}
# 元组:固定长度和类型
point: Tuple[float, float] = (3.14, 2.71)
# 集合
unique_ids: Set[int] = {1, 2, 3}

⚠️ 注意:从 Python 3.9+ 开始,可以直接使用内置类型如 list[int],无需导入 List


2.2. Optional(可选类型)#

表示“可能是某类型,也可能是 None”。

from typing import Optional
def find_user(user_id: int) -> Optional[str]:
if user_id == 1:
return "Alice"
return None # 可返回 None

等价于 Union[str, None]


2.3. Union(联合类型)#

表示“可以是多种类型之一”。

from typing import Union
def parse_value(value: Union[int, str]) -> str:
return str(value)
# Python 3.10+ 可简写为 value: int | str

2.4. Any(任意类型)#

关闭类型检查,适用于不确定类型的场景(不推荐滥用)。

from typing import Any
def log_anything(data: Any) -> None:
print("Received:", data)

2.5. Callable(函数类型)#

用于标注接受或返回函数的参数/返回值。

from typing import Callable
def apply_operation(x: int, func: Callable[[int], int]) -> int:
return func(x)
double = lambda n: n * 2
print(apply_operation(5, double)) # 输出 10

2.6. TypeVar(泛型)#

定义泛型函数或类,保持类型一致性。

from typing import TypeVar
T = TypeVar('T')
def first_element(items: List[T]) -> T:
return items[0]
# 推断出返回类型与输入列表元素类型一致
names: List[str] = ["Alice", "Bob"]
first: str = first_element(names)

2.7. Literal(字面量类型)#

限制变量只能取特定值。

from typing import Literal
FileMode = Literal['r', 'w', 'a', 'rb']
def open_file(mode: FileMode) -> None: ...

2.8. NewType(创建新类型)#

创建语义上不同的类型(即使底层相同),增强类型安全。

from typing import NewType
UserId = NewType('UserId', int)
BookId = NewType('BookId', int)
def get_user(user_id: UserId) -> str:
return f"User {user_id}"
uid = UserId(123)
bid = BookId(456)
get_user(uid) # ✅ 正确
get_user(bid) # ❌ 类型检查器会报错(虽然运行时是 int)

2.9. TypedDict(结构化字典)#

为字典指定每个键的类型(类似接口)。

from typing import TypedDict
class Person(TypedDict):
name: str
age: int
email: str
p: Person = {"name": "Alice", "age": 30, "email": "alice@example.com"}

支持与分享

如果这篇文章对你有帮助,欢迎分享给更多人或赞助支持!

赞助
Typing 模块
https://kianzhao.site/posts/python-typing/
作者
Kian Zhao
发布于
2026-05-06
许可协议
CC BY-NC-SA 4.0
Profile Image of the Author
Kian Zhao
Hello, I'm Kian Zhao.
公告
欢迎来到我的博客!这是一则示例公告。
音乐
封面

音乐

暂未播放

0:00 0:00
暂无歌词
分类
标签
站点统计
文章
19
分类
6
标签
22
总字数
23,111
运行时长
0
最后活动
0 天前

目录