8000 Clarify `Self` interaction with subclasses (#107511) · python/cpython@c8872f4 · GitHub
[go: up one dir, main page]

Skip to content

Commit c8872f4

Browse files
authored
Clarify Self interaction with subclasses (#107511)
1 parent 030f6b1 commit c8872f4

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
@@ -963,13 +963,17 @@ using ``[]``.
963963

964964
For example::
965965

966-
from typing import Self
966+
from typing import Self, reveal_type
967967

968968
class Foo:
969969
def return_self(self) -> Self:
970970
...
971971
return self
972972

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

974978
This annotation is semantically equivalent to the following,
975979
albeit in a more succinct fashion::
@@ -983,22 +987,29 @@ using ``[]``.
983987
...
984988
return self
985989

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

996996
Other common use cases include:
997997

998998
- :class:`classmethod`\s that are used as alternative constructors and return instances
999999
of the ``cls`` parameter.
10001000
- Annotating an :meth:`~object.__enter__` method which returns self.
10011001

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

10041015
.. versionadded:: 3.11

0 commit comments

Comments
 (0)
0