summaryrefslogtreecommitdiffstats
path: root/Doc
diff options
context:
space:
mode:
authorJames Hilton-Balfe <gobot1234yt@gmail.com>2022-02-07 20:47:48 (GMT)
committerGitHub <noreply@github.com>2022-02-07 20:47:48 (GMT)
commit7ba1cc8049fbcb94ac039ab02522f78177130588 (patch)
tree3b1a480d5512a3ad5e7f47c78db1458ba0ba1bee /Doc
parent39dec1c09c9f5ddf951bed5b875f837735a06733 (diff)
downloadcpython-7ba1cc8049fbcb94ac039ab02522f78177130588.zip
cpython-7ba1cc8049fbcb94ac039ab02522f78177130588.tar.gz
cpython-7ba1cc8049fbcb94ac039ab02522f78177130588.tar.bz2
bpo-46534: Implement PEP 673 Self in typing.py (GH-30924)
Co-authored-by: Pradeep Kumar Srinivasan <gohanpra@gmail.com> Co-authored-by: Jelle Zijlstra <jelle.zijlstra@gmail.com>
Diffstat (limited to 'Doc')
-rw-r--r--Doc/library/typing.rst47
-rw-r--r--Doc/whatsnew/3.11.rst2
2 files changed, 49 insertions, 0 deletions
diff --git a/Doc/library/typing.rst b/Doc/library/typing.rst
index 9007c0d..8c1c34e 100644
--- a/Doc/library/typing.rst
+++ b/Doc/library/typing.rst
@@ -68,6 +68,8 @@ annotations. These include:
*Introducing* :data:`TypeAlias`
* :pep:`647`: User-Defined Type Guards
*Introducing* :data:`TypeGuard`
+* :pep:`673`: Self type
+ *Introducing* :data:`Self`
.. _type-aliases:
@@ -585,6 +587,51 @@ These can be used as types in annotations and do not support ``[]``.
.. versionadded:: 3.5.4
.. versionadded:: 3.6.2
+.. data:: Self
+
+ Special type to represent the current enclosed class.
+ For example::
+
+ from typing import Self
+
+ class Foo:
+ def returns_self(self) -> Self:
+ ...
+ return self
+
+
+ This annotation is semantically equivalent to the following,
+ albeit in a more succinct fashion::
+
+ from typing import TypeVar
+
+ Self = TypeVar("Self", bound="Foo")
+
+ class Foo:
+ def returns_self(self: Self) -> Self:
+ ...
+ return self
+
+ In general if something currently follows the pattern of::
+
+ class Foo:
+ def return_self(self) -> "Foo":
+ ...
+ return self
+
+ You should use use :data:`Self` as calls to ``SubclassOfFoo.returns_self`` would have
+ ``Foo`` as the return type and not ``SubclassOfFoo``.
+
+ Other common use cases include:
+
+ - :class:`classmethod`\s that are used as alternative constructors and return instances
+ of the ``cls`` parameter.
+ - Annotating an :meth:`object.__enter__` method which returns self.
+
+ For more information, see :pep:`673`.
+
+ .. versionadded:: 3.11
+
.. data:: TypeAlias
Special annotation for explicitly declaring a :ref:`type alias <type-aliases>`.
diff --git a/Doc/whatsnew/3.11.rst b/Doc/whatsnew/3.11.rst
index c3c2c67..c1f267a 100644
--- a/Doc/whatsnew/3.11.rst
+++ b/Doc/whatsnew/3.11.rst
@@ -67,6 +67,8 @@ Summary -- Release highlights
PEP-654: Exception Groups and ``except*``.
(Contributed by Irit Katriel in :issue:`45292`.)
+PEP-673: ``Self`` Type.
+(Contributed by James Hilton-Balfe and Pradeep Kumar in :issue:`30924`.)
New Features
============