Python3.11+如何实现NotRequired[Optional[T]]的泛型别名Possibly[T]?
在TypedDict中实现Possibly[T]泛型别名的解决方案
核心问题
NotRequired[T]表示TypedDict的键可缺失,Optional[T]表示键存在时值可为None。在MongoDB场景中,若无需区分二者,想要将NotRequired[T | None]简写为Possibly[T],需解决mypy对该泛型别名的识别问题。
可行实现方案
方法1:Python 3.11+ 兼容写法(需mypy v1.0+)
通过TypeVar定义泛型,直接创建别名:
from typing import TypeVar, TypedDict, NotRequired, Optional # 定义泛型变量 T = TypeVar('T') # 定义Possibly[T] 等价于 NotRequired[T | None] Possibly = NotRequired[Optional[T]] # 使用示例 class MongoDocument(TypedDict): username: str # 表示该键可缺失,或存在时为int/None age: Possibly[int] # 表示该键可缺失,或存在时为str/None bio: Possibly[str]
方法2:Python 3.12+ 简洁写法
利用Python 3.12新增的泛型别名语法,定义更直观:
from typing import TypeVar, TypedDict, NotRequired T = TypeVar('T') # 明确声明泛型别名 type Possibly[T] = NotRequired[T | None] # 使用示例 class MongoDocument(TypedDict): username: str age: Possibly[int] bio: Possibly[str]
注意事项
- 确保mypy版本不低于v1.0,旧版本可能无法正确识别
NotRequired与泛型的结合。 - 若仍有报错,检查
mypy.ini配置,指定正确的Python版本:[mypy] python_version = 3.11 strict = true
内容的提问来源于stack exchange,提问作者Jonathan Herrera
相关产品推荐
相关产品推荐

