File tree Expand file tree Collapse file tree 1 file changed +27
-0
lines changed Expand file tree Collapse file tree 1 file changed +27
-0
lines changed Original file line number Diff line number Diff line change @@ -819,3 +819,30 @@ This is best understood via an example:
819
819
To get this code to type check, you could assign ``y = x `` after ``x `` has been
820
820
narrowed, and use ``y `` in the inner function, or add an assert in the inner
821
821
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"
You can’t perform that action at this time.
0 commit comments