目录
一、简单介绍
Optional
和 Generic
都是 Python 类型提示(type hinting)系统的一部分,用于增强代码的可读性和类型安全性,但它们有不同的用途和作用:
1.1 Optional用法及样例
- 定义:
Optional
是typing
模块中的一个类型别名,用于表示一个值可以是某种类型,也可以是None
。 - 用法:
Optional[X]
等价于Union[X, None]
,表示该值可以是类型X
或None
。
from typing import Optional
def get_user(user_id: int) -> Optional[str]:
users = {1: "Alice", 2: "Bob"}
return users.get(user_id)
# 返回值可以是字符串或 None
user = get_user(3)
if user is None:
print("User not found")
else:
print(f"User found: {user}")