FazBrowse GitHub Viewer | Trending |
URL:
| Home
Tools: [Download Repo ZIP]   [Original HTTPS Page]

feat: add typing.Self by starpit · Pull Request #5710 · RustPython/RustPython · GitHub

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension .py  (2) All 1 file type selected
Viewed files
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Unified
Split
Hide whitespace
Diff view
Unified
Split
Hide whitespace
22 changes: 21 additions & 1 deletion Lib/typing.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
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)

Back | FazBrowse Home | New Git URL