@@ -963,13 +963,17 @@ using ``[]``.
963
963
964
964
For example::
965
965
966
- from typing import Self
966
+ from typing import Self, reveal_type
967
967
968
968
class Foo:
969
969
def return_self(self) -> Self:
970
970
...
971
971
return self
972
972
973
+ class SubclassOfFoo(Foo): pass
974
+
975
+ reveal_type(Foo().return_self()) # Revealed type is "Foo"
976
+ reveal_type(SubclassOfFoo().return_self()) # Revealed type is "SubclassOfFoo"
973
977
974
978
This annotation is semantically equivalent to the following,
975
979
albeit in a more succinct fashion::
@@ -983,22 +987,29 @@ using ``[]``.
983
987
...
984
988
return self
985
989
986
- In general if something currently follows the pattern of::
987
-
988
- class Foo:
989
- def return_self(self) -> "Foo":
990
- ...
991
- return self
992
-
993
- You should use :data: `Self ` as calls to ``SubclassOfFoo.return_self `` would have
994
- ``Foo `` as the return type and not ``SubclassOfFoo ``.
990
+ In general, if something returns ``self ``, as in the above examples, you
991
+ should use ``Self `` as the return annotation. If ``Foo.return_self `` was
992
+ annotated as returning ``"Foo" ``, then the type checker would infer the
993
+ object returned from ``SubclassOfFoo.return_self `` as being of type ``Foo ``
994
+ rather than ``SubclassOfFoo ``.
995
995
996
996
Other common use cases include:
997
997
998
998
- :class: `classmethod `\s that are used as alternative constructors and return instances
999
999
of the ``cls `` parameter.
1000
1000
- Annotating an :meth: `~object.__enter__ ` method which returns self.
1001
1001
1002
+ You should not use ``Self `` as the return annotation if the method is not
1003
+ guaranteed to return an instance of a subclass when the class is
1004
+ subclassed::
1005
+
1006
+ class Eggs:
1007
+ # Self would be an incorrect return annotation here,
1008
+ # as the object returned is always an instance of Eggs,
1009
+ # even in subclasses
1010
+ def returns_eggs(self) -> "Eggs":
1011
+ return Eggs()
1012
+
1002
1013
See :pep: `673 ` for more details.
1003
1014
1004
1015
.. versionadded :: 3.11
0 commit comments