类型分析中None与type(None)是否等价?矛盾场景解析
关于PEP 484中None与type(None)类型提示矛盾的疑问
根据PEP 484的「使用None」章节:在类型提示中,表达式None被视为与type(None)等价。
但实际使用时遇到了二者不等价的场景,先看核心简化案例:
from typing import Type a: Type[None] # 这段代码会触发类型检查错误: # main.py:4: error: Incompatible types in assignment (expression has type "None", variable has type "type[None]") [assignment] # Found 1 error in 1 file (checked 1 source file) a = None # 这段代码则完全正常 a = type(None)
更完整的原始场景代码如下:
from typing import Callable, NamedTuple, Type, Union # 定义可用返回类型集合: ReturnType = Union[ int, None, ] # 用该Union类型定义可调用类型 SomeCallableType = Callable[..., ReturnType] # 用NamedTuple存储函数元数据(含返回类型): class FuncInfos(NamedTuple): return_type: Type[ReturnType] # 此代码正常: fi_1 = FuncInfos(return_type=int) # 此代码报错: # main.py:21: error: Argument "return_type" to "FuncInfos" has incompatible type "None"; expected "type[int] | type[None]" [arg-type] # Found 1 error in 1 file (checked 1 source file) fi_2 = FuncInfos(return_type=None) # 此代码正常: fi_3 = FuncInfos(return_type=type(None))
虽然用type(None)替代None可以解决问题,但想弄明白为什么这个报错会和PEP 484的规定看似矛盾。
内容的提问来源于stack exchange,提问作者vmonteco
相关产品推荐
相关产品推荐

