7

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


  • Is there a reason that self is not annotated or is this only convention?
  • Are there trade offs I'm missing or is my annotation of self wrong for some reason?
cjds
  • 8,268
  • 10
  • 49
  • 84
  • 4
    It's not needed -- the type of `self` is guaranteed to be the class. – Barmar Sep 15 '20 at 17:13
  • 3
    How am I not myself? – JacobIRR Sep 15 '20 at 17:14
  • 1
    Yeah I totally agree. Maybe the job is to make `mypy` able to check the `self` parameters without needing the type hint? I think I ran across a problem where I wanted to see what would happen and then noticed. "hey mypy is picking up bugs I didn't know about" why don't I do this everywhere/ – cjds Sep 15 '20 at 17:14
  • 3
    @Barmar "guaranteed" -> "expected" – khelwood Sep 15 '20 at 17:16
  • 1
    @khelwood Yeah, I regretted the choice of words immediately. But it's as "guaranteed" as any other type annotation. – Barmar Sep 15 '20 at 17:17

1 Answers1

9

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.

user2357112
  • 260,549
  • 28
  • 431
  • 505
  • [Relevant mypy settings](https://mypy.readthedocs.io/en/stable/config_file.html?highlight=check_untyped_defs#untyped-definitions-and-calls) – l0b0 Sep 18 '20 at 04:21
  • 1
    While both is possible, I think annotating the return type (using `-> None` if nothing is returned) instead of `self` is the more canonic solution in this case. – luator Sep 27 '22 at 09:21