如何解决Pyright 的递归类型别名
使用 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
我做错了吗?
还是我误解了 announcement for support of recursive types in Pyright?
解决方法
哦,我发现了 Pyright 绊倒的东西!
它希望在递归定义中有类型参数:X_or_RecurListOf = Union[T,list['X_or_RecurListOf[T]']]
- 注意 [T]
!
我不明白为什么这是必要的,但它对我有用,尤其是因为我真正的意思是 X_or_RecurListOf[T]
而不是 X_or_RecurListOf[Any]
。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。