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>
This commit is contained in:
James Hilton-Balfe 2022-02-07 20:47:48 +00:00 committed by GitHub
parent 39dec1c09c
commit 7ba1cc8049
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
5 changed files with 116 additions and 2 deletions

View file

@ -132,6 +132,7 @@ __all__ = [
'ParamSpecKwargs',
'reveal_type',
'runtime_checkable',
'Self',
'Text',
'TYPE_CHECKING',
'TypeAlias',
@ -174,7 +175,7 @@ def _type_check(arg, msg, is_argument=True, module=None, *, allow_special_forms=
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, ClassVar, Final, TypeAlias):
if arg in (Any, NoReturn, Self, ClassVar, Final, TypeAlias):
return arg
if isinstance(arg, _SpecialForm) or arg in (Generic, Protocol):
raise TypeError(f"Plain {arg} is not valid as type argument")
@ -445,6 +446,27 @@ def NoReturn(self, parameters):
"""
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.