pythonpython-typingmypy

Why is self not type hinted in Python


I've been looking into type hinting my code but noticed that Python programmers typically do not type hint self in their programs

Even when I look at the docs, they do not seem to type hint self, see here. This is from version 3.10 post forward declarations

    def __init__(self, value: T, name: str, logger: Logger) -> None:

I can understand why this is an issue before type annotations were introduced in 3.7 with Forward declarations

More info here and here


The reason this seems useful to me is mypy seems able to catch bugs with this problem

example:

from __future__ import annotations

class Simple(object):
    def __init__(self: Simple):
        print(self.x)
          

would return this from mypy

mypy test.py 
test.py:5: error: "Simple" has no attribute "x"
Found 1 error in 1 file (checked 1 source file)

Which if you remove the type from self becomes

Success: no issues found in 1 source file


Solution

  • mypy usually handles the type of self without needing an explicit annotation. You're running into a different problem - a method with no argument or return type annotations is not type-checked at all. For a method with no non-self arguments, you can avoid this by annotating self, but you can also avoid it by annotating the return type.