8000 feat: add typing.Self · RustPython/RustPython@b41c207 · GitHub
[go: up one dir, main page]

Skip to content

Commit b41c207

Browse files
committed
feat: add typing.Self
Signed-off-by: Nick Mitchell <nickm@us.ibm.com>
1 parent b72f3a4 commit b41c207

File tree

1 file changed

+21
-1
lines changed

1 file changed

+21
-1
lines changed

Lib/typing.py

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,7 @@
122122
'ParamSpecArgs',
123123
'ParamSpecKwargs',
124124
'runtime_checkable',
125+
'Self',
125126
'Text',
126127
'TYPE_CHECKING',
127128
'TypeAlias',
@@ -164,7 +165,7 @@ def _type_check(arg, msg, is_argument=True, module=None, *, allow_special_forms=
164165
if (isinstance(arg, _GenericAlias) and
165166
arg.__origin__ in invalid_generic_forms):
166167
raise TypeError(f"{arg} is not valid as type argument")
167-
if arg in (Any, NoReturn, Final, TypeAlias):
168+
if arg in (Any, NoReturn, Final, Self, TypeAlias):
168169
return arg
169170
if isinstance(arg, _SpecialForm) or arg in (Generic, Protocol):
170171
raise TypeError(f"Plain {arg} is not valid as type argument")
@@ -438,6 +439,25 @@ def stop() -> NoReturn:
438439
"""
439440
raise TypeError(f"{self} is not subscriptable")
440441

442+
@_SpecialForm
443+
def Self(self, parameters):
444+
"""Used to spell the type of "self" in classes.
445+
446+
Example::
447+
448+
from typing import Self
449+
450+
class Foo:
451+
def return_self(self) -> Self:
452+
...
453+
return self
454+
455+
This is especially useful for:
456+
- classmethods that are used as alternative constructors
457+
- annotating an `__enter__` method which returns self
458+
"""
459+
raise TypeError(f"{self} is not subscriptable")
460+
441461
@_SpecialForm
442462
def ClassVar(self, parameters):
443463
"""Special type construct to mark class variables.

0 commit comments

Comments
 (0)
0