blob: f3cd280a09e27180a7cb453c102429e50e6286be [file] [log] [blame]
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001"""
2The typing module: Support for gradual typing as defined by PEP 484.
3
4At large scale, the structure of the module is following:
Tim McNamara5265b3a2018-09-01 20:56:58 +12005* Imports and exports, all public names should be explicitly added to __all__.
Ivan Levkivskyid911e402018-01-20 11:23:59 +00006* Internal helper functions: these should never be used in code outside this module.
7* _SpecialForm and its instances (special forms): Any, NoReturn, ClassVar, Union, Optional
8* Two classes whose instances can be type arguments in addition to types: ForwardRef and TypeVar
9* The core of internal generics API: _GenericAlias and _VariadicGenericAlias, the latter is
10 currently only used by Tuple and Callable. All subscripted types like X[int], Union[int, str],
11 etc., are instances of either of these classes.
Ivan Levkivskyi74d7f762019-05-28 08:40:15 +010012* The public counterpart of the generics API consists of two classes: Generic and Protocol.
Ivan Levkivskyid911e402018-01-20 11:23:59 +000013* Public helper functions: get_type_hints, overload, cast, no_type_check,
14 no_type_check_decorator.
15* Generic aliases for collections.abc ABCs and few additional protocols.
ananthan-123ab6423f2020-02-19 10:03:05 +053016* Special types: NewType, NamedTuple, TypedDict.
Ivan Levkivskyid911e402018-01-20 11:23:59 +000017* Wrapper submodules for re and io related types.
18"""
19
HongWeipeng6ce03ec2019-09-27 15:54:26 +080020from abc import abstractmethod, ABCMeta
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070021import collections
Ivan Levkivskyid911e402018-01-20 11:23:59 +000022import collections.abc
Brett Cannonf3ad0422016-04-15 10:51:30 -070023import contextlib
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070024import functools
Serhiy Storchaka09f32212018-05-26 21:19:26 +030025import operator
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070026import re as stdlib_re # Avoid confusion with the re we export.
27import sys
28import types
Guido van Rossum48b069a2020-04-07 09:50:06 -070029from types import WrapperDescriptorType, MethodWrapperType, MethodDescriptorType, GenericAlias
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070030
31# Please keep __all__ alphabetized within each category.
32__all__ = [
33 # Super-special typing primitives.
Jakub Stasiakcf5b1092020-02-05 02:10:19 +010034 'Annotated',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070035 'Any',
36 'Callable',
Guido van Rossum0a6976d2016-09-11 15:34:56 -070037 'ClassVar',
Ivan Levkivskyif3672422019-05-26 09:37:07 +010038 'Final',
Anthony Sottiled30da5d2019-05-29 11:19:38 -070039 'ForwardRef',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070040 'Generic',
Ivan Levkivskyib891c462019-05-26 09:37:48 +010041 'Literal',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070042 'Optional',
Ivan Levkivskyi74d7f762019-05-28 08:40:15 +010043 'Protocol',
Guido van Rossumeb9aca32016-05-24 16:38:22 -070044 'Tuple',
45 'Type',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070046 'TypeVar',
47 'Union',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070048
49 # ABCs (from collections.abc).
50 'AbstractSet', # collections.abc.Set.
51 'ByteString',
52 'Container',
Ivan Levkivskyi29fda8d2017-06-10 21:57:56 +020053 'ContextManager',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070054 'Hashable',
55 'ItemsView',
56 'Iterable',
57 'Iterator',
58 'KeysView',
59 'Mapping',
60 'MappingView',
61 'MutableMapping',
62 'MutableSequence',
63 'MutableSet',
64 'Sequence',
65 'Sized',
66 'ValuesView',
Ivan Levkivskyid911e402018-01-20 11:23:59 +000067 'Awaitable',
68 'AsyncIterator',
69 'AsyncIterable',
70 'Coroutine',
71 'Collection',
72 'AsyncGenerator',
73 'AsyncContextManager',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070074
75 # Structural checks, a.k.a. protocols.
76 'Reversible',
77 'SupportsAbs',
Ivan Levkivskyif06e0212017-05-02 19:14:07 +020078 'SupportsBytes',
79 'SupportsComplex',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070080 'SupportsFloat',
Paul Dagnelie4c7a46e2019-05-22 07:23:01 -070081 'SupportsIndex',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070082 'SupportsInt',
83 'SupportsRound',
84
85 # Concrete collection types.
Anthony Sottiled30da5d2019-05-29 11:19:38 -070086 'ChainMap',
Ivan Levkivskyib692dc82017-02-13 22:50:14 +010087 'Counter',
Raymond Hettinger80490522017-01-16 22:42:37 -080088 'Deque',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070089 'Dict',
Guido van Rossumbd5b9a02016-04-05 08:28:52 -070090 'DefaultDict',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070091 'List',
Anthony Sottiled30da5d2019-05-29 11:19:38 -070092 'OrderedDict',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070093 'Set',
Guido van Rossumefa798d2016-08-23 11:01:50 -070094 'FrozenSet',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070095 'NamedTuple', # Not really a type.
Ivan Levkivskyi135c6a52019-05-26 09:39:24 +010096 'TypedDict', # Not really a type.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070097 'Generator',
98
99 # One-off things.
100 'AnyStr',
101 'cast',
Ivan Levkivskyif3672422019-05-26 09:37:07 +0100102 'final',
Ivan Levkivskyi4c23aff2019-05-31 00:10:07 +0100103 'get_args',
104 'get_origin',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700105 'get_type_hints',
Guido van Rossum91185fe2016-06-08 11:19:11 -0700106 'NewType',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700107 'no_type_check',
108 'no_type_check_decorator',
aetracht45738202018-03-19 14:41:32 -0400109 'NoReturn',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700110 'overload',
Ivan Levkivskyi74d7f762019-05-28 08:40:15 +0100111 'runtime_checkable',
Guido van Rossum0e0563c2016-04-05 14:54:25 -0700112 'Text',
Guido van Rossum91185fe2016-06-08 11:19:11 -0700113 'TYPE_CHECKING',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700114]
115
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700116# The pseudo-submodules 're' and 'io' are part of the public
117# namespace, but excluded from __all__ because they might stomp on
118# legitimate imports of those modules.
119
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700120
Nina Zakharenko0e61dff2018-05-22 20:32:10 -0700121def _type_check(arg, msg, is_argument=True):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000122 """Check that the argument is a type, and return it (internal helper).
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700123
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000124 As a special case, accept None and return type(None) instead. Also wrap strings
125 into ForwardRef instances. Consider several corner cases, for example plain
126 special forms like Union are not valid, while Union[int, str] is OK, etc.
127 The msg argument is a human-readable error message, e.g::
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700128
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000129 "Union[arg, ...]: arg should be a type."
Guido van Rossum4cefe742016-09-27 15:20:12 -0700130
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000131 We append the repr() of the actual value (truncated to 100 chars).
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700132 """
Ivan Levkivskyi74d7f762019-05-28 08:40:15 +0100133 invalid_generic_forms = (Generic, Protocol)
Nina Zakharenko0e61dff2018-05-22 20:32:10 -0700134 if is_argument:
Ivan Levkivskyif3672422019-05-26 09:37:07 +0100135 invalid_generic_forms = invalid_generic_forms + (ClassVar, Final)
Nina Zakharenko2d2d3b12018-05-16 12:27:03 -0400136
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000137 if arg is None:
138 return type(None)
139 if isinstance(arg, str):
140 return ForwardRef(arg)
141 if (isinstance(arg, _GenericAlias) and
Nina Zakharenko2d2d3b12018-05-16 12:27:03 -0400142 arg.__origin__ in invalid_generic_forms):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000143 raise TypeError(f"{arg} is not valid as type argument")
Serhiy Storchaka40ded942020-04-23 21:26:48 +0300144 if arg in (Any, NoReturn):
145 return arg
146 if isinstance(arg, _SpecialForm) or arg in (Generic, Protocol):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000147 raise TypeError(f"Plain {arg} is not valid as type argument")
148 if isinstance(arg, (type, TypeVar, ForwardRef)):
149 return arg
150 if not callable(arg):
151 raise TypeError(f"{msg} Got {arg!r:.100}.")
152 return arg
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700153
154
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000155def _type_repr(obj):
156 """Return the repr() of an object, special-casing types (internal helper).
157
158 If obj is a type, we return a shorter version than the default
159 type.__repr__, based on the module and qualified name, which is
160 typically enough to uniquely identify a type. For everything
161 else, we fall back on repr(obj).
162 """
163 if isinstance(obj, type):
164 if obj.__module__ == 'builtins':
165 return obj.__qualname__
166 return f'{obj.__module__}.{obj.__qualname__}'
167 if obj is ...:
168 return('...')
169 if isinstance(obj, types.FunctionType):
170 return obj.__name__
171 return repr(obj)
172
173
174def _collect_type_vars(types):
175 """Collect all type variable contained in types in order of
176 first appearance (lexicographic order). For example::
177
178 _collect_type_vars((T, List[S, T])) == (T, S)
179 """
180 tvars = []
181 for t in types:
182 if isinstance(t, TypeVar) and t not in tvars:
183 tvars.append(t)
Guido van Rossum48b069a2020-04-07 09:50:06 -0700184 if ((isinstance(t, _GenericAlias) and not t._special)
185 or isinstance(t, GenericAlias)):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000186 tvars.extend([t for t in t.__parameters__ if t not in tvars])
187 return tuple(tvars)
188
189
190def _subs_tvars(tp, tvars, subs):
191 """Substitute type variables 'tvars' with substitutions 'subs'.
192 These two must have the same length.
193 """
Serhiy Storchaka68b352a2020-04-26 21:21:08 +0300194 if not isinstance(tp, (_GenericAlias, GenericAlias)):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000195 return tp
196 new_args = list(tp.__args__)
197 for a, arg in enumerate(tp.__args__):
198 if isinstance(arg, TypeVar):
199 for i, tvar in enumerate(tvars):
200 if arg == tvar:
201 new_args[a] = subs[i]
202 else:
203 new_args[a] = _subs_tvars(arg, tvars, subs)
204 if tp.__origin__ is Union:
205 return Union[tuple(new_args)]
Serhiy Storchaka68b352a2020-04-26 21:21:08 +0300206 if isinstance(tp, GenericAlias):
207 return GenericAlias(tp.__origin__, tuple(new_args))
208 else:
209 return tp.copy_with(tuple(new_args))
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000210
211
212def _check_generic(cls, parameters):
213 """Check correct count for parameters of a generic cls (internal helper).
214 This gives a nice error message in case of count mismatch.
215 """
216 if not cls.__parameters__:
217 raise TypeError(f"{cls} is not a generic class")
218 alen = len(parameters)
219 elen = len(cls.__parameters__)
220 if alen != elen:
221 raise TypeError(f"Too {'many' if alen > elen else 'few'} parameters for {cls};"
222 f" actual {alen}, expected {elen}")
223
224
225def _remove_dups_flatten(parameters):
Ivan Levkivskyif65e31f2018-05-18 16:00:38 -0700226 """An internal helper for Union creation and substitution: flatten Unions
227 among parameters, then remove duplicates.
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000228 """
229 # Flatten out Union[Union[...], ...].
230 params = []
231 for p in parameters:
232 if isinstance(p, _GenericAlias) and p.__origin__ is Union:
233 params.extend(p.__args__)
234 elif isinstance(p, tuple) and len(p) > 0 and p[0] is Union:
235 params.extend(p[1:])
236 else:
237 params.append(p)
238 # Weed out strict duplicates, preserving the first of each occurrence.
239 all_params = set(params)
240 if len(all_params) < len(params):
241 new_params = []
242 for t in params:
243 if t in all_params:
244 new_params.append(t)
245 all_params.remove(t)
246 params = new_params
247 assert not all_params, all_params
Ivan Levkivskyif65e31f2018-05-18 16:00:38 -0700248 return tuple(params)
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000249
250
251_cleanups = []
252
253
254def _tp_cache(func):
255 """Internal wrapper caching __getitem__ of generic types with a fallback to
256 original function for non-hashable arguments.
257 """
258 cached = functools.lru_cache()(func)
259 _cleanups.append(cached.cache_clear)
260
261 @functools.wraps(func)
262 def inner(*args, **kwds):
263 try:
264 return cached(*args, **kwds)
265 except TypeError:
266 pass # All real errors (not unhashable args) are raised below.
267 return func(*args, **kwds)
268 return inner
269
270
271def _eval_type(t, globalns, localns):
272 """Evaluate all forward reverences in the given type t.
273 For use of globalns and localns see the docstring for get_type_hints().
274 """
275 if isinstance(t, ForwardRef):
276 return t._evaluate(globalns, localns)
277 if isinstance(t, _GenericAlias):
278 ev_args = tuple(_eval_type(a, globalns, localns) for a in t.__args__)
279 if ev_args == t.__args__:
280 return t
281 res = t.copy_with(ev_args)
282 res._special = t._special
283 return res
Serhiy Storchaka68b352a2020-04-26 21:21:08 +0300284 if isinstance(t, GenericAlias):
285 ev_args = tuple(_eval_type(a, globalns, localns) for a in t.__args__)
286 if ev_args == t.__args__:
287 return t
288 return GenericAlias(t.__origin__, ev_args)
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000289 return t
290
291
292class _Final:
293 """Mixin to prohibit subclassing"""
Guido van Rossum4cefe742016-09-27 15:20:12 -0700294
Guido van Rossum83ec3022017-01-17 20:43:28 -0800295 __slots__ = ('__weakref__',)
Guido van Rossum4cefe742016-09-27 15:20:12 -0700296
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300297 def __init_subclass__(self, /, *args, **kwds):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000298 if '_root' not in kwds:
299 raise TypeError("Cannot subclass special typing classes")
300
Ivan Levkivskyi83494032018-03-26 23:01:12 +0100301class _Immutable:
302 """Mixin to indicate that object should not be copied."""
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000303
Ivan Levkivskyi83494032018-03-26 23:01:12 +0100304 def __copy__(self):
305 return self
306
307 def __deepcopy__(self, memo):
308 return self
309
310
Serhiy Storchaka40ded942020-04-23 21:26:48 +0300311# Internal indicator of special typing constructs.
312# See __doc__ instance attribute for specific docs.
313class _SpecialForm(_Final, _root=True):
314 __slots__ = ('_name', '__doc__', '_getitem')
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000315
Serhiy Storchaka40ded942020-04-23 21:26:48 +0300316 def __init__(self, getitem):
317 self._getitem = getitem
318 self._name = getitem.__name__
319 self.__doc__ = getitem.__doc__
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000320
Serhiy Storchaka40ded942020-04-23 21:26:48 +0300321 def __mro_entries__(self, bases):
322 raise TypeError(f"Cannot subclass {self!r}")
Guido van Rossum4cefe742016-09-27 15:20:12 -0700323
324 def __repr__(self):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000325 return 'typing.' + self._name
326
Ivan Levkivskyi83494032018-03-26 23:01:12 +0100327 def __reduce__(self):
328 return self._name
Guido van Rossum4cefe742016-09-27 15:20:12 -0700329
330 def __call__(self, *args, **kwds):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000331 raise TypeError(f"Cannot instantiate {self!r}")
332
333 def __instancecheck__(self, obj):
334 raise TypeError(f"{self} cannot be used with isinstance()")
335
336 def __subclasscheck__(self, cls):
337 raise TypeError(f"{self} cannot be used with issubclass()")
338
339 @_tp_cache
340 def __getitem__(self, parameters):
Serhiy Storchaka40ded942020-04-23 21:26:48 +0300341 return self._getitem(self, parameters)
Guido van Rossum4cefe742016-09-27 15:20:12 -0700342
Serhiy Storchaka40ded942020-04-23 21:26:48 +0300343@_SpecialForm
344def Any(self, parameters):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000345 """Special type indicating an unconstrained type.
Guido van Rossumb47c9d22016-10-03 08:40:50 -0700346
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000347 - Any is compatible with every type.
348 - Any assumed to have all methods.
349 - All values assumed to be instances of Any.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700350
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000351 Note that all the above statements are true from the point of view of
352 static type checkers. At runtime, Any should not be used with instance
353 or class checks.
Serhiy Storchaka40ded942020-04-23 21:26:48 +0300354 """
355 raise TypeError(f"{self} is not subscriptable")
Guido van Rossumd70fe632015-08-05 12:11:06 +0200356
Serhiy Storchaka40ded942020-04-23 21:26:48 +0300357@_SpecialForm
358def NoReturn(self, parameters):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000359 """Special type indicating functions that never return.
360 Example::
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700361
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000362 from typing import NoReturn
363
364 def stop() -> NoReturn:
365 raise Exception('no way')
366
367 This type is invalid in other positions, e.g., ``List[NoReturn]``
368 will fail in static type checkers.
Serhiy Storchaka40ded942020-04-23 21:26:48 +0300369 """
370 raise TypeError(f"{self} is not subscriptable")
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000371
Serhiy Storchaka40ded942020-04-23 21:26:48 +0300372@_SpecialForm
373def ClassVar(self, parameters):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000374 """Special type construct to mark class variables.
375
376 An annotation wrapped in ClassVar indicates that a given
377 attribute is intended to be used as a class variable and
378 should not be set on instances of that class. Usage::
379
380 class Starship:
381 stats: ClassVar[Dict[str, int]] = {} # class variable
382 damage: int = 10 # instance variable
383
384 ClassVar accepts only types and cannot be further subscribed.
385
386 Note that ClassVar is not a class itself, and should not
387 be used with isinstance() or issubclass().
Serhiy Storchaka40ded942020-04-23 21:26:48 +0300388 """
389 item = _type_check(parameters, f'{self} accepts only single type.')
390 return _GenericAlias(self, (item,))
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000391
Serhiy Storchaka40ded942020-04-23 21:26:48 +0300392@_SpecialForm
393def Final(self, parameters):
Ivan Levkivskyif3672422019-05-26 09:37:07 +0100394 """Special typing construct to indicate final names to type checkers.
395
396 A final name cannot be re-assigned or overridden in a subclass.
397 For example:
398
399 MAX_SIZE: Final = 9000
400 MAX_SIZE += 1 # Error reported by type checker
401
402 class Connection:
403 TIMEOUT: Final[int] = 10
404
405 class FastConnector(Connection):
406 TIMEOUT = 1 # Error reported by type checker
407
408 There is no runtime checking of these properties.
Serhiy Storchaka40ded942020-04-23 21:26:48 +0300409 """
410 item = _type_check(parameters, f'{self} accepts only single type.')
411 return _GenericAlias(self, (item,))
Ivan Levkivskyif3672422019-05-26 09:37:07 +0100412
Serhiy Storchaka40ded942020-04-23 21:26:48 +0300413@_SpecialForm
414def Union(self, parameters):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000415 """Union type; Union[X, Y] means either X or Y.
416
417 To define a union, use e.g. Union[int, str]. Details:
418 - The arguments must be types and there must be at least one.
419 - None as an argument is a special case and is replaced by
420 type(None).
421 - Unions of unions are flattened, e.g.::
422
423 Union[Union[int, str], float] == Union[int, str, float]
424
425 - Unions of a single argument vanish, e.g.::
426
427 Union[int] == int # The constructor actually returns int
428
429 - Redundant arguments are skipped, e.g.::
430
431 Union[int, str, int] == Union[int, str]
432
433 - When comparing unions, the argument order is ignored, e.g.::
434
435 Union[int, str] == Union[str, int]
436
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000437 - You cannot subclass or instantiate a union.
438 - You can use Optional[X] as a shorthand for Union[X, None].
Serhiy Storchaka40ded942020-04-23 21:26:48 +0300439 """
440 if parameters == ():
441 raise TypeError("Cannot take a Union of no types.")
442 if not isinstance(parameters, tuple):
443 parameters = (parameters,)
444 msg = "Union[arg, ...]: each arg must be a type."
445 parameters = tuple(_type_check(p, msg) for p in parameters)
446 parameters = _remove_dups_flatten(parameters)
447 if len(parameters) == 1:
448 return parameters[0]
449 return _GenericAlias(self, parameters)
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000450
Serhiy Storchaka40ded942020-04-23 21:26:48 +0300451@_SpecialForm
452def Optional(self, parameters):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000453 """Optional type.
454
455 Optional[X] is equivalent to Union[X, None].
Serhiy Storchaka40ded942020-04-23 21:26:48 +0300456 """
457 arg = _type_check(parameters, f"{self} requires a single type.")
458 return Union[arg, type(None)]
Guido van Rossumb7dedc82016-10-29 12:44:29 -0700459
Serhiy Storchaka40ded942020-04-23 21:26:48 +0300460@_SpecialForm
461def Literal(self, parameters):
Ivan Levkivskyib891c462019-05-26 09:37:48 +0100462 """Special typing form to define literal types (a.k.a. value types).
463
464 This form can be used to indicate to type checkers that the corresponding
465 variable or function parameter has a value equivalent to the provided
466 literal (or one of several literals):
467
468 def validate_simple(data: Any) -> Literal[True]: # always returns True
469 ...
470
471 MODE = Literal['r', 'rb', 'w', 'wb']
472 def open_helper(file: str, mode: MODE) -> str:
473 ...
474
475 open_helper('/some/path', 'r') # Passes type check
476 open_helper('/other/path', 'typo') # Error in type checker
477
Serhiy Storchaka40ded942020-04-23 21:26:48 +0300478 Literal[...] cannot be subclassed. At runtime, an arbitrary value
479 is allowed as type argument to Literal[...], but type checkers may
480 impose restrictions.
481 """
482 # There is no '_type_check' call because arguments to Literal[...] are
483 # values, not types.
484 return _GenericAlias(self, parameters)
Ivan Levkivskyib891c462019-05-26 09:37:48 +0100485
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700486
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000487class ForwardRef(_Final, _root=True):
Guido van Rossumb24569a2016-11-20 18:01:29 -0800488 """Internal wrapper to hold a forward reference."""
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700489
Guido van Rossum4cefe742016-09-27 15:20:12 -0700490 __slots__ = ('__forward_arg__', '__forward_code__',
Nina Zakharenko2d2d3b12018-05-16 12:27:03 -0400491 '__forward_evaluated__', '__forward_value__',
492 '__forward_is_argument__')
Guido van Rossum4cefe742016-09-27 15:20:12 -0700493
Nina Zakharenko0e61dff2018-05-22 20:32:10 -0700494 def __init__(self, arg, is_argument=True):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700495 if not isinstance(arg, str):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000496 raise TypeError(f"Forward reference must be a string -- got {arg!r}")
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700497 try:
498 code = compile(arg, '<string>', 'eval')
499 except SyntaxError:
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000500 raise SyntaxError(f"Forward reference must be an expression -- got {arg!r}")
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700501 self.__forward_arg__ = arg
502 self.__forward_code__ = code
503 self.__forward_evaluated__ = False
504 self.__forward_value__ = None
Nina Zakharenko2d2d3b12018-05-16 12:27:03 -0400505 self.__forward_is_argument__ = is_argument
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700506
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000507 def _evaluate(self, globalns, localns):
Guido van Rossumdad17902016-11-10 08:29:18 -0800508 if not self.__forward_evaluated__ or localns is not globalns:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700509 if globalns is None and localns is None:
510 globalns = localns = {}
511 elif globalns is None:
512 globalns = localns
513 elif localns is None:
514 localns = globalns
515 self.__forward_value__ = _type_check(
516 eval(self.__forward_code__, globalns, localns),
Nina Zakharenko2d2d3b12018-05-16 12:27:03 -0400517 "Forward references must evaluate to types.",
518 is_argument=self.__forward_is_argument__)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700519 self.__forward_evaluated__ = True
520 return self.__forward_value__
521
Guido van Rossum4cefe742016-09-27 15:20:12 -0700522 def __eq__(self, other):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000523 if not isinstance(other, ForwardRef):
Guido van Rossum4cefe742016-09-27 15:20:12 -0700524 return NotImplemented
plokmijnuhbye082e7c2019-09-13 20:40:54 +0100525 if self.__forward_evaluated__ and other.__forward_evaluated__:
526 return (self.__forward_arg__ == other.__forward_arg__ and
527 self.__forward_value__ == other.__forward_value__)
528 return self.__forward_arg__ == other.__forward_arg__
Guido van Rossum4cefe742016-09-27 15:20:12 -0700529
530 def __hash__(self):
plokmijnuhbye082e7c2019-09-13 20:40:54 +0100531 return hash(self.__forward_arg__)
Guido van Rossum4cefe742016-09-27 15:20:12 -0700532
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700533 def __repr__(self):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000534 return f'ForwardRef({self.__forward_arg__!r})'
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700535
536
Ivan Levkivskyi83494032018-03-26 23:01:12 +0100537class TypeVar(_Final, _Immutable, _root=True):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700538 """Type variable.
539
540 Usage::
541
542 T = TypeVar('T') # Can be anything
543 A = TypeVar('A', str, bytes) # Must be str or bytes
544
545 Type variables exist primarily for the benefit of static type
546 checkers. They serve as the parameters for generic types as well
547 as for generic function definitions. See class Generic for more
548 information on generic types. Generic functions work as follows:
549
Guido van Rossumb24569a2016-11-20 18:01:29 -0800550 def repeat(x: T, n: int) -> List[T]:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700551 '''Return a list containing n references to x.'''
552 return [x]*n
553
554 def longest(x: A, y: A) -> A:
555 '''Return the longest of two strings.'''
556 return x if len(x) >= len(y) else y
557
558 The latter example's signature is essentially the overloading
559 of (str, str) -> str and (bytes, bytes) -> bytes. Also note
560 that if the arguments are instances of some subclass of str,
561 the return type is still plain str.
562
Guido van Rossumb24569a2016-11-20 18:01:29 -0800563 At runtime, isinstance(x, T) and issubclass(C, T) will raise TypeError.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700564
Guido van Rossumefa798d2016-08-23 11:01:50 -0700565 Type variables defined with covariant=True or contravariant=True
João D. Ferreira86bfed32018-07-07 16:41:20 +0100566 can be used to declare covariant or contravariant generic types.
Guido van Rossumefa798d2016-08-23 11:01:50 -0700567 See PEP 484 for more details. By default generic types are invariant
568 in all type variables.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700569
570 Type variables can be introspected. e.g.:
571
572 T.__name__ == 'T'
573 T.__constraints__ == ()
574 T.__covariant__ == False
575 T.__contravariant__ = False
576 A.__constraints__ == (str, bytes)
Ivan Levkivskyi83494032018-03-26 23:01:12 +0100577
578 Note that only type variables defined in global scope can be pickled.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700579 """
580
Guido van Rossum4cefe742016-09-27 15:20:12 -0700581 __slots__ = ('__name__', '__bound__', '__constraints__',
Serhiy Storchaka09f32212018-05-26 21:19:26 +0300582 '__covariant__', '__contravariant__')
Guido van Rossum4cefe742016-09-27 15:20:12 -0700583
584 def __init__(self, name, *constraints, bound=None,
Guido van Rossumd7adfe12017-01-22 17:43:53 -0800585 covariant=False, contravariant=False):
Guido van Rossum4cefe742016-09-27 15:20:12 -0700586 self.__name__ = name
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700587 if covariant and contravariant:
Guido van Rossumefa798d2016-08-23 11:01:50 -0700588 raise ValueError("Bivariant types are not supported.")
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700589 self.__covariant__ = bool(covariant)
590 self.__contravariant__ = bool(contravariant)
591 if constraints and bound is not None:
592 raise TypeError("Constraints cannot be combined with bound=...")
593 if constraints and len(constraints) == 1:
594 raise TypeError("A single constraint is not allowed")
595 msg = "TypeVar(name, constraint, ...): constraints must be types."
596 self.__constraints__ = tuple(_type_check(t, msg) for t in constraints)
597 if bound:
598 self.__bound__ = _type_check(bound, "Bound must be a type.")
599 else:
600 self.__bound__ = None
HongWeipenga25a04f2020-04-21 04:01:53 +0800601 try:
602 def_mod = sys._getframe(1).f_globals.get('__name__', '__main__') # for pickling
603 except (AttributeError, ValueError):
604 def_mod = None
Serhiy Storchaka09f32212018-05-26 21:19:26 +0300605 if def_mod != 'typing':
606 self.__module__ = def_mod
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700607
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700608 def __repr__(self):
609 if self.__covariant__:
610 prefix = '+'
611 elif self.__contravariant__:
612 prefix = '-'
613 else:
614 prefix = '~'
615 return prefix + self.__name__
616
Ivan Levkivskyi83494032018-03-26 23:01:12 +0100617 def __reduce__(self):
Serhiy Storchaka09f32212018-05-26 21:19:26 +0300618 return self.__name__
Ivan Levkivskyi83494032018-03-26 23:01:12 +0100619
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700620
Guido van Rossum83ec3022017-01-17 20:43:28 -0800621# Special typing constructs Union, Optional, Generic, Callable and Tuple
622# use three special attributes for internal bookkeeping of generic types:
623# * __parameters__ is a tuple of unique free type parameters of a generic
624# type, for example, Dict[T, T].__parameters__ == (T,);
625# * __origin__ keeps a reference to a type that was subscripted,
Ivan Levkivskyi43d12a62018-05-09 02:23:46 +0100626# e.g., Union[T, int].__origin__ == Union, or the non-generic version of
627# the type.
Guido van Rossum83ec3022017-01-17 20:43:28 -0800628# * __args__ is a tuple of all arguments used in subscripting,
629# e.g., Dict[T, int].__args__ == (T, int).
630
Ivan Levkivskyi2a363d22018-04-05 01:25:15 +0100631
632# Mapping from non-generic type names that have a generic alias in typing
633# but with a different name.
634_normalize_alias = {'list': 'List',
635 'tuple': 'Tuple',
636 'dict': 'Dict',
637 'set': 'Set',
638 'frozenset': 'FrozenSet',
639 'deque': 'Deque',
640 'defaultdict': 'DefaultDict',
641 'type': 'Type',
642 'Set': 'AbstractSet'}
643
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000644def _is_dunder(attr):
645 return attr.startswith('__') and attr.endswith('__')
Guido van Rossum83ec3022017-01-17 20:43:28 -0800646
Guido van Rossumb24569a2016-11-20 18:01:29 -0800647
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000648class _GenericAlias(_Final, _root=True):
649 """The central part of internal API.
650
651 This represents a generic version of type 'origin' with type arguments 'params'.
652 There are two kind of these aliases: user defined and special. The special ones
653 are wrappers around builtin collections and ABCs in collections.abc. These must
654 have 'name' always set. If 'inst' is False, then the alias can't be instantiated,
655 this is used by e.g. typing.List and typing.Dict.
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700656 """
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000657 def __init__(self, origin, params, *, inst=True, special=False, name=None):
658 self._inst = inst
659 self._special = special
660 if special and name is None:
661 orig_name = origin.__name__
Ivan Levkivskyi2a363d22018-04-05 01:25:15 +0100662 name = _normalize_alias.get(orig_name, orig_name)
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000663 self._name = name
664 if not isinstance(params, tuple):
665 params = (params,)
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700666 self.__origin__ = origin
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700667 self.__args__ = tuple(... if a is _TypingEllipsis else
668 () if a is _TypingEmpty else
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000669 a for a in params)
670 self.__parameters__ = _collect_type_vars(params)
671 self.__slots__ = None # This is not documented.
672 if not name:
673 self.__module__ = origin.__module__
Serhiy Storchaka7e644142020-04-18 17:13:21 +0300674 if special:
675 self.__doc__ = f'A generic version of {origin.__module__}.{origin.__qualname__}'
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700676
Guido van Rossum4cefe742016-09-27 15:20:12 -0700677 @_tp_cache
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700678 def __getitem__(self, params):
Ivan Levkivskyi74d7f762019-05-28 08:40:15 +0100679 if self.__origin__ in (Generic, Protocol):
680 # Can't subscript Generic[...] or Protocol[...].
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000681 raise TypeError(f"Cannot subscript already-subscripted {self}")
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700682 if not isinstance(params, tuple):
683 params = (params,)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700684 msg = "Parameters to generic types must be types."
685 params = tuple(_type_check(p, msg) for p in params)
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000686 _check_generic(self, params)
687 return _subs_tvars(self, self.__parameters__, params)
Ivan Levkivskyib692dc82017-02-13 22:50:14 +0100688
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000689 def copy_with(self, params):
690 # We don't copy self._special.
691 return _GenericAlias(self.__origin__, params, name=self._name, inst=self._inst)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700692
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000693 def __repr__(self):
Vlad Serebrennikov138a9b92020-04-30 04:06:39 +0300694 if (self.__origin__ == Union and len(self.__args__) == 2
695 and type(None) in self.__args__):
696 if self.__args__[0] is not type(None):
697 arg = self.__args__[0]
698 else:
699 arg = self.__args__[1]
700 return (f'typing.Optional[{_type_repr(arg)}]')
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000701 if (self._name != 'Callable' or
702 len(self.__args__) == 2 and self.__args__[0] is Ellipsis):
703 if self._name:
704 name = 'typing.' + self._name
705 else:
706 name = _type_repr(self.__origin__)
707 if not self._special:
708 args = f'[{", ".join([_type_repr(a) for a in self.__args__])}]'
709 else:
710 args = ''
711 return (f'{name}{args}')
712 if self._special:
713 return 'typing.Callable'
714 return (f'typing.Callable'
715 f'[[{", ".join([_type_repr(a) for a in self.__args__[:-1]])}], '
716 f'{_type_repr(self.__args__[-1])}]')
717
718 def __eq__(self, other):
719 if not isinstance(other, _GenericAlias):
720 return NotImplemented
721 if self.__origin__ != other.__origin__:
Ivan Levkivskyib692dc82017-02-13 22:50:14 +0100722 return False
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000723 if self.__origin__ is Union and other.__origin__ is Union:
724 return frozenset(self.__args__) == frozenset(other.__args__)
725 return self.__args__ == other.__args__
Ivan Levkivskyib692dc82017-02-13 22:50:14 +0100726
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000727 def __hash__(self):
728 if self.__origin__ is Union:
729 return hash((Union, frozenset(self.__args__)))
730 return hash((self.__origin__, self.__args__))
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700731
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000732 def __call__(self, *args, **kwargs):
733 if not self._inst:
734 raise TypeError(f"Type {self._name} cannot be instantiated; "
735 f"use {self._name.lower()}() instead")
736 result = self.__origin__(*args, **kwargs)
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700737 try:
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000738 result.__orig_class__ = self
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700739 except AttributeError:
740 pass
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000741 return result
742
743 def __mro_entries__(self, bases):
744 if self._name: # generic version of an ABC or built-in class
745 res = []
746 if self.__origin__ not in bases:
747 res.append(self.__origin__)
748 i = bases.index(self)
749 if not any(isinstance(b, _GenericAlias) or issubclass(b, Generic)
750 for b in bases[i+1:]):
751 res.append(Generic)
752 return tuple(res)
753 if self.__origin__ is Generic:
Ivan Levkivskyi74d7f762019-05-28 08:40:15 +0100754 if Protocol in bases:
755 return ()
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000756 i = bases.index(self)
757 for b in bases[i+1:]:
758 if isinstance(b, _GenericAlias) and b is not self:
759 return ()
760 return (self.__origin__,)
761
762 def __getattr__(self, attr):
Ville Skyttä61f82e02018-04-20 23:08:45 +0300763 # We are careful for copy and pickle.
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000764 # Also for simplicity we just don't relay all dunder names
765 if '__origin__' in self.__dict__ and not _is_dunder(attr):
766 return getattr(self.__origin__, attr)
767 raise AttributeError(attr)
768
769 def __setattr__(self, attr, val):
770 if _is_dunder(attr) or attr in ('_name', '_inst', '_special'):
771 super().__setattr__(attr, val)
772 else:
773 setattr(self.__origin__, attr, val)
774
775 def __instancecheck__(self, obj):
776 return self.__subclasscheck__(type(obj))
777
778 def __subclasscheck__(self, cls):
779 if self._special:
780 if not isinstance(cls, _GenericAlias):
781 return issubclass(cls, self.__origin__)
782 if cls._special:
783 return issubclass(cls.__origin__, self.__origin__)
784 raise TypeError("Subscripted generics cannot be used with"
785 " class and instance checks")
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700786
Ivan Levkivskyi83494032018-03-26 23:01:12 +0100787 def __reduce__(self):
788 if self._special:
789 return self._name
Serhiy Storchaka09f32212018-05-26 21:19:26 +0300790
791 if self._name:
792 origin = globals()[self._name]
793 else:
794 origin = self.__origin__
795 if (origin is Callable and
796 not (len(self.__args__) == 2 and self.__args__[0] is Ellipsis)):
797 args = list(self.__args__[:-1]), self.__args__[-1]
798 else:
799 args = tuple(self.__args__)
800 if len(args) == 1 and not isinstance(args[0], tuple):
801 args, = args
802 return operator.getitem, (origin, args)
Ivan Levkivskyi83494032018-03-26 23:01:12 +0100803
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700804
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000805class _VariadicGenericAlias(_GenericAlias, _root=True):
806 """Same as _GenericAlias above but for variadic aliases. Currently,
807 this is used only by special internal aliases: Tuple and Callable.
808 """
809 def __getitem__(self, params):
810 if self._name != 'Callable' or not self._special:
811 return self.__getitem_inner__(params)
812 if not isinstance(params, tuple) or len(params) != 2:
813 raise TypeError("Callable must be used as "
814 "Callable[[arg, ...], result].")
815 args, result = params
816 if args is Ellipsis:
817 params = (Ellipsis, result)
818 else:
819 if not isinstance(args, list):
820 raise TypeError(f"Callable[args, result]: args must be a list."
821 f" Got {args}")
822 params = (tuple(args), result)
823 return self.__getitem_inner__(params)
824
825 @_tp_cache
826 def __getitem_inner__(self, params):
827 if self.__origin__ is tuple and self._special:
828 if params == ():
829 return self.copy_with((_TypingEmpty,))
830 if not isinstance(params, tuple):
831 params = (params,)
832 if len(params) == 2 and params[1] is ...:
833 msg = "Tuple[t, ...]: t must be a type."
834 p = _type_check(params[0], msg)
835 return self.copy_with((p, _TypingEllipsis))
836 msg = "Tuple[t0, t1, ...]: each t must be a type."
837 params = tuple(_type_check(p, msg) for p in params)
838 return self.copy_with(params)
839 if self.__origin__ is collections.abc.Callable and self._special:
840 args, result = params
841 msg = "Callable[args, result]: result must be a type."
842 result = _type_check(result, msg)
843 if args is Ellipsis:
844 return self.copy_with((_TypingEllipsis, result))
845 msg = "Callable[[arg, ...], result]: each arg must be a type."
846 args = tuple(_type_check(arg, msg) for arg in args)
847 params = args + (result,)
848 return self.copy_with(params)
849 return super().__getitem__(params)
850
851
852class Generic:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700853 """Abstract base class for generic types.
854
Guido van Rossumb24569a2016-11-20 18:01:29 -0800855 A generic type is typically declared by inheriting from
856 this class parameterized with one or more type variables.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700857 For example, a generic mapping type might be defined as::
858
859 class Mapping(Generic[KT, VT]):
860 def __getitem__(self, key: KT) -> VT:
861 ...
862 # Etc.
863
864 This class can then be used as follows::
865
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700866 def lookup_name(mapping: Mapping[KT, VT], key: KT, default: VT) -> VT:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700867 try:
868 return mapping[key]
869 except KeyError:
870 return default
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700871 """
Guido van Rossumd70fe632015-08-05 12:11:06 +0200872 __slots__ = ()
Ivan Levkivskyi74d7f762019-05-28 08:40:15 +0100873 _is_protocol = False
Guido van Rossumd70fe632015-08-05 12:11:06 +0200874
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700875 def __new__(cls, *args, **kwds):
Ivan Levkivskyi74d7f762019-05-28 08:40:15 +0100876 if cls in (Generic, Protocol):
877 raise TypeError(f"Type {cls.__name__} cannot be instantiated; "
Guido van Rossum62fe1bb2016-10-29 16:05:26 -0700878 "it can be used only as a base class")
Ivan Levkivskyib551e9f2018-05-10 23:10:10 -0400879 if super().__new__ is object.__new__ and cls.__init__ is not object.__init__:
Ivan Levkivskyi43d12a62018-05-09 02:23:46 +0100880 obj = super().__new__(cls)
881 else:
882 obj = super().__new__(cls, *args, **kwds)
883 return obj
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000884
885 @_tp_cache
886 def __class_getitem__(cls, params):
887 if not isinstance(params, tuple):
888 params = (params,)
889 if not params and cls is not Tuple:
890 raise TypeError(
891 f"Parameter list to {cls.__qualname__}[...] cannot be empty")
892 msg = "Parameters to generic types must be types."
893 params = tuple(_type_check(p, msg) for p in params)
Ivan Levkivskyi74d7f762019-05-28 08:40:15 +0100894 if cls in (Generic, Protocol):
895 # Generic and Protocol can only be subscripted with unique type variables.
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000896 if not all(isinstance(p, TypeVar) for p in params):
897 raise TypeError(
Ivan Levkivskyi74d7f762019-05-28 08:40:15 +0100898 f"Parameters to {cls.__name__}[...] must all be type variables")
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000899 if len(set(params)) != len(params):
900 raise TypeError(
Ivan Levkivskyi74d7f762019-05-28 08:40:15 +0100901 f"Parameters to {cls.__name__}[...] must all be unique")
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000902 else:
903 # Subscripting a regular Generic subclass.
904 _check_generic(cls, params)
905 return _GenericAlias(cls, params)
906
907 def __init_subclass__(cls, *args, **kwargs):
Ivan Levkivskyiee566fe2018-04-04 17:00:15 +0100908 super().__init_subclass__(*args, **kwargs)
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000909 tvars = []
910 if '__orig_bases__' in cls.__dict__:
911 error = Generic in cls.__orig_bases__
912 else:
Ivan Levkivskyi74d7f762019-05-28 08:40:15 +0100913 error = Generic in cls.__bases__ and cls.__name__ != 'Protocol'
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000914 if error:
915 raise TypeError("Cannot inherit from plain Generic")
916 if '__orig_bases__' in cls.__dict__:
917 tvars = _collect_type_vars(cls.__orig_bases__)
918 # Look for Generic[T1, ..., Tn].
919 # If found, tvars must be a subset of it.
920 # If not found, tvars is it.
921 # Also check for and reject plain Generic,
922 # and reject multiple Generic[...].
923 gvars = None
924 for base in cls.__orig_bases__:
925 if (isinstance(base, _GenericAlias) and
926 base.__origin__ is Generic):
927 if gvars is not None:
928 raise TypeError(
929 "Cannot inherit from Generic[...] multiple types.")
930 gvars = base.__parameters__
Ivan Levkivskyi74d7f762019-05-28 08:40:15 +0100931 if gvars is not None:
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000932 tvarset = set(tvars)
933 gvarset = set(gvars)
934 if not tvarset <= gvarset:
935 s_vars = ', '.join(str(t) for t in tvars if t not in gvarset)
936 s_args = ', '.join(str(g) for g in gvars)
937 raise TypeError(f"Some type variables ({s_vars}) are"
938 f" not listed in Generic[{s_args}]")
939 tvars = gvars
940 cls.__parameters__ = tuple(tvars)
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700941
942
943class _TypingEmpty:
Guido van Rossumb24569a2016-11-20 18:01:29 -0800944 """Internal placeholder for () or []. Used by TupleMeta and CallableMeta
945 to allow empty list/tuple in specific places, without allowing them
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700946 to sneak in where prohibited.
947 """
948
949
950class _TypingEllipsis:
Guido van Rossumb24569a2016-11-20 18:01:29 -0800951 """Internal placeholder for ... (ellipsis)."""
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700952
953
Ivan Levkivskyi74d7f762019-05-28 08:40:15 +0100954_TYPING_INTERNALS = ['__parameters__', '__orig_bases__', '__orig_class__',
955 '_is_protocol', '_is_runtime_protocol']
956
957_SPECIAL_NAMES = ['__abstractmethods__', '__annotations__', '__dict__', '__doc__',
958 '__init__', '__module__', '__new__', '__slots__',
Guido van Rossum48b069a2020-04-07 09:50:06 -0700959 '__subclasshook__', '__weakref__', '__class_getitem__']
Ivan Levkivskyi74d7f762019-05-28 08:40:15 +0100960
961# These special attributes will be not collected as protocol members.
962EXCLUDED_ATTRIBUTES = _TYPING_INTERNALS + _SPECIAL_NAMES + ['_MutableMapping__marker']
963
964
965def _get_protocol_attrs(cls):
966 """Collect protocol members from a protocol class objects.
967
968 This includes names actually defined in the class dictionary, as well
969 as names that appear in annotations. Special names (above) are skipped.
970 """
971 attrs = set()
972 for base in cls.__mro__[:-1]: # without object
973 if base.__name__ in ('Protocol', 'Generic'):
974 continue
975 annotations = getattr(base, '__annotations__', {})
976 for attr in list(base.__dict__.keys()) + list(annotations.keys()):
977 if not attr.startswith('_abc_') and attr not in EXCLUDED_ATTRIBUTES:
978 attrs.add(attr)
979 return attrs
980
981
982def _is_callable_members_only(cls):
983 # PEP 544 prohibits using issubclass() with protocols that have non-method members.
984 return all(callable(getattr(cls, attr, None)) for attr in _get_protocol_attrs(cls))
985
986
987def _no_init(self, *args, **kwargs):
988 if type(self)._is_protocol:
989 raise TypeError('Protocols cannot be instantiated')
990
991
992def _allow_reckless_class_cheks():
Nickolena Fishercfaf4c02020-04-26 12:49:11 -0500993 """Allow instance and class checks for special stdlib modules.
Ivan Levkivskyi74d7f762019-05-28 08:40:15 +0100994
995 The abc and functools modules indiscriminately call isinstance() and
996 issubclass() on the whole MRO of a user class, which may contain protocols.
997 """
998 try:
999 return sys._getframe(3).f_globals['__name__'] in ['abc', 'functools']
1000 except (AttributeError, ValueError): # For platforms without _getframe().
1001 return True
1002
1003
Divij Rajkumar692a0dc2019-09-12 11:13:51 +01001004_PROTO_WHITELIST = {
1005 'collections.abc': [
1006 'Callable', 'Awaitable', 'Iterable', 'Iterator', 'AsyncIterable',
1007 'Hashable', 'Sized', 'Container', 'Collection', 'Reversible',
1008 ],
1009 'contextlib': ['AbstractContextManager', 'AbstractAsyncContextManager'],
1010}
Ivan Levkivskyi74d7f762019-05-28 08:40:15 +01001011
1012
1013class _ProtocolMeta(ABCMeta):
1014 # This metaclass is really unfortunate and exists only because of
1015 # the lack of __instancehook__.
1016 def __instancecheck__(cls, instance):
1017 # We need this method for situations where attributes are
1018 # assigned in __init__.
1019 if ((not getattr(cls, '_is_protocol', False) or
1020 _is_callable_members_only(cls)) and
1021 issubclass(instance.__class__, cls)):
1022 return True
1023 if cls._is_protocol:
1024 if all(hasattr(instance, attr) and
1025 # All *methods* can be blocked by setting them to None.
1026 (not callable(getattr(cls, attr, None)) or
1027 getattr(instance, attr) is not None)
1028 for attr in _get_protocol_attrs(cls)):
1029 return True
1030 return super().__instancecheck__(instance)
1031
1032
1033class Protocol(Generic, metaclass=_ProtocolMeta):
1034 """Base class for protocol classes.
1035
1036 Protocol classes are defined as::
1037
1038 class Proto(Protocol):
1039 def meth(self) -> int:
1040 ...
1041
1042 Such classes are primarily used with static type checkers that recognize
1043 structural subtyping (static duck-typing), for example::
1044
1045 class C:
1046 def meth(self) -> int:
1047 return 0
1048
1049 def func(x: Proto) -> int:
1050 return x.meth()
1051
1052 func(C()) # Passes static type check
1053
1054 See PEP 544 for details. Protocol classes decorated with
1055 @typing.runtime_checkable act as simple-minded runtime protocols that check
1056 only the presence of given attributes, ignoring their type signatures.
1057 Protocol classes can be generic, they are defined as::
1058
1059 class GenProto(Protocol[T]):
1060 def meth(self) -> T:
1061 ...
1062 """
1063 __slots__ = ()
1064 _is_protocol = True
1065 _is_runtime_protocol = False
1066
1067 def __init_subclass__(cls, *args, **kwargs):
1068 super().__init_subclass__(*args, **kwargs)
1069
1070 # Determine if this is a protocol or a concrete subclass.
1071 if not cls.__dict__.get('_is_protocol', False):
1072 cls._is_protocol = any(b is Protocol for b in cls.__bases__)
1073
1074 # Set (or override) the protocol subclass hook.
1075 def _proto_hook(other):
1076 if not cls.__dict__.get('_is_protocol', False):
1077 return NotImplemented
1078
1079 # First, perform various sanity checks.
1080 if not getattr(cls, '_is_runtime_protocol', False):
1081 if _allow_reckless_class_cheks():
1082 return NotImplemented
1083 raise TypeError("Instance and class checks can only be used with"
1084 " @runtime_checkable protocols")
1085 if not _is_callable_members_only(cls):
1086 if _allow_reckless_class_cheks():
1087 return NotImplemented
1088 raise TypeError("Protocols with non-method members"
1089 " don't support issubclass()")
1090 if not isinstance(other, type):
1091 # Same error message as for issubclass(1, int).
1092 raise TypeError('issubclass() arg 1 must be a class')
1093
1094 # Second, perform the actual structural compatibility check.
1095 for attr in _get_protocol_attrs(cls):
1096 for base in other.__mro__:
1097 # Check if the members appears in the class dictionary...
1098 if attr in base.__dict__:
1099 if base.__dict__[attr] is None:
1100 return NotImplemented
1101 break
1102
1103 # ...or in annotations, if it is a sub-protocol.
1104 annotations = getattr(base, '__annotations__', {})
1105 if (isinstance(annotations, collections.abc.Mapping) and
1106 attr in annotations and
1107 issubclass(other, Generic) and other._is_protocol):
1108 break
1109 else:
1110 return NotImplemented
1111 return True
1112
1113 if '__subclasshook__' not in cls.__dict__:
1114 cls.__subclasshook__ = _proto_hook
1115
1116 # We have nothing more to do for non-protocols...
1117 if not cls._is_protocol:
1118 return
1119
1120 # ... otherwise check consistency of bases, and prohibit instantiation.
1121 for base in cls.__bases__:
1122 if not (base in (object, Generic) or
Divij Rajkumar692a0dc2019-09-12 11:13:51 +01001123 base.__module__ in _PROTO_WHITELIST and
1124 base.__name__ in _PROTO_WHITELIST[base.__module__] or
Ivan Levkivskyi74d7f762019-05-28 08:40:15 +01001125 issubclass(base, Generic) and base._is_protocol):
1126 raise TypeError('Protocols can only inherit from other'
1127 ' protocols, got %r' % base)
1128 cls.__init__ = _no_init
1129
1130
Jakub Stasiakcf5b1092020-02-05 02:10:19 +01001131class _AnnotatedAlias(_GenericAlias, _root=True):
1132 """Runtime representation of an annotated type.
1133
1134 At its core 'Annotated[t, dec1, dec2, ...]' is an alias for the type 't'
1135 with extra annotations. The alias behaves like a normal typing alias,
1136 instantiating is the same as instantiating the underlying type, binding
1137 it to types is also the same.
1138 """
1139 def __init__(self, origin, metadata):
1140 if isinstance(origin, _AnnotatedAlias):
1141 metadata = origin.__metadata__ + metadata
1142 origin = origin.__origin__
1143 super().__init__(origin, origin)
1144 self.__metadata__ = metadata
1145
1146 def copy_with(self, params):
1147 assert len(params) == 1
1148 new_type = params[0]
1149 return _AnnotatedAlias(new_type, self.__metadata__)
1150
1151 def __repr__(self):
1152 return "typing.Annotated[{}, {}]".format(
1153 _type_repr(self.__origin__),
1154 ", ".join(repr(a) for a in self.__metadata__)
1155 )
1156
1157 def __reduce__(self):
1158 return operator.getitem, (
1159 Annotated, (self.__origin__,) + self.__metadata__
1160 )
1161
1162 def __eq__(self, other):
1163 if not isinstance(other, _AnnotatedAlias):
1164 return NotImplemented
1165 if self.__origin__ != other.__origin__:
1166 return False
1167 return self.__metadata__ == other.__metadata__
1168
1169 def __hash__(self):
1170 return hash((self.__origin__, self.__metadata__))
1171
1172
1173class Annotated:
1174 """Add context specific metadata to a type.
1175
1176 Example: Annotated[int, runtime_check.Unsigned] indicates to the
1177 hypothetical runtime_check module that this type is an unsigned int.
1178 Every other consumer of this type can ignore this metadata and treat
1179 this type as int.
1180
1181 The first argument to Annotated must be a valid type.
1182
1183 Details:
1184
1185 - It's an error to call `Annotated` with less than two arguments.
1186 - Nested Annotated are flattened::
1187
1188 Annotated[Annotated[T, Ann1, Ann2], Ann3] == Annotated[T, Ann1, Ann2, Ann3]
1189
1190 - Instantiating an annotated type is equivalent to instantiating the
1191 underlying type::
1192
1193 Annotated[C, Ann1](5) == C(5)
1194
1195 - Annotated can be used as a generic type alias::
1196
1197 Optimized = Annotated[T, runtime.Optimize()]
1198 Optimized[int] == Annotated[int, runtime.Optimize()]
1199
1200 OptimizedList = Annotated[List[T], runtime.Optimize()]
1201 OptimizedList[int] == Annotated[List[int], runtime.Optimize()]
1202 """
1203
1204 __slots__ = ()
1205
1206 def __new__(cls, *args, **kwargs):
1207 raise TypeError("Type Annotated cannot be instantiated.")
1208
1209 @_tp_cache
1210 def __class_getitem__(cls, params):
1211 if not isinstance(params, tuple) or len(params) < 2:
1212 raise TypeError("Annotated[...] should be used "
1213 "with at least two arguments (a type and an "
1214 "annotation).")
1215 msg = "Annotated[t, ...]: t must be a type."
1216 origin = _type_check(params[0], msg)
1217 metadata = tuple(params[1:])
1218 return _AnnotatedAlias(origin, metadata)
1219
1220 def __init_subclass__(cls, *args, **kwargs):
1221 raise TypeError(
1222 "Cannot subclass {}.Annotated".format(cls.__module__)
1223 )
1224
1225
Ivan Levkivskyi74d7f762019-05-28 08:40:15 +01001226def runtime_checkable(cls):
1227 """Mark a protocol class as a runtime protocol.
1228
1229 Such protocol can be used with isinstance() and issubclass().
1230 Raise TypeError if applied to a non-protocol class.
1231 This allows a simple-minded structural check very similar to
1232 one trick ponies in collections.abc such as Iterable.
1233 For example::
1234
1235 @runtime_checkable
1236 class Closable(Protocol):
1237 def close(self): ...
1238
1239 assert isinstance(open('/some/file'), Closable)
1240
1241 Warning: this will check only the presence of the required methods,
1242 not their type signatures!
1243 """
1244 if not issubclass(cls, Generic) or not cls._is_protocol:
1245 raise TypeError('@runtime_checkable can be only applied to protocol classes,'
1246 ' got %r' % cls)
1247 cls._is_runtime_protocol = True
1248 return cls
1249
1250
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001251def cast(typ, val):
1252 """Cast a value to a type.
1253
1254 This returns the value unchanged. To the type checker this
1255 signals that the return value has the designated type, but at
1256 runtime we intentionally don't check anything (we want this
1257 to be as fast as possible).
1258 """
1259 return val
1260
1261
1262def _get_defaults(func):
1263 """Internal helper to extract the default arguments, by name."""
Guido van Rossum991d14f2016-11-09 13:12:51 -08001264 try:
1265 code = func.__code__
1266 except AttributeError:
1267 # Some built-in functions don't have __code__, __defaults__, etc.
1268 return {}
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001269 pos_count = code.co_argcount
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001270 arg_names = code.co_varnames
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001271 arg_names = arg_names[:pos_count]
1272 defaults = func.__defaults__ or ()
1273 kwdefaults = func.__kwdefaults__
1274 res = dict(kwdefaults) if kwdefaults else {}
1275 pos_offset = pos_count - len(defaults)
1276 for name, value in zip(arg_names[pos_offset:], defaults):
1277 assert name not in res
1278 res[name] = value
1279 return res
1280
1281
Ivan Levkivskyib692dc82017-02-13 22:50:14 +01001282_allowed_types = (types.FunctionType, types.BuiltinFunctionType,
1283 types.MethodType, types.ModuleType,
Ivan Levkivskyif06e0212017-05-02 19:14:07 +02001284 WrapperDescriptorType, MethodWrapperType, MethodDescriptorType)
Ivan Levkivskyib692dc82017-02-13 22:50:14 +01001285
1286
Jakub Stasiakcf5b1092020-02-05 02:10:19 +01001287def get_type_hints(obj, globalns=None, localns=None, include_extras=False):
Guido van Rossum991d14f2016-11-09 13:12:51 -08001288 """Return type hints for an object.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001289
Guido van Rossum991d14f2016-11-09 13:12:51 -08001290 This is often the same as obj.__annotations__, but it handles
Jakub Stasiakcf5b1092020-02-05 02:10:19 +01001291 forward references encoded as string literals, adds Optional[t] if a
1292 default value equal to None is set and recursively replaces all
1293 'Annotated[T, ...]' with 'T' (unless 'include_extras=True').
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001294
Guido van Rossum991d14f2016-11-09 13:12:51 -08001295 The argument may be a module, class, method, or function. The annotations
1296 are returned as a dictionary. For classes, annotations include also
1297 inherited members.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001298
Guido van Rossum991d14f2016-11-09 13:12:51 -08001299 TypeError is raised if the argument is not of a type that can contain
1300 annotations, and an empty dictionary is returned if no annotations are
1301 present.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001302
Guido van Rossum991d14f2016-11-09 13:12:51 -08001303 BEWARE -- the behavior of globalns and localns is counterintuitive
1304 (unless you are familiar with how eval() and exec() work). The
1305 search order is locals first, then globals.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001306
Guido van Rossum991d14f2016-11-09 13:12:51 -08001307 - If no dict arguments are passed, an attempt is made to use the
Łukasz Langaf350a262017-09-14 14:33:00 -04001308 globals from obj (or the respective module's globals for classes),
1309 and these are also used as the locals. If the object does not appear
1310 to have globals, an empty dictionary is used.
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001311
Guido van Rossum991d14f2016-11-09 13:12:51 -08001312 - If one dict argument is passed, it is used for both globals and
1313 locals.
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001314
Guido van Rossum991d14f2016-11-09 13:12:51 -08001315 - If two dict arguments are passed, they specify globals and
1316 locals, respectively.
1317 """
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001318
Guido van Rossum991d14f2016-11-09 13:12:51 -08001319 if getattr(obj, '__no_type_check__', None):
1320 return {}
Guido van Rossum991d14f2016-11-09 13:12:51 -08001321 # Classes require a special treatment.
1322 if isinstance(obj, type):
1323 hints = {}
1324 for base in reversed(obj.__mro__):
Łukasz Langaf350a262017-09-14 14:33:00 -04001325 if globalns is None:
1326 base_globals = sys.modules[base.__module__].__dict__
1327 else:
1328 base_globals = globalns
Guido van Rossum991d14f2016-11-09 13:12:51 -08001329 ann = base.__dict__.get('__annotations__', {})
1330 for name, value in ann.items():
1331 if value is None:
1332 value = type(None)
1333 if isinstance(value, str):
Nina Zakharenko0e61dff2018-05-22 20:32:10 -07001334 value = ForwardRef(value, is_argument=False)
Łukasz Langaf350a262017-09-14 14:33:00 -04001335 value = _eval_type(value, base_globals, localns)
Guido van Rossum991d14f2016-11-09 13:12:51 -08001336 hints[name] = value
Jakub Stasiakcf5b1092020-02-05 02:10:19 +01001337 return hints if include_extras else {k: _strip_annotations(t) for k, t in hints.items()}
Łukasz Langaf350a262017-09-14 14:33:00 -04001338
1339 if globalns is None:
1340 if isinstance(obj, types.ModuleType):
1341 globalns = obj.__dict__
1342 else:
benedwards140aca3a32019-11-21 17:24:58 +00001343 nsobj = obj
1344 # Find globalns for the unwrapped object.
1345 while hasattr(nsobj, '__wrapped__'):
1346 nsobj = nsobj.__wrapped__
1347 globalns = getattr(nsobj, '__globals__', {})
Łukasz Langaf350a262017-09-14 14:33:00 -04001348 if localns is None:
1349 localns = globalns
1350 elif localns is None:
1351 localns = globalns
Guido van Rossum991d14f2016-11-09 13:12:51 -08001352 hints = getattr(obj, '__annotations__', None)
1353 if hints is None:
1354 # Return empty annotations for something that _could_ have them.
Ivan Levkivskyib692dc82017-02-13 22:50:14 +01001355 if isinstance(obj, _allowed_types):
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001356 return {}
Guido van Rossum991d14f2016-11-09 13:12:51 -08001357 else:
1358 raise TypeError('{!r} is not a module, class, method, '
1359 'or function.'.format(obj))
1360 defaults = _get_defaults(obj)
1361 hints = dict(hints)
1362 for name, value in hints.items():
1363 if value is None:
1364 value = type(None)
1365 if isinstance(value, str):
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001366 value = ForwardRef(value)
Guido van Rossum991d14f2016-11-09 13:12:51 -08001367 value = _eval_type(value, globalns, localns)
1368 if name in defaults and defaults[name] is None:
1369 value = Optional[value]
1370 hints[name] = value
Jakub Stasiakcf5b1092020-02-05 02:10:19 +01001371 return hints if include_extras else {k: _strip_annotations(t) for k, t in hints.items()}
1372
1373
1374def _strip_annotations(t):
1375 """Strips the annotations from a given type.
1376 """
1377 if isinstance(t, _AnnotatedAlias):
1378 return _strip_annotations(t.__origin__)
1379 if isinstance(t, _GenericAlias):
1380 stripped_args = tuple(_strip_annotations(a) for a in t.__args__)
1381 if stripped_args == t.__args__:
1382 return t
1383 res = t.copy_with(stripped_args)
1384 res._special = t._special
1385 return res
Serhiy Storchaka68b352a2020-04-26 21:21:08 +03001386 if isinstance(t, GenericAlias):
1387 stripped_args = tuple(_strip_annotations(a) for a in t.__args__)
1388 if stripped_args == t.__args__:
1389 return t
1390 return GenericAlias(t.__origin__, stripped_args)
Jakub Stasiakcf5b1092020-02-05 02:10:19 +01001391 return t
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001392
1393
Ivan Levkivskyi4c23aff2019-05-31 00:10:07 +01001394def get_origin(tp):
1395 """Get the unsubscripted version of a type.
1396
Jakub Stasiak38aaaaa2020-02-07 02:15:12 +01001397 This supports generic types, Callable, Tuple, Union, Literal, Final, ClassVar
1398 and Annotated. Return None for unsupported types. Examples::
Ivan Levkivskyi4c23aff2019-05-31 00:10:07 +01001399
1400 get_origin(Literal[42]) is Literal
1401 get_origin(int) is None
1402 get_origin(ClassVar[int]) is ClassVar
1403 get_origin(Generic) is Generic
1404 get_origin(Generic[T]) is Generic
1405 get_origin(Union[T, int]) is Union
1406 get_origin(List[Tuple[T, T]][int]) == list
1407 """
Jakub Stasiakcf5b1092020-02-05 02:10:19 +01001408 if isinstance(tp, _AnnotatedAlias):
1409 return Annotated
Serhiy Storchaka68b352a2020-04-26 21:21:08 +03001410 if isinstance(tp, (_GenericAlias, GenericAlias)):
Ivan Levkivskyi4c23aff2019-05-31 00:10:07 +01001411 return tp.__origin__
1412 if tp is Generic:
1413 return Generic
1414 return None
1415
1416
1417def get_args(tp):
1418 """Get type arguments with all substitutions performed.
1419
1420 For unions, basic simplifications used by Union constructor are performed.
1421 Examples::
1422 get_args(Dict[str, int]) == (str, int)
1423 get_args(int) == ()
1424 get_args(Union[int, Union[T, int], str][int]) == (int, str)
1425 get_args(Union[int, Tuple[T, int]][str]) == (int, Tuple[str, int])
1426 get_args(Callable[[], T][int]) == ([], int)
1427 """
Jakub Stasiakcf5b1092020-02-05 02:10:19 +01001428 if isinstance(tp, _AnnotatedAlias):
1429 return (tp.__origin__,) + tp.__metadata__
Serhiy Storchaka6292be72020-04-27 10:27:21 +03001430 if isinstance(tp, _GenericAlias) and not tp._special:
Ivan Levkivskyi4c23aff2019-05-31 00:10:07 +01001431 res = tp.__args__
Serhiy Storchaka68b352a2020-04-26 21:21:08 +03001432 if tp.__origin__ is collections.abc.Callable and res[0] is not Ellipsis:
Ivan Levkivskyi4c23aff2019-05-31 00:10:07 +01001433 res = (list(res[:-1]), res[-1])
1434 return res
Serhiy Storchaka6292be72020-04-27 10:27:21 +03001435 if isinstance(tp, GenericAlias):
1436 return tp.__args__
Ivan Levkivskyi4c23aff2019-05-31 00:10:07 +01001437 return ()
1438
1439
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001440def no_type_check(arg):
1441 """Decorator to indicate that annotations are not type hints.
1442
1443 The argument must be a class or function; if it is a class, it
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001444 applies recursively to all methods and classes defined in that class
1445 (but not to methods defined in its superclasses or subclasses).
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001446
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001447 This mutates the function(s) or class(es) in place.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001448 """
1449 if isinstance(arg, type):
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001450 arg_attrs = arg.__dict__.copy()
1451 for attr, val in arg.__dict__.items():
Ivan Levkivskyi65bc6202017-09-14 01:25:15 +02001452 if val in arg.__bases__ + (arg,):
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001453 arg_attrs.pop(attr)
1454 for obj in arg_attrs.values():
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001455 if isinstance(obj, types.FunctionType):
1456 obj.__no_type_check__ = True
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001457 if isinstance(obj, type):
1458 no_type_check(obj)
1459 try:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001460 arg.__no_type_check__ = True
Guido van Rossumd7adfe12017-01-22 17:43:53 -08001461 except TypeError: # built-in classes
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001462 pass
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001463 return arg
1464
1465
1466def no_type_check_decorator(decorator):
1467 """Decorator to give another decorator the @no_type_check effect.
1468
1469 This wraps the decorator with something that wraps the decorated
1470 function in @no_type_check.
1471 """
1472
1473 @functools.wraps(decorator)
1474 def wrapped_decorator(*args, **kwds):
1475 func = decorator(*args, **kwds)
1476 func = no_type_check(func)
1477 return func
1478
1479 return wrapped_decorator
1480
1481
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001482def _overload_dummy(*args, **kwds):
1483 """Helper for @overload to raise when called."""
1484 raise NotImplementedError(
1485 "You should not call an overloaded function. "
1486 "A series of @overload-decorated functions "
1487 "outside a stub module should always be followed "
1488 "by an implementation that is not @overload-ed.")
1489
1490
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001491def overload(func):
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001492 """Decorator for overloaded functions/methods.
1493
1494 In a stub file, place two or more stub definitions for the same
1495 function in a row, each decorated with @overload. For example:
1496
1497 @overload
1498 def utf8(value: None) -> None: ...
1499 @overload
1500 def utf8(value: bytes) -> bytes: ...
1501 @overload
1502 def utf8(value: str) -> bytes: ...
1503
1504 In a non-stub file (i.e. a regular .py file), do the same but
1505 follow it with an implementation. The implementation should *not*
1506 be decorated with @overload. For example:
1507
1508 @overload
1509 def utf8(value: None) -> None: ...
1510 @overload
1511 def utf8(value: bytes) -> bytes: ...
1512 @overload
1513 def utf8(value: str) -> bytes: ...
1514 def utf8(value):
1515 # implementation goes here
1516 """
1517 return _overload_dummy
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001518
1519
Ivan Levkivskyif3672422019-05-26 09:37:07 +01001520def final(f):
1521 """A decorator to indicate final methods and final classes.
1522
1523 Use this decorator to indicate to type checkers that the decorated
1524 method cannot be overridden, and decorated class cannot be subclassed.
1525 For example:
1526
1527 class Base:
1528 @final
1529 def done(self) -> None:
1530 ...
1531 class Sub(Base):
1532 def done(self) -> None: # Error reported by type checker
1533 ...
1534
1535 @final
1536 class Leaf:
1537 ...
1538 class Other(Leaf): # Error reported by type checker
1539 ...
1540
1541 There is no runtime checking of these properties.
1542 """
1543 return f
1544
1545
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001546# Some unconstrained type variables. These are used by the container types.
1547# (These are not for export.)
1548T = TypeVar('T') # Any type.
1549KT = TypeVar('KT') # Key type.
1550VT = TypeVar('VT') # Value type.
1551T_co = TypeVar('T_co', covariant=True) # Any type covariant containers.
1552V_co = TypeVar('V_co', covariant=True) # Any type covariant containers.
1553VT_co = TypeVar('VT_co', covariant=True) # Value type covariant containers.
1554T_contra = TypeVar('T_contra', contravariant=True) # Ditto contravariant.
1555# Internal type variable used for Type[].
1556CT_co = TypeVar('CT_co', covariant=True, bound=type)
1557
1558# A useful type variable with constraints. This represents string types.
1559# (This one *is* for export!)
1560AnyStr = TypeVar('AnyStr', bytes, str)
1561
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001562
1563# Various ABCs mimicking those in collections.abc.
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001564def _alias(origin, params, inst=True):
1565 return _GenericAlias(origin, params, special=True, inst=inst)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001566
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001567Hashable = _alias(collections.abc.Hashable, ()) # Not generic.
1568Awaitable = _alias(collections.abc.Awaitable, T_co)
1569Coroutine = _alias(collections.abc.Coroutine, (T_co, T_contra, V_co))
1570AsyncIterable = _alias(collections.abc.AsyncIterable, T_co)
1571AsyncIterator = _alias(collections.abc.AsyncIterator, T_co)
1572Iterable = _alias(collections.abc.Iterable, T_co)
1573Iterator = _alias(collections.abc.Iterator, T_co)
1574Reversible = _alias(collections.abc.Reversible, T_co)
1575Sized = _alias(collections.abc.Sized, ()) # Not generic.
1576Container = _alias(collections.abc.Container, T_co)
1577Collection = _alias(collections.abc.Collection, T_co)
1578Callable = _VariadicGenericAlias(collections.abc.Callable, (), special=True)
1579Callable.__doc__ = \
1580 """Callable type; Callable[[int], str] is a function of (int) -> str.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001581
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001582 The subscription syntax must always be used with exactly two
1583 values: the argument list and the return type. The argument list
1584 must be a list of types or ellipsis; the return type must be a single type.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001585
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001586 There is no syntax to indicate optional or keyword arguments,
1587 such function types are rarely used as callback types.
1588 """
1589AbstractSet = _alias(collections.abc.Set, T_co)
1590MutableSet = _alias(collections.abc.MutableSet, T)
1591# NOTE: Mapping is only covariant in the value type.
1592Mapping = _alias(collections.abc.Mapping, (KT, VT_co))
1593MutableMapping = _alias(collections.abc.MutableMapping, (KT, VT))
1594Sequence = _alias(collections.abc.Sequence, T_co)
1595MutableSequence = _alias(collections.abc.MutableSequence, T)
1596ByteString = _alias(collections.abc.ByteString, ()) # Not generic
1597Tuple = _VariadicGenericAlias(tuple, (), inst=False, special=True)
1598Tuple.__doc__ = \
1599 """Tuple type; Tuple[X, Y] is the cross-product type of X and Y.
Guido van Rossum62fe1bb2016-10-29 16:05:26 -07001600
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001601 Example: Tuple[T1, T2] is a tuple of two elements corresponding
1602 to type variables T1 and T2. Tuple[int, float, str] is a tuple
1603 of an int, a float and a string.
Guido van Rossum62fe1bb2016-10-29 16:05:26 -07001604
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001605 To specify a variable-length tuple of homogeneous type, use Tuple[T, ...].
1606 """
1607List = _alias(list, T, inst=False)
1608Deque = _alias(collections.deque, T)
1609Set = _alias(set, T, inst=False)
1610FrozenSet = _alias(frozenset, T_co, inst=False)
1611MappingView = _alias(collections.abc.MappingView, T_co)
1612KeysView = _alias(collections.abc.KeysView, KT)
1613ItemsView = _alias(collections.abc.ItemsView, (KT, VT_co))
1614ValuesView = _alias(collections.abc.ValuesView, VT_co)
1615ContextManager = _alias(contextlib.AbstractContextManager, T_co)
1616AsyncContextManager = _alias(contextlib.AbstractAsyncContextManager, T_co)
1617Dict = _alias(dict, (KT, VT), inst=False)
1618DefaultDict = _alias(collections.defaultdict, (KT, VT))
Ismo Toijala68b56d02018-12-02 17:53:14 +02001619OrderedDict = _alias(collections.OrderedDict, (KT, VT))
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001620Counter = _alias(collections.Counter, T)
1621ChainMap = _alias(collections.ChainMap, (KT, VT))
1622Generator = _alias(collections.abc.Generator, (T_co, T_contra, V_co))
1623AsyncGenerator = _alias(collections.abc.AsyncGenerator, (T_co, T_contra))
1624Type = _alias(type, CT_co, inst=False)
1625Type.__doc__ = \
1626 """A special construct usable to annotate class objects.
Guido van Rossum62fe1bb2016-10-29 16:05:26 -07001627
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001628 For example, suppose we have the following classes::
Guido van Rossum62fe1bb2016-10-29 16:05:26 -07001629
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001630 class User: ... # Abstract base for User classes
1631 class BasicUser(User): ...
1632 class ProUser(User): ...
1633 class TeamUser(User): ...
Guido van Rossumf17c2002015-12-03 17:31:24 -08001634
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001635 And a function that takes a class argument that's a subclass of
1636 User and returns an instance of the corresponding class::
Guido van Rossumf17c2002015-12-03 17:31:24 -08001637
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001638 U = TypeVar('U', bound=User)
1639 def new_user(user_class: Type[U]) -> U:
1640 user = user_class()
1641 # (Here we could write the user object to a database)
1642 return user
Guido van Rossumf17c2002015-12-03 17:31:24 -08001643
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001644 joe = new_user(BasicUser)
Guido van Rossumf17c2002015-12-03 17:31:24 -08001645
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001646 At this point the type checker knows that joe has type BasicUser.
1647 """
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001648
1649
Ivan Levkivskyi74d7f762019-05-28 08:40:15 +01001650@runtime_checkable
1651class SupportsInt(Protocol):
Serhiy Storchaka8252c522019-10-08 16:30:17 +03001652 """An ABC with one abstract method __int__."""
Guido van Rossumd70fe632015-08-05 12:11:06 +02001653 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001654
1655 @abstractmethod
1656 def __int__(self) -> int:
1657 pass
1658
1659
Ivan Levkivskyi74d7f762019-05-28 08:40:15 +01001660@runtime_checkable
1661class SupportsFloat(Protocol):
Serhiy Storchaka8252c522019-10-08 16:30:17 +03001662 """An ABC with one abstract method __float__."""
Guido van Rossumd70fe632015-08-05 12:11:06 +02001663 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001664
1665 @abstractmethod
1666 def __float__(self) -> float:
1667 pass
1668
1669
Ivan Levkivskyi74d7f762019-05-28 08:40:15 +01001670@runtime_checkable
1671class SupportsComplex(Protocol):
Serhiy Storchaka8252c522019-10-08 16:30:17 +03001672 """An ABC with one abstract method __complex__."""
Guido van Rossumd70fe632015-08-05 12:11:06 +02001673 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001674
1675 @abstractmethod
1676 def __complex__(self) -> complex:
1677 pass
1678
1679
Ivan Levkivskyi74d7f762019-05-28 08:40:15 +01001680@runtime_checkable
1681class SupportsBytes(Protocol):
Serhiy Storchaka8252c522019-10-08 16:30:17 +03001682 """An ABC with one abstract method __bytes__."""
Guido van Rossumd70fe632015-08-05 12:11:06 +02001683 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001684
1685 @abstractmethod
1686 def __bytes__(self) -> bytes:
1687 pass
1688
1689
Ivan Levkivskyi74d7f762019-05-28 08:40:15 +01001690@runtime_checkable
1691class SupportsIndex(Protocol):
Serhiy Storchaka8252c522019-10-08 16:30:17 +03001692 """An ABC with one abstract method __index__."""
Paul Dagnelie4c7a46e2019-05-22 07:23:01 -07001693 __slots__ = ()
1694
1695 @abstractmethod
1696 def __index__(self) -> int:
1697 pass
1698
1699
Ivan Levkivskyi74d7f762019-05-28 08:40:15 +01001700@runtime_checkable
1701class SupportsAbs(Protocol[T_co]):
Serhiy Storchaka8252c522019-10-08 16:30:17 +03001702 """An ABC with one abstract method __abs__ that is covariant in its return type."""
Guido van Rossumd70fe632015-08-05 12:11:06 +02001703 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001704
1705 @abstractmethod
Guido van Rossumd70fe632015-08-05 12:11:06 +02001706 def __abs__(self) -> T_co:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001707 pass
1708
1709
Ivan Levkivskyi74d7f762019-05-28 08:40:15 +01001710@runtime_checkable
1711class SupportsRound(Protocol[T_co]):
Serhiy Storchaka8252c522019-10-08 16:30:17 +03001712 """An ABC with one abstract method __round__ that is covariant in its return type."""
Guido van Rossumd70fe632015-08-05 12:11:06 +02001713 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001714
1715 @abstractmethod
Guido van Rossumd70fe632015-08-05 12:11:06 +02001716 def __round__(self, ndigits: int = 0) -> T_co:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001717 pass
1718
1719
Serhiy Storchakaa2ec0692020-04-08 10:59:04 +03001720def _make_nmtuple(name, types, module, defaults = ()):
1721 fields = [n for n, t in types]
1722 types = {n: _type_check(t, f"field {n} annotation must be a type")
1723 for n, t in types}
1724 nm_tpl = collections.namedtuple(name, fields,
1725 defaults=defaults, module=module)
1726 nm_tpl.__annotations__ = nm_tpl.__new__.__annotations__ = types
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001727 return nm_tpl
1728
1729
Ivan Levkivskyib692dc82017-02-13 22:50:14 +01001730# attributes prohibited to set in NamedTuple class syntax
Serhiy Storchakaa2ec0692020-04-08 10:59:04 +03001731_prohibited = frozenset({'__new__', '__init__', '__slots__', '__getnewargs__',
1732 '_fields', '_field_defaults',
1733 '_make', '_replace', '_asdict', '_source'})
Ivan Levkivskyib692dc82017-02-13 22:50:14 +01001734
Serhiy Storchakaa2ec0692020-04-08 10:59:04 +03001735_special = frozenset({'__module__', '__name__', '__annotations__'})
Ivan Levkivskyib692dc82017-02-13 22:50:14 +01001736
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001737
Guido van Rossum2f841442016-11-15 09:48:06 -08001738class NamedTupleMeta(type):
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001739
Guido van Rossum2f841442016-11-15 09:48:06 -08001740 def __new__(cls, typename, bases, ns):
Serhiy Storchakaa2ec0692020-04-08 10:59:04 +03001741 assert bases[0] is _NamedTuple
Guido van Rossum2f841442016-11-15 09:48:06 -08001742 types = ns.get('__annotations__', {})
Serhiy Storchakaa2ec0692020-04-08 10:59:04 +03001743 default_names = []
Guido van Rossum3c268be2017-01-18 08:03:50 -08001744 for field_name in types:
1745 if field_name in ns:
Serhiy Storchakaa2ec0692020-04-08 10:59:04 +03001746 default_names.append(field_name)
1747 elif default_names:
1748 raise TypeError(f"Non-default namedtuple field {field_name} "
1749 f"cannot follow default field"
1750 f"{'s' if len(default_names) > 1 else ''} "
1751 f"{', '.join(default_names)}")
1752 nm_tpl = _make_nmtuple(typename, types.items(),
1753 defaults=[ns[n] for n in default_names],
1754 module=ns['__module__'])
Guido van Rossum95919c02017-01-22 17:47:20 -08001755 # update from user namespace without overriding special namedtuple attributes
1756 for key in ns:
Ivan Levkivskyib692dc82017-02-13 22:50:14 +01001757 if key in _prohibited:
1758 raise AttributeError("Cannot overwrite NamedTuple attribute " + key)
1759 elif key not in _special and key not in nm_tpl._fields:
Guido van Rossum95919c02017-01-22 17:47:20 -08001760 setattr(nm_tpl, key, ns[key])
Guido van Rossum3c268be2017-01-18 08:03:50 -08001761 return nm_tpl
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001762
Guido van Rossumd7adfe12017-01-22 17:43:53 -08001763
Serhiy Storchakaa2ec0692020-04-08 10:59:04 +03001764def NamedTuple(typename, fields=None, /, **kwargs):
Guido van Rossum2f841442016-11-15 09:48:06 -08001765 """Typed version of namedtuple.
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001766
Guido van Rossum2f841442016-11-15 09:48:06 -08001767 Usage in Python versions >= 3.6::
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001768
Guido van Rossum2f841442016-11-15 09:48:06 -08001769 class Employee(NamedTuple):
1770 name: str
1771 id: int
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001772
Guido van Rossum2f841442016-11-15 09:48:06 -08001773 This is equivalent to::
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001774
Guido van Rossum2f841442016-11-15 09:48:06 -08001775 Employee = collections.namedtuple('Employee', ['name', 'id'])
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001776
Raymond Hettingerf7b57df2019-03-18 09:53:56 -07001777 The resulting class has an extra __annotations__ attribute, giving a
1778 dict that maps field names to types. (The field names are also in
1779 the _fields attribute, which is part of the namedtuple API.)
1780 Alternative equivalent keyword syntax is also accepted::
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001781
Guido van Rossum2f841442016-11-15 09:48:06 -08001782 Employee = NamedTuple('Employee', name=str, id=int)
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001783
Guido van Rossum2f841442016-11-15 09:48:06 -08001784 In Python versions <= 3.5 use::
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001785
Guido van Rossum2f841442016-11-15 09:48:06 -08001786 Employee = NamedTuple('Employee', [('name', str), ('id', int)])
1787 """
Serhiy Storchakaa2ec0692020-04-08 10:59:04 +03001788 if fields is None:
1789 fields = kwargs.items()
1790 elif kwargs:
1791 raise TypeError("Either list of fields or keywords"
1792 " can be provided to NamedTuple, not both")
1793 try:
1794 module = sys._getframe(1).f_globals.get('__name__', '__main__')
1795 except (AttributeError, ValueError):
1796 module = None
1797 return _make_nmtuple(typename, fields, module=module)
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001798
Serhiy Storchakaa2ec0692020-04-08 10:59:04 +03001799_NamedTuple = type.__new__(NamedTupleMeta, 'NamedTuple', (), {})
1800
1801def _namedtuple_mro_entries(bases):
1802 if len(bases) > 1:
1803 raise TypeError("Multiple inheritance with NamedTuple is not supported")
1804 assert bases[0] is NamedTuple
1805 return (_NamedTuple,)
1806
1807NamedTuple.__mro_entries__ = _namedtuple_mro_entries
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001808
1809
Ivan Levkivskyi135c6a52019-05-26 09:39:24 +01001810class _TypedDictMeta(type):
1811 def __new__(cls, name, bases, ns, total=True):
1812 """Create new typed dict class object.
1813
Serhiy Storchakaf228bf22020-04-08 11:03:27 +03001814 This method is called when TypedDict is subclassed,
1815 or when TypedDict is instantiated. This way
Ivan Levkivskyi135c6a52019-05-26 09:39:24 +01001816 TypedDict supports all three syntax forms described in its docstring.
Serhiy Storchakaf228bf22020-04-08 11:03:27 +03001817 Subclasses and instances of TypedDict return actual dictionaries.
Ivan Levkivskyi135c6a52019-05-26 09:39:24 +01001818 """
Serhiy Storchakaf228bf22020-04-08 11:03:27 +03001819 for base in bases:
1820 if type(base) is not _TypedDictMeta:
1821 raise TypeError('cannot inherit from both a TypedDict type '
1822 'and a non-TypedDict base class')
1823 tp_dict = type.__new__(_TypedDictMeta, name, (dict,), ns)
Ivan Levkivskyi135c6a52019-05-26 09:39:24 +01001824
Vlad Emelianov10e87e52020-02-13 20:53:29 +01001825 annotations = {}
1826 own_annotations = ns.get('__annotations__', {})
1827 own_annotation_keys = set(own_annotations.keys())
Ivan Levkivskyi135c6a52019-05-26 09:39:24 +01001828 msg = "TypedDict('Name', {f0: t0, f1: t1, ...}); each t must be a type"
Vlad Emelianov10e87e52020-02-13 20:53:29 +01001829 own_annotations = {
1830 n: _type_check(tp, msg) for n, tp in own_annotations.items()
1831 }
1832 required_keys = set()
1833 optional_keys = set()
Zac Hatfield-Dodds665ad3d2019-11-24 21:48:48 +11001834
Ivan Levkivskyi135c6a52019-05-26 09:39:24 +01001835 for base in bases:
Vlad Emelianov10e87e52020-02-13 20:53:29 +01001836 annotations.update(base.__dict__.get('__annotations__', {}))
1837 required_keys.update(base.__dict__.get('__required_keys__', ()))
1838 optional_keys.update(base.__dict__.get('__optional_keys__', ()))
Zac Hatfield-Dodds665ad3d2019-11-24 21:48:48 +11001839
Vlad Emelianov10e87e52020-02-13 20:53:29 +01001840 annotations.update(own_annotations)
1841 if total:
1842 required_keys.update(own_annotation_keys)
1843 else:
1844 optional_keys.update(own_annotation_keys)
1845
1846 tp_dict.__annotations__ = annotations
1847 tp_dict.__required_keys__ = frozenset(required_keys)
1848 tp_dict.__optional_keys__ = frozenset(optional_keys)
Ivan Levkivskyi135c6a52019-05-26 09:39:24 +01001849 if not hasattr(tp_dict, '__total__'):
1850 tp_dict.__total__ = total
1851 return tp_dict
1852
Serhiy Storchakaf228bf22020-04-08 11:03:27 +03001853 __call__ = dict # static method
1854
1855 def __subclasscheck__(cls, other):
1856 # Typed dicts are only for static structural subtyping.
1857 raise TypeError('TypedDict does not support instance and class checks')
1858
1859 __instancecheck__ = __subclasscheck__
Ivan Levkivskyi135c6a52019-05-26 09:39:24 +01001860
1861
Serhiy Storchakaf228bf22020-04-08 11:03:27 +03001862def TypedDict(typename, fields=None, /, *, total=True, **kwargs):
Ivan Levkivskyi135c6a52019-05-26 09:39:24 +01001863 """A simple typed namespace. At runtime it is equivalent to a plain dict.
1864
1865 TypedDict creates a dictionary type that expects all of its
1866 instances to have a certain set of keys, where each key is
1867 associated with a value of a consistent type. This expectation
1868 is not checked at runtime but is only enforced by type checkers.
1869 Usage::
1870
1871 class Point2D(TypedDict):
1872 x: int
1873 y: int
1874 label: str
1875
1876 a: Point2D = {'x': 1, 'y': 2, 'label': 'good'} # OK
1877 b: Point2D = {'z': 3, 'label': 'bad'} # Fails type check
1878
1879 assert Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first')
1880
Zac Hatfield-Dodds665ad3d2019-11-24 21:48:48 +11001881 The type info can be accessed via the Point2D.__annotations__ dict, and
1882 the Point2D.__required_keys__ and Point2D.__optional_keys__ frozensets.
1883 TypedDict supports two additional equivalent forms::
Ivan Levkivskyi135c6a52019-05-26 09:39:24 +01001884
1885 Point2D = TypedDict('Point2D', x=int, y=int, label=str)
1886 Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str})
1887
ananthan-123ab6423f2020-02-19 10:03:05 +05301888 By default, all keys must be present in a TypedDict. It is possible
1889 to override this by specifying totality.
1890 Usage::
1891
1892 class point2D(TypedDict, total=False):
1893 x: int
1894 y: int
1895
1896 This means that a point2D TypedDict can have any of the keys omitted.A type
1897 checker is only expected to support a literal False or True as the value of
1898 the total argument. True is the default, and makes all items defined in the
1899 class body be required.
1900
Ivan Levkivskyi135c6a52019-05-26 09:39:24 +01001901 The class syntax is only supported in Python 3.6+, while two other
1902 syntax forms work for Python 2.7 and 3.2+
1903 """
Serhiy Storchakaf228bf22020-04-08 11:03:27 +03001904 if fields is None:
1905 fields = kwargs
1906 elif kwargs:
1907 raise TypeError("TypedDict takes either a dict or keyword arguments,"
1908 " but not both")
1909
1910 ns = {'__annotations__': dict(fields), '__total__': total}
1911 try:
1912 # Setting correct module is necessary to make typed dict classes pickleable.
1913 ns['__module__'] = sys._getframe(1).f_globals.get('__name__', '__main__')
1914 except (AttributeError, ValueError):
1915 pass
1916
1917 return _TypedDictMeta(typename, (), ns)
1918
1919_TypedDict = type.__new__(_TypedDictMeta, 'TypedDict', (), {})
1920TypedDict.__mro_entries__ = lambda bases: (_TypedDict,)
Ivan Levkivskyi135c6a52019-05-26 09:39:24 +01001921
1922
Guido van Rossum91185fe2016-06-08 11:19:11 -07001923def NewType(name, tp):
1924 """NewType creates simple unique types with almost zero
1925 runtime overhead. NewType(name, tp) is considered a subtype of tp
1926 by static type checkers. At runtime, NewType(name, tp) returns
1927 a dummy function that simply returns its argument. Usage::
1928
1929 UserId = NewType('UserId', int)
1930
1931 def name_by_id(user_id: UserId) -> str:
1932 ...
1933
1934 UserId('user') # Fails type check
1935
1936 name_by_id(42) # Fails type check
1937 name_by_id(UserId(42)) # OK
1938
1939 num = UserId(5) + 1 # type: int
1940 """
1941
1942 def new_type(x):
1943 return x
1944
1945 new_type.__name__ = name
1946 new_type.__supertype__ = tp
1947 return new_type
1948
1949
Guido van Rossum0e0563c2016-04-05 14:54:25 -07001950# Python-version-specific alias (Python 2: unicode; Python 3: str)
1951Text = str
1952
1953
Guido van Rossum91185fe2016-06-08 11:19:11 -07001954# Constant that's True when type checking, but False here.
1955TYPE_CHECKING = False
1956
1957
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001958class IO(Generic[AnyStr]):
1959 """Generic base class for TextIO and BinaryIO.
1960
1961 This is an abstract, generic version of the return of open().
1962
1963 NOTE: This does not distinguish between the different possible
1964 classes (text vs. binary, read vs. write vs. read/write,
1965 append-only, unbuffered). The TextIO and BinaryIO subclasses
1966 below capture the distinctions between text vs. binary, which is
1967 pervasive in the interface; however we currently do not offer a
1968 way to track the other distinctions in the type system.
1969 """
1970
Guido van Rossumd70fe632015-08-05 12:11:06 +02001971 __slots__ = ()
1972
HongWeipeng6ce03ec2019-09-27 15:54:26 +08001973 @property
1974 @abstractmethod
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001975 def mode(self) -> str:
1976 pass
1977
HongWeipeng6ce03ec2019-09-27 15:54:26 +08001978 @property
1979 @abstractmethod
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001980 def name(self) -> str:
1981 pass
1982
1983 @abstractmethod
1984 def close(self) -> None:
1985 pass
1986
Shantanu2e6569b2020-01-29 18:52:36 -08001987 @property
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001988 @abstractmethod
1989 def closed(self) -> bool:
1990 pass
1991
1992 @abstractmethod
1993 def fileno(self) -> int:
1994 pass
1995
1996 @abstractmethod
1997 def flush(self) -> None:
1998 pass
1999
2000 @abstractmethod
2001 def isatty(self) -> bool:
2002 pass
2003
2004 @abstractmethod
2005 def read(self, n: int = -1) -> AnyStr:
2006 pass
2007
2008 @abstractmethod
2009 def readable(self) -> bool:
2010 pass
2011
2012 @abstractmethod
2013 def readline(self, limit: int = -1) -> AnyStr:
2014 pass
2015
2016 @abstractmethod
2017 def readlines(self, hint: int = -1) -> List[AnyStr]:
2018 pass
2019
2020 @abstractmethod
2021 def seek(self, offset: int, whence: int = 0) -> int:
2022 pass
2023
2024 @abstractmethod
2025 def seekable(self) -> bool:
2026 pass
2027
2028 @abstractmethod
2029 def tell(self) -> int:
2030 pass
2031
2032 @abstractmethod
2033 def truncate(self, size: int = None) -> int:
2034 pass
2035
2036 @abstractmethod
2037 def writable(self) -> bool:
2038 pass
2039
2040 @abstractmethod
2041 def write(self, s: AnyStr) -> int:
2042 pass
2043
2044 @abstractmethod
2045 def writelines(self, lines: List[AnyStr]) -> None:
2046 pass
2047
2048 @abstractmethod
2049 def __enter__(self) -> 'IO[AnyStr]':
2050 pass
2051
2052 @abstractmethod
2053 def __exit__(self, type, value, traceback) -> None:
2054 pass
2055
2056
2057class BinaryIO(IO[bytes]):
2058 """Typed version of the return of open() in binary mode."""
2059
Guido van Rossumd70fe632015-08-05 12:11:06 +02002060 __slots__ = ()
2061
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07002062 @abstractmethod
2063 def write(self, s: Union[bytes, bytearray]) -> int:
2064 pass
2065
2066 @abstractmethod
2067 def __enter__(self) -> 'BinaryIO':
2068 pass
2069
2070
2071class TextIO(IO[str]):
2072 """Typed version of the return of open() in text mode."""
2073
Guido van Rossumd70fe632015-08-05 12:11:06 +02002074 __slots__ = ()
2075
HongWeipeng6ce03ec2019-09-27 15:54:26 +08002076 @property
2077 @abstractmethod
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07002078 def buffer(self) -> BinaryIO:
2079 pass
2080
HongWeipeng6ce03ec2019-09-27 15:54:26 +08002081 @property
2082 @abstractmethod
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07002083 def encoding(self) -> str:
2084 pass
2085
HongWeipeng6ce03ec2019-09-27 15:54:26 +08002086 @property
2087 @abstractmethod
Guido van Rossum991d14f2016-11-09 13:12:51 -08002088 def errors(self) -> Optional[str]:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07002089 pass
2090
HongWeipeng6ce03ec2019-09-27 15:54:26 +08002091 @property
2092 @abstractmethod
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07002093 def line_buffering(self) -> bool:
2094 pass
2095
HongWeipeng6ce03ec2019-09-27 15:54:26 +08002096 @property
2097 @abstractmethod
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07002098 def newlines(self) -> Any:
2099 pass
2100
2101 @abstractmethod
2102 def __enter__(self) -> 'TextIO':
2103 pass
2104
2105
2106class io:
2107 """Wrapper namespace for IO generic classes."""
2108
2109 __all__ = ['IO', 'TextIO', 'BinaryIO']
2110 IO = IO
2111 TextIO = TextIO
2112 BinaryIO = BinaryIO
2113
Guido van Rossumd7adfe12017-01-22 17:43:53 -08002114
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07002115io.__name__ = __name__ + '.io'
2116sys.modules[io.__name__] = io
2117
Ivan Levkivskyid911e402018-01-20 11:23:59 +00002118Pattern = _alias(stdlib_re.Pattern, AnyStr)
2119Match = _alias(stdlib_re.Match, AnyStr)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07002120
2121class re:
2122 """Wrapper namespace for re type aliases."""
2123
2124 __all__ = ['Pattern', 'Match']
2125 Pattern = Pattern
2126 Match = Match
2127
Guido van Rossumd7adfe12017-01-22 17:43:53 -08002128
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07002129re.__name__ = __name__ + '.re'
2130sys.modules[re.__name__] = re