From 14974072c0a70f8ca29c17c740475187b800e714 Mon Sep 17 00:00:00 2001 From: Shantanu <12621235+hauntsaninja@users.noreply.github.com> Date: Tue, 10 Dec 2024 06:06:34 -0800 Subject: [PATCH] Add Self misuse to common issues (#18261) This has come up at least a half dozen times on the tracker --- docs/source/common_issues.rst | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/docs/source/common_issues.rst b/docs/source/common_issues.rst index 39954b8e332a..61b71c108ea0 100644 --- a/docs/source/common_issues.rst +++ b/docs/source/common_issues.rst @@ -819,3 +819,30 @@ This is best understood via an example: To get this code to type check, you could assign ``y = x`` after ``x`` has been narrowed, and use ``y`` in the inner function, or add an assert in the inner function. + +.. _incorrect-self: + +Incorrect use of ``Self`` +------------------------- + +``Self`` is not the type of the current class; it's a type variable with upper +bound of the current class. That is, it represents the type of the current class +or of potential subclasses. + +.. code-block:: python + + from typing import Self + + class Foo: + @classmethod + def constructor(cls) -> Self: + # Instead, either call cls() or change the annotation to -> Foo + return Foo() # error: Incompatible return value type (got "Foo", expected "Self") + + class Bar(Foo): + ... + + reveal_type(Foo.constructor()) # note: Revealed type is "Foo" + # In the context of the subclass Bar, the Self return type promises + # that the return value will be Bar + reveal_type(Bar.constructor()) # note: Revealed type is "Bar"