Skip to content

Automatically use Self type even if it doesn't appear in method annotation #14075

Open
@ilevkivskyi

Description

@ilevkivskyi

This is a follow up for #14041

This example gives an error:

from typing import Self

class C:
    x: Self
    def meth(self) -> None:
        self.x = self  # E: Incompatible types in assignment (expression has type "C", variable has type "Self")

Although it is unfortunate, technically this is required by PEP 484, that says that if no annotation is given, self has a type of current class (note also we can't bind self type for self.x expression giving it type C, as this will open another unsafety). This can be avoided by using e.g. self: Self (or generally Self type anywhere in the signature).

It looks like there can be only two solutions:

  • Always infer Self type for self. This will cause a big performance penalty and may be surprising for users who are not familiar with Self (if they use reveal_type(self)).
  • Use some heuristic and only infer Self where otherwise we will have this problem. For example, infer Self if an attribute with type containing Self is used anywhere in a method.

I am leaning towards the latter, but didn't want to do this until we get some more experience.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions