[Python] Why is self not type hinted in Python

Discussão em 'Python' iniciado por Stack, Julho 3, 2025.

  1. Stack

    Stack Membro Participativo

    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?

    Continue reading...

Compartilhe esta Página