Skip to content

Commit 1497407

Browse files
authored
Add Self misuse to common issues (#18261)
This has come up at least a half dozen times on the tracker
1 parent 6427ef1 commit 1497407

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

docs/source/common_issues.rst

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -819,3 +819,30 @@ This is best understood via an example:
819819
To get this code to type check, you could assign ``y = x`` after ``x`` has been
820820
narrowed, and use ``y`` in the inner function, or add an assert in the inner
821821
function.
822+
823+
.. _incorrect-self:
824+
825+
Incorrect use of ``Self``
826+
-------------------------
827+
828+
``Self`` is not the type of the current class; it's a type variable with upper
829+
bound of the current class. That is, it represents the type of the current class
830+
or of potential subclasses.
831+
832+
.. code-block:: python
833+
834+
from typing import Self
835+
836+
class Foo:
837+
@classmethod
838+
def constructor(cls) -> Self:
839+
# Instead, either call cls() or change the annotation to -> Foo
840+
return Foo() # error: Incompatible return value type (got "Foo", expected "Self")
841+
842+
class Bar(Foo):
843+
...
844+
845+
reveal_type(Foo.constructor()) # note: Revealed type is "Foo"
846+
# In the context of the subclass Bar, the Self return type promises
847+
# that the return value will be Bar
848+
reveal_type(Bar.constructor()) # note: Revealed type is "Bar"

0 commit comments

Comments
 (0)