8000 feat: add typing.Self by starpit · Pull Request #5710 · RustPython/RustPython · GitHub
[go: up one dir, main page]

Skip to content
Closed
Show file tree
Hide file tree
Changes from all 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
22 changes: 21 additions & 1 deletion Lib/typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,7 @@
'ParamSpecArgs',
'ParamSpecKwargs',
'runtime_checkable',
'Self',
'Text',
'TYPE_CHECKING',
'TypeAlias',
Expand Down Expand Up @@ -164,7 +165,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, Final, TypeAlias):
if arg in (Any, NoReturn, Final, Self, TypeAlias):
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 @@ -438,6 +439,25 @@ 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 return_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
8 changes: 8 additions & 0 deletions extra_tests/snippets/stdlib_typing.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
from typing import Self

class Shape:
def set_scale(self, scale: float) -> Self:
self.scale = scale
return self

print(Shape().set_scale(3).scale)
Loading
0