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