1

Checking the following code with Pyright:

from typing import Union, TypeVar

T = TypeVar('T')
X_or_RecurListOf = Union[T, list['X_or_RecurListOf']]
x: X_or_RecurListOf[str] = ['asd']

produces the error:

  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

Am I doing something wrong?
Or have I misunderstood the announcement for support of recursive types in Pyright?

Min-Soo Pipefeet
  • 2,208
  • 4
  • 12
  • 31

1 Answers1

0

Oh, I've found what Pyright stumbles over!

It wants to have the type parameter in the recursive definition:
X_or_RecurListOf = Union[T, list['X_or_RecurListOf[T]']] - pay attention to the [T]!

I don't see why this is necessary but it works for me, especially as I really meant X_or_RecurListOf[T] and not X_or_RecurListOf[Any].

Min-Soo Pipefeet
  • 2,208
  • 4
  • 12
  • 31