Skip to content

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

Derived from the flake8-pyi linter.

Fix is sometimes available.

What it does

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

Why is this bad?

While the semantics are often identical, using 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: ...

Fix safety

The fix is only available in stub files. It will try to remove all usages and declarations of the custom type variable. Pre-[PEP-695]-style declarations will not be removed.

If a variable's annotation is too complex to handle, the fix will be marked as display only. Otherwise, it will be marked as safe.