MyPy v1.1.0使用TypeAlias报错,是否属于Bug?
MyPy 1.1.0 使用 TypeAlias 时的类型错误问题
当在MyPy 1.1.0中使用TypeAlias定义联合类型后,尝试将该类型别名赋值给标注为type[StrBytes]的变量时,出现了类型不兼容错误。
代码示例
from typing import TypeAlias StrBytes: TypeAlias = str | bytes var: type[StrBytes] = StrBytes
MyPy 错误提示
error: Incompatible types in assignment (expression has type "<typing special form>", variable has type "type[str] | type[bytes]")
问题解析
这不属于MyPy的Bug,是对type[]和TypeAlias的用法理解偏差导致的:
- TypeAlias是类型的别名,
StrBytes代表的是str | bytes这个联合类型本身,而非该类型的类型对象。 type[StrBytes]表示的是StrBytes对应类型的类型对象集合,也就是type[str] | type[bytes]。但直接赋值StrBytes时,它指向的是str | bytes这个类型表达式(属于typing特殊形式),并非对应的类型对象。
正确写法
如果你的意图是让var存储str或bytes的类型对象,应该这样写:
from typing import TypeAlias # 直接定义类型对象的联合别名 StrBytesType: TypeAlias = type[str] | type[bytes] var: StrBytesType = str # 或赋值bytes
如果你的意图是让var是StrBytes类型的实例,那应该去掉type[]:
from typing import TypeAlias StrBytes: TypeAlias = str | bytes var: StrBytes = "test" # 或b"test",符合联合类型的实例要求
内容的提问来源于stack exchange,提问作者Napoleon Cornejo
相关产品推荐
相关产品推荐

