8
8
import typing
9
9
10
10
11
- # Please keep __all__ alphabetized within each category.
12
11
__all__ = [
13
12
# Super-special typing primitives.
13
+ 'Any' ,
14
14
'ClassVar' ,
15
15
'Concatenate' ,
16
16
'Final' ,
20
20
'ParamSpecKwargs' ,
21
21
'Self' ,
22
22
'Type' ,
23
+ 'TypeVar' ,
23
24
'TypeVarTuple' ,
24
25
'Unpack' ,
25
26
60
61
'Literal' ,
61
62
'NewType' ,
62
63
'overload' ,
64
+ 'override' ,
63
65
'Protocol' ,
64
66
'reveal_type' ,
65
67
'runtime' ,
@@ -149,6 +151,37 @@ def _collect_type_vars(types, typevar_types=None):
149
151
T_co = typing .TypeVar ('T_co' , covariant = True ) # Any type covariant containers.
150
152
T_contra = typing .TypeVar ('T_contra' , contravariant = True ) # Ditto contravariant.
151
153
154
+
155
+ if sys .version_info >= (3 , 11 ):
156
+ from typing import Any
157
+ else :
158
+
159
+ class _AnyMeta (type ):
160
+ def __instancecheck__ (self , obj ):
161
+ if self is Any :
162
+ raise TypeError ("typing_extensions.Any cannot be used with isinstance()" )
163
+ return super ().__instancecheck__ (obj )
164
+
165
+ def __repr__ (self ):
166
+ if self is Any :
167
+ return "typing_extensions.Any"
168
+ return super ().__repr__ ()
169
+
170
+ class Any (metaclass = _AnyMeta ):
171
+ """Special type indicating an unconstrained type.
172
+ - Any is compatible with every type.
173
+ - Any assumed to have all methods.
174
+ - All values assumed to be instances of Any.
175
+ Note that all the above statements are true from the point of view of
176
+ static type checkers. At runtime, Any should not be used with instance
177
+ checks.
178
+ """
179
+ def __new__ (cls , * args , ** kwargs ):
180
+ if cls is Any :
181
+ raise TypeError ("Any cannot be instantiated" )
182
+ return super ().__new__ (cls , * args , ** kwargs )
183
+
184
+
152
185
ClassVar = typing .ClassVar
153
186
154
187
# On older versions of typing there is an internal class named "Final".
@@ -431,7 +464,7 @@ def _no_init(self, *args, **kwargs):
431
464
if type (self )._is_protocol :
432
465
raise TypeError ('Protocols cannot be instantiated' )
433
466
434
- class _ProtocolMeta (abc .ABCMeta ):
467
+ class _ProtocolMeta (abc .ABCMeta ): # noqa: B024
435
468
# This metaclass is a bit unfortunate and exists only because of the lack
436
469
# of __instancehook__.
437
470
def __instancecheck__ (cls , instance ):
@@ -1115,6 +1148,44 @@ def __repr__(self):
1115
1148
above.""" )
1116
1149
1117
1150
1151
+ class _DefaultMixin :
1152
+ """Mixin for TypeVarLike defaults."""
1153
+
1154
+ __slots__ = ()
1155
+
1156
+ def __init__ (self , default ):
1157
+ if isinstance (default , (tuple , list )):
1158
+ self .__default__ = tuple ((typing ._type_check (d , "Default must be a type" )
1159
+ for d in default ))
1160
+ elif default :
1161
+ self .__default__ = typing ._type_check (default , "Default must be a type" )
1162
+ else :
1163
+ self .__default__ = None
1164
+
1165
+
1166
+ # Add default and infer_variance parameters from PEP 696 and 695
1167
+ class TypeVar (typing .TypeVar , _DefaultMixin , _root = True ):
1168
+ """Type variable."""
1169
+
1170
+ __module__ = 'typing'
1171
+
1172
+ def __init__ (self , name , * constraints , bound = None ,
1173
+ covariant = False , contravariant = False ,
1174
+ default = None , infer_variance = False ):
1175
+ super ().__init__ (name , * constraints , bound = bound , covariant = covariant ,
1176
+ contravariant = contravariant )
1177
+ _DefaultMixin .__init__ (self , default )
1178
+ self .__infer_variance__ = infer_variance
1179
+
1180
+ # for pickling:
1181
+ try :
1182
+ def_mod = sys ._getframe (1 ).f_globals .get ('__name__' , '__main__' )
1183
+ except (AttributeError , ValueError ):
1184
+ def_mod = None
1185
+ if def_mod != 'typing_extensions' :
1186
+ self .__module__ = def_mod
1187
+
1188
+
1118
1189
# Python 3.10+ has PEP 612
1119
1190
if hasattr (typing , 'ParamSpecArgs' ):
1120
1191
ParamSpecArgs = typing .ParamSpecArgs
@@ -1179,12 +1250,32 @@ def __eq__(self, other):
1179
1250
1180
1251
# 3.10+
1181
1252
if hasattr (typing , 'ParamSpec' ):
1182
- ParamSpec = typing .ParamSpec
1253
+
1254
+ # Add default Parameter - PEP 696
1255
+ class ParamSpec (typing .ParamSpec , _DefaultMixin , _root = True ):
1256
+ """Parameter specification variable."""
1257
+
1258
+ __module__ = 'typing'
1259
+
1260
+ def __init__ (self , name , * , bound = None , covariant = False , contravariant = False ,
1261
+ default = None ):
1262
+ super ().__init__ (name , bound = bound , covariant = covariant ,
1263
+ contravariant = contravariant )
1264
+ _DefaultMixin .__init__ (self , default )
1265
+
1266
+ # for pickling:
1267
+ try :
1268
+ def_mod = sys ._getframe (1 ).f_globals .get ('__name__' , '__main__' )
1269
+ except (AttributeError , ValueError ):
1270
+ def_mod = None
1271
+ if def_mod != 'typing_extensions' :
1272
+ self .__module__ = def_mod
1273
+
1183
1274
# 3.7-3.9
1184
1275
else :
1185
1276
1186
1277
# Inherits from list as a workaround for Callable checks in Python < 3.9.2.
1187
- class ParamSpec (list ):
1278
+ class ParamSpec (list , _DefaultMixin ):
1188
1279
"""Parameter specification variable.
1189
1280
1190
1281
Usage::
@@ -1242,7 +1333,8 @@ def args(self):
1242
1333
def kwargs (self ):
1243
1334
return ParamSpecKwargs (self )
1244
1335
1245
- def __init__ (self , name , * , bound = None , covariant = False , contravariant = False ):
1336
+ def __init__ (self , name , * , bound = None , covariant = False , contravariant = False ,
1337
+ default = None ):
1246
1338
super ().__init__ ([self ])
1247
1339
self .__name__ = name
1248
1340
self .__covariant__ = bool (covariant )
@@ -1251,6 +1343,7 @@ def __init__(self, name, *, bound=None, covariant=False, contravariant=False):
1251
1343
self .__bound__ = typing ._type_check (bound , 'Bound must be a type.' )
1252
1344
else :
1253
1345
self .__bound__ = None
1346
+ _DefaultMixin .__init__ (self , default )
1254
1347
1255
1348
# for pickling:
1256
1349
try :
@@ -1752,9 +1845,25 @@ def _is_unpack(obj):
1752
1845
1753
1846
1754
1847
if hasattr (typing , "TypeVarTuple" ): # 3.11+
1755
- TypeVarTuple = typing .TypeVarTuple
1848
+
1849
+ # Add default Parameter - PEP 696
1850
+ class TypeVarTuple (typing .TypeVarTuple , _DefaultMixin , _root = True ):
1851
+ """Type variable tuple."""
1852
+
1853
+ def __init__ (self , name , * , default = None ):
1854
+ super ().__init__ (name )
1855
+ _DefaultMixin .__init__ (self , default )
1856
+
1857
+ # for pickling:
1858
+ try :
1859
+ def_mod = sys ._getframe (1 ).f_globals .get ('__name__' , '__main__' )
1860
+ except (AttributeError , ValueError ):
1861
+ def_mod = None
1862
+ if def_mod != 'typing_extensions' :
1863
+ self .__module__ = def_mod
1864
+
1756
1865
else :
1757
- class TypeVarTuple :
1866
+ class TypeVarTuple ( _DefaultMixin ) :
1758
1867
"""Type variable tuple.
1759
1868
1760
1869
Usage::
@@ -1804,8 +1913,9 @@ def get_shape(self) -> Tuple[*Ts]:
1804
1913
def __iter__ (self ):
1805
1914
yield self .__unpacked__
1806
1915
1807
- def __init__ (self , name ):
1916
+ def __init__ (self , name , * , default = None ):
1808
1917
self .__name__ = name
1918
+ _DefaultMixin .__init__ (self , default )
1809
1919
1810
1920
# for pickling:
1811
1921
try :
@@ -1968,6 +2078,36 @@ def decorator(cls_or_fn):
1968
2078
return decorator
1969
2079
1970
2080
2081
+ if hasattr (typing , "override" ):
2082
+ override = typing .override
2083
+ else :
2084
+ _F = typing .TypeVar ("_F" , bound = typing .Callable [..., typing .Any ])
2085
+
2086
+ def override (__arg : _F ) -> _F :
2087
+ """Indicate that a method is intended to override a method in a base class.
2088
+
2089
+ Usage:
2090
+
2091
+ class Base:
2092
+ def method(self) -> None: ...
2093
+ pass
2094
+
2095
+ class Child(Base):
2096
+ @override
2097
+ def method(self) -> None:
2098
+ super().method()
2099
+
2100
+ When this decorator is applied to a method, the type checker will
2101
+ validate that it overrides a method with the same name on a base class.
2102
+ This helps prevent bugs that may occur when a base class is changed
2103
+ without an equivalent change to a child class.
2104
+
2105
+ See PEP 698 for details.
2106
+
2107
+ """
2108
+ return __arg
2109
+
2110
+
1971
2111
# We have to do some monkey patching to deal with the dual nature of
1972
2112
# Unpack/TypeVarTuple:
1973
2113
# - We want Unpack to be a kind of TypeVar so it gets accepted in
0 commit comments