Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

bpo-46534: Implement PEP 673 Self in typing.py #30924

Merged
merged 15 commits into from
Feb 7, 2022
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions Doc/library/typing.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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:

Expand Down Expand Up @@ -585,6 +587,31 @@ 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

.. note::

This code would be semantically equivalent to a bound :class:`TypeVar` with the `bound=Foo`.

This is especially useful for:

- :class:`classmethod`\s that are used as alternative constructors
Gobot1234 marked this conversation as resolved.
Show resolved Hide resolved
- Annotating an :meth:`object.__enter__` method which returns self

For more info see :pep:`673`.
Gobot1234 marked this conversation as resolved.
Show resolved Hide resolved

.. versionadded:: 3.11

.. data:: TypeAlias

Special annotation for explicitly declaring a :ref:`type alias <type-aliases>`.
Expand Down
43 changes: 42 additions & 1 deletion Lib/test/test_typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
from typing import IO, TextIO, BinaryIO
from typing import Pattern, Match
from typing import Annotated, ForwardRef
from typing import Self
from typing import TypeAlias
from typing import ParamSpec, Concatenate, ParamSpecArgs, ParamSpecKwargs
from typing import TypeGuard
Expand Down Expand Up @@ -155,8 +156,48 @@ def test_cannot_instantiate(self):
type(NoReturn)()


class TypeVarTests(BaseTestCase):
class SelfTests(BaseTestCase):
def test_basics(self):
class Foo:
def bar(self) -> Self: ...

self.assertEqual(gth(Foo.bar), {'return': Self})

def test_repr(self):
self.assertEqual(repr(Self), 'typing.Self')

def test_cannot_subscript(self):
with self.assertRaises(TypeError):
Self[int]

def test_cannot_subclass(self):
with self.assertRaises(TypeError):
class C(type(Self)):
pass

def test_cannot_init(self):
with self.assertRaises(TypeError):
Self()
with self.assertRaises(TypeError):
type(Self)()

def test_no_isinstance(self):
with self.assertRaises(TypeError):
isinstance(1, Self)
with self.assertRaises(TypeError):
issubclass(int, Self)

def test_alias(self):
Gobot1234 marked this conversation as resolved.
Show resolved Hide resolved
# TypeAliases are not actually part of the spec
alias_1 = Tuple[Self, Self]
alias_2 = List[Self]
alias_3 = ClassVar[Self]
self.assertEqual(get_args(alias_1), (Self, Self))
self.assertEqual(get_args(alias_2), (Self,))
self.assertEqual(get_args(alias_3), (Self,))


class TypeVarTests(BaseTestCase):
def test_basic_plain(self):
T = TypeVar('T')
# T equals itself.
Expand Down
24 changes: 23 additions & 1 deletion Lib/typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,7 @@ def _idfunc(_, x):
'ParamSpecArgs',
'ParamSpecKwargs',
'runtime_checkable',
'Self',
'Text',
'TYPE_CHECKING',
'TypeAlias',
Expand Down Expand Up @@ -173,7 +174,7 @@ def _type_check(arg, msg, is_argument=True, module=None, *, is_class=False):
if (isinstance(arg, _GenericAlias) and
arg.__origin__ in invalid_generic_forms):
raise TypeError(f"{arg} is not valid as type argument")
if arg in (Any, NoReturn, Final):
if arg in (Any, NoReturn, Self, Final):
return arg
if isinstance(arg, _SpecialForm) or arg in (Generic, Protocol):
raise TypeError(f"Plain {arg} is not valid as type argument")
Expand Down Expand Up @@ -446,6 +447,27 @@ def stop() -> NoReturn:
"""
raise TypeError(f"{self} is not subscriptable")


@_SpecialForm
def Self(self, parameters):
"""Used to spell the type of "self" in classes.

Example::

from typing import Self

class Foo:
def returns_self(self) -> Self:
...
return self

This is especially useful for:
- classmethods that are used as alternative constructors
- annotating an `__enter__` method which returns self
"""
raise TypeError(f"{self} is not subscriptable")


@_SpecialForm
def ClassVar(self, parameters):
"""Special type construct to mark class variables.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Implement PEP 673 :class:`typing.Self`.
Gobot1234 marked this conversation as resolved.
Show resolved Hide resolved
Gobot1234 marked this conversation as resolved.
Show resolved Hide resolved