Skip to content

Commit 05b58db

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

File tree

2 files changed

+29
-1
lines changed

2 files changed

+29
-1
lines changed

Lib/typing.py

+21-1
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.

extra_tests/snippets/stdlib_typing.py

+8
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
from typing import Self
2+
3+
class Shape:
4+
def set_scale(self, scale: float) -> Self:
5+
self.scale = scale
6+
return self
7+
8+
print(Shape().set_scale(3).scale)

0 commit comments

Comments
 (0)