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

Add PEP 673 Self type #933

Merged
merged 14 commits into from Nov 12, 2021
67 changes: 67 additions & 0 deletions typing_extensions/src_py3/typing_extensions.py
Expand Up @@ -2844,3 +2844,70 @@ def is_str(val: Union[str, float]):
PEP 647 (User-Defined Type Guards).
"""
__type__ = None


if hasattr(typing, "Self"):
Self = typing.Self

elif sys.version_info[:2] >= (3, 9):
@typing._SpecialForm
def Self(self, params):
"""Used to spell the type of "self" in classes.

Example::

from typing import Self

class ReturnsSelf:
def parse(self, data: bytes) -> Self:
...
return self

"""

raise TypeError(f"{self} is not subscriptable")

elif sys.version_info[:2] >= (3, 7):
class _SelfForm(typing._SpecialForm, _root=True):
def __repr__(self):
return 'typing_extensions.' + self._name

Self = _SelfForm(
"Self",
doc="""Used to spell the type of "self" in classes.

Example::

from typing import Self

class ReturnsSelf:
def parse(self, data: bytes) -> Self:
...
return self

"""
)
else:
class _Self(typing._FinalTypingBase, _root=True):
"""Used to spell the type of "self" in classes.

Example::

from typing import Self

class ReturnsSelf:
def parse(self, data: bytes) -> Self:
...
return self

"""

__slots__ = ()

def __instancecheck__(self, obj):
raise TypeError(f"{self} cannot be used with isinstance().")

def __subclasscheck__(self, cls):
raise TypeError(f"{self} cannot be used with issubclass().")

Self = _Self(_root=True)