[Python] How is an instance attribute of the same type as the instance type-hinted?

Discussão em 'Python' iniciado por Stack, Abril 29, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to assign a variable to an instance of a class such that the variable is of the same type. I want to use the instance itself in the construction of the variable. In order to be compatible with inheritance, I want to type hint it as Self rather than the class.

    The following works:

    class Foo:

    var: "Foo"

    def bar(self) -> None:
    self.var = self


    However, var is marked as being of type Foo rather than Self. What I want is:

    from typing import Self

    class Foo:

    var: Self

    def bar(self) -> None:
    self.var = self


    In this case, mypy gives me the following message:

    error: Incompatible types in assignment (expression has type "Foo", variable has type "Self") [assignment]


    Clearly, self is not regarded as being of type Self but only of type Foo.

    Continue reading...

Compartilhe esta Página