【问题标题】:Recursive type aliases with PyrightPyright 的递归类型别名
【发布时间】:2021-03-03 15:46:36
【问题描述】:

使用 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

【问题讨论】:

    标签: type-alias python-3.9 pyright


    【解决方案1】:

    哦,我发现了 Pyright 的绊脚石!

    它希望在递归定义中有类型参数:
    X_or_RecurListOf = Union[T, list['X_or_RecurListOf[T]']] - 注意[T]

    我不明白为什么这是必要的,但它对我有用,尤其是我的意思是 X_or_RecurListOf[T] 而不是 X_or_RecurListOf[Any]

    【讨论】:

      猜你喜欢
      • 2012-11-09
      • 2018-05-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多