Псевдонимы рекурсивного типа с 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

Я делаю что-то не так?
Или я неправильно понял объявление о поддержке рекурсивных типов в Pyright?


person Min-Soo Pipefeet    schedule 03.03.2021    source источник


Ответы (1)


О, я нашел то, о что спотыкается Пайрайт!

Он хочет иметь параметр типа в рекурсивном определении:
X_or_RecurListOf = Union[T, list['X_or_RecurListOf[T]']] — обратите внимание на [T]!

Я не понимаю, зачем это нужно, но у меня это работает, тем более, что я действительно имел в виду X_or_RecurListOf[T], а не X_or_RecurListOf[Any].

person Min-Soo Pipefeet    schedule 04.03.2021