|
86 | 86 | 'Text', |
87 | 87 | 'TypeAlias', |
88 | 88 | 'TypeAliasType', |
| 89 | + 'TypeExpr', |
89 | 90 | 'TypeGuard', |
90 | 91 | 'TypeIs', |
91 | 92 | 'TYPE_CHECKING', |
@@ -2045,6 +2046,55 @@ def f(val: Union[int, Awaitable[int]]) -> int: |
2045 | 2046 | PEP 742 (Narrowing types with TypeIs). |
2046 | 2047 | """) |
2047 | 2048 |
|
| 2049 | +# 3.14+? |
| 2050 | +if hasattr(typing, 'TypeExpr'): |
| 2051 | + TypeExpr = typing.TypeExpr |
| 2052 | +# 3.9 |
| 2053 | +elif sys.version_info[:2] >= (3, 9): |
| 2054 | + class _TypeExprForm(_ExtensionsSpecialForm, _root=True): |
| 2055 | + # TypeExpr(X) is equivalent to X but indicates to the type checker |
| 2056 | + # that the object is a TypeExpr. |
| 2057 | + def __call__(self, obj, /): |
| 2058 | + return obj |
| 2059 | + |
| 2060 | + @_TypeExprForm |
| 2061 | + def TypeExpr(self, parameters): |
| 2062 | + """Special typing form used to represent a type expression. |
| 2063 | +
|
| 2064 | + Usage: |
| 2065 | +
|
| 2066 | + def cast[T](typ: TypeExpr[T], value: Any) -> T: ... |
| 2067 | +
|
| 2068 | + reveal_type(cast(int, "x")) # int |
| 2069 | +
|
| 2070 | + See PEP 747 for more information. |
| 2071 | + """ |
| 2072 | + item = typing._type_check(parameters, f'{self} accepts only a single type.') |
| 2073 | + return typing._GenericAlias(self, (item,)) |
| 2074 | +# 3.8 |
| 2075 | +else: |
| 2076 | + class _TypeExprForm(_ExtensionsSpecialForm, _root=True): |
| 2077 | + def __getitem__(self, parameters): |
| 2078 | + item = typing._type_check(parameters, |
| 2079 | + f'{self._name} accepts only a single type') |
| 2080 | + return typing._GenericAlias(self, (item,)) |
| 2081 | + |
| 2082 | + def __call__(self, obj, /): |
| 2083 | + return obj |
| 2084 | + |
| 2085 | + TypeExpr = _TypeExprForm( |
| 2086 | + 'TypeExpr', |
| 2087 | + doc="""Special typing form used to represent a type expression. |
| 2088 | +
|
| 2089 | + Usage: |
| 2090 | +
|
| 2091 | + def cast[T](typ: TypeExpr[T], value: Any) -> T: ... |
| 2092 | +
|
| 2093 | + reveal_type(cast(int, "x")) # int |
| 2094 | +
|
| 2095 | + See PEP 747 for more information. |
| 2096 | + """) |
| 2097 | + |
2048 | 2098 |
|
2049 | 2099 | # Vendored from cpython typing._SpecialFrom |
2050 | 2100 | class _SpecialForm(typing._Final, _root=True): |
|
0 commit comments