Skip to content

custom-type-var-return-type (PYI019)#

Derived from the flake8-pyi linter.

What it does#

Checks for methods that define a custom TypeVar for their return type annotation instead of using typing_extensions.Self.

Why is this bad?#

If certain methods are annotated with a custom TypeVar type, and the class is subclassed, type checkers will not be able to infer the correct return type.

This check currently applies to instance methods that return self, class methods that return an instance of cls, and __new__ methods.

Example#

class Foo:
    def __new__(cls: type[_S], *args: str, **kwargs: int) -> _S:
        ...

    def foo(self: _S, arg: bytes) -> _S:
        ...

    @classmethod
    def bar(cls: type[_S], arg: int) -> _S:
        ...

Use instead:

from typing import Self


class Foo:
    def __new__(cls: type[Self], *args: str, **kwargs: int) -> Self:
        ...

    def foo(self: Self, arg: bytes) -> Self:
        ...

    @classmethod
    def bar(cls: type[Self], arg: int) -> Self:
        ...