@Eric: Explicit would still be better than implicit. As you mentioned, inference would not help with stubs that return Self, since there won't be a method body to analyze. It would be good to standardize this across typecheckers.

This pattern of typing `self` or `cls` makes up about a quarter of all TypeVar definitions (in typeshed and other projects). Most people aren't familiar with the `Type[T]` trick for doing this, which means they often leave such methods without any return type. It makes sense to have a simple way to express their intentions ("return Self").

@James: We'd discussed the Self idea during the Typing Summit [1]. Happy to collaborate on this if you'd like.

Another use case is a parameter that needs to be of type Self:

class Foo:
    def difference(self, other: Self) -> Self: ...

    def apply(self, f: Callable[[Self], None]) -> None: ...

[1]: Slides: https://drive.google.com/file/d/1x-qoDVY_OvLpIV1EwT7m3vm4HrgubHPG/view?usp=sharing

On Wed, Jun 2, 2021 at 9:30 AM Eric Traut <eric@traut.com> wrote:
I wouldn't say that the type checker is guessing your intent. It's still verifying full type consistency of the function and its callers. I presume that you rely on type inference in other places within your code. Or do you provide annotations for every variable?

You're correct that any time you rely on type inference (and this is true for variables as well), you may find there are differences between type checkers.

I didn't realize that mypy never inferred return types for functions. If that's the case, then it would be a bigger investment to add this capability to mypy.

My team maintains a Python code base with about a quarter million lines of code, and most of it uses the strictest type checking modes in pyright, which means that full type consistency is validated. We tend to annotate function return types only in cases where type inference is insufficient, probably about a quarter of the functions or methods in the code base.


Eric Traut
Contributor to Pyright & Pylance
Microsoft Corp
Typing-sig mailing list -- typing-sig@python.org
To unsubscribe send an email to typing-sig-leave@python.org
Member address: gohanpra@gmail.com

S Pradeep Kumar