Pyright: Expression cannot be assigned to return value (TypeVar is invariant)

Created on 1 Dec 2020  路  5Comments  路  Source: microsoft/pyright

Describe the bug

Sorry but I don't understand this error so I'll just show it to you. It might be due to user error (wrong annotations) or it might be a bug in Pyright. I thought you'd be the best person to tell.

To Reproduce

See the code snippet below.

Expected behavior

No errors reported.
mypy doesn't report any, if that is of any indication.

Pyright is showing those errors:

Argument of type "list[int]" cannot be assigned to parameter "value" of type "T" in function "resolve"
  Type "list[int]" cannot be assigned to type "T"

Expression of type "Foo[T]" cannot be assigned to return type "Foo[List[int]]"
  TypeVar "T" is invariant
    "object" is incompatible with "List[int]"

Screenshots or Code

from typing import Generic, List, TypeVar

T = TypeVar('T')


class Foo(Generic[T]):

    @classmethod
    def resolve(cls, value: T) -> 'Foo[T]':
        return cls()


def create_foo() -> Foo[List[int]]:
    return Foo.resolve([1])

VS Code extension or command-line

Running pyright as a language server but in ST.

Additional context
Add any other context about the problem here.

addressed in next version bug

Most helpful comment

This will be fixed in the next release.

All 5 comments

Yes, I agree this is a bug in pyright. It falls into a bit of gray area because you're using an unspecialized class to access a class method and expecting the type checker to solve for the class-level TypeVars when invoking that method. Pyright currently does this as a special case only for constructors (__init__ and __new__ methods) but not for class methods in general. The specs (PEP 484, etc.) don't indicate the proper behavior in this case, but since the intent is unambiguous and mypy appears to accept this, I think it's reasonable for pyright to do so as well.

FYI: This is btw how you would write this in F#. The compiler has no problems with this:

Screenshot 2020-12-04 at 08 57 00

Type hover info for Resolve method:

Screenshot 2020-12-04 at 08 57 16

This will be fixed in the next release.

Great news! Thanks for fixing!

This is addressed in Pyright 1.1.93, which I just published. It will also be included in the next release of Pylance.

Was this page helpful?
0 / 5 - 0 ratings