|
122 | 122 | 'ParamSpecArgs',
|
123 | 123 | 'ParamSpecKwargs',
|
124 | 124 | 'runtime_checkable',
|
| 125 | + 'Self', |
125 | 126 | 'Text',
|
126 | 127 | 'TYPE_CHECKING',
|
127 | 128 | 'TypeAlias',
|
@@ -164,7 +165,7 @@ def _type_check(arg, msg, is_argument=True, module=None, *, allow_special_forms=
|
164 | 165 | if (isinstance(arg, _GenericAlias) and
|
165 | 166 | arg.__origin__ in invalid_generic_forms):
|
166 | 167 | 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): |
168 | 169 | return arg
|
169 | 170 | if isinstance(arg, _SpecialForm) or arg in (Generic, Protocol):
|
170 | 171 | raise TypeError(f"Plain {arg} is not valid as type argument")
|
@@ -438,6 +439,25 @@ def stop() -> NoReturn:
|
438 | 439 | """
|
439 | 440 | raise TypeError(f"{self} is not subscriptable")
|
440 | 441 |
|
| 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 | + |
441 | 461 | @_SpecialForm
|
442 | 462 | def ClassVar(self, parameters):
|
443 | 463 | """Special type construct to mark class variables.
|
|
0 commit comments