使用Pyright检查以下代码:
from typing import Union, TypeVar
T = TypeVar('T')
X_or_RecurListOf = Union[T, list['X_or_RecurListOf']]
x: X_or_RecurListOf[str] = ['asd']生成以下错误:
5:28 - error: Expression of type "list[str]" cannot be assigned to declared type "X_or_RecurListOf[str]"
Type "list[str]" cannot be assigned to type "X_or_RecurListOf[str]"
"list[str]" is incompatible with "str"
TypeVar "_T@list" is invariant
Type "str" cannot be assigned to type "X_or_RecurListOf[Type[T@X_or_RecurListOf]]"
Type "str" cannot be assigned to type "T@X_or_RecurListOf"
"str" is incompatible with "list[X_or_RecurListOf]" (reportGeneralTypeIssues)
1 error, 0 warnings, 0 infos
Completed in 0.677sec我做错了什么吗?
发布于 2021-03-04 17:10:11
哦,我找到Pyright跌跌撞撞的地方了!
它希望在递归定义中包含类型参数:
X_or_RecurListOf = Union[T, list['X_or_RecurListOf[T]']] -注意[T]!
我不明白为什么这是必要的,但它对我来说是有效的,特别是因为我真正指的是X_or_RecurListOf[T]而不是X_or_RecurListOf[Any]。
https://stackoverflow.com/questions/66460376
复制相似问题