Skip to content

Commit f7e16d7

Browse files
[3.12] Clarify Self interaction with subclasses (GH-107511) (#107548)
Clarify `Self` interaction with subclasses (GH-107511) (cherry picked from commit c8872f4) Co-authored-by: Alexandru Mărășteanu <[email protected]>
1 parent b68faa3 commit f7e16d7

File tree

1 file changed

+21
-10
lines changed

1 file changed

+21
-10
lines changed

Doc/library/typing.rst

Lines changed: 21 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -953,13 +953,17 @@ using ``[]``.
953953

954954
For example::
955955

956-
from typing import Self
956+
from typing import Self, reveal_type
957957

958958
class Foo:
959959
def return_self(self) -> Self:
960960
...
961961
return self
962962

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"
963967

964968
This annotation is semantically equivalent to the following,
965969
albeit in a more succinct fashion::
@@ -973,22 +977,29 @@ using ``[]``.
973977
...
974978
return self
975979

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``.
985985

986986
Other common use cases include:
987987

988988
- :class:`classmethod`\s that are used as alternative constructors and return instances
989989
of the ``cls`` parameter.
990990
- Annotating an :meth:`~object.__enter__` method which returns self.
991991

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+
9921003
See :pep:`673` for more details.
9931004

9941005
.. versionadded:: 3.11

0 commit comments

Comments
 (0)