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?#

While the semantics are often identical, using typing_extensions.Self is more intuitive and succinct (per PEP 673) than a custom TypeVar. For example, the use of Self will typically allow for the omission of type parameters on the self and cls arguments.

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, *args: str, **kwargs: int) -> Self:
        ...

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

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