blob: df3650001e78ed694d7028aeba2ed3c2911d9388 [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")
Noah Wood5eea0ad2018-10-08 14:50:16 -0400144 if (isinstance(arg, _SpecialForm) and arg not in (Any, NoReturn) or
Ivan Levkivskyi74d7f762019-05-28 08:40:15 +0100145 arg in (Generic, Protocol)):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000146 raise TypeError(f"Plain {arg} is not valid as type argument")
147 if isinstance(arg, (type, TypeVar, ForwardRef)):
148 return arg
149 if not callable(arg):
150 raise TypeError(f"{msg} Got {arg!r:.100}.")
151 return arg
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700152
153
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000154def _type_repr(obj):
155 """Return the repr() of an object, special-casing types (internal helper).
156
157 If obj is a type, we return a shorter version than the default
158 type.__repr__, based on the module and qualified name, which is
159 typically enough to uniquely identify a type. For everything
160 else, we fall back on repr(obj).
161 """
162 if isinstance(obj, type):
163 if obj.__module__ == 'builtins':
164 return obj.__qualname__
165 return f'{obj.__module__}.{obj.__qualname__}'
166 if obj is ...:
167 return('...')
168 if isinstance(obj, types.FunctionType):
169 return obj.__name__
170 return repr(obj)
171
172
173def _collect_type_vars(types):
174 """Collect all type variable contained in types in order of
175 first appearance (lexicographic order). For example::
176
177 _collect_type_vars((T, List[S, T])) == (T, S)
178 """
179 tvars = []
180 for t in types:
181 if isinstance(t, TypeVar) and t not in tvars:
182 tvars.append(t)
Guido van Rossum48b069a2020-04-07 09:50:06 -0700183 if ((isinstance(t, _GenericAlias) and not t._special)
184 or isinstance(t, GenericAlias)):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000185 tvars.extend([t for t in t.__parameters__ if t not in tvars])
186 return tuple(tvars)
187
188
189def _subs_tvars(tp, tvars, subs):
190 """Substitute type variables 'tvars' with substitutions 'subs'.
191 These two must have the same length.
192 """
193 if not isinstance(tp, _GenericAlias):
194 return tp
195 new_args = list(tp.__args__)
196 for a, arg in enumerate(tp.__args__):
197 if isinstance(arg, TypeVar):
198 for i, tvar in enumerate(tvars):
199 if arg == tvar:
200 new_args[a] = subs[i]
201 else:
202 new_args[a] = _subs_tvars(arg, tvars, subs)
203 if tp.__origin__ is Union:
204 return Union[tuple(new_args)]
205 return tp.copy_with(tuple(new_args))
206
207
208def _check_generic(cls, parameters):
209 """Check correct count for parameters of a generic cls (internal helper).
210 This gives a nice error message in case of count mismatch.
211 """
212 if not cls.__parameters__:
213 raise TypeError(f"{cls} is not a generic class")
214 alen = len(parameters)
215 elen = len(cls.__parameters__)
216 if alen != elen:
217 raise TypeError(f"Too {'many' if alen > elen else 'few'} parameters for {cls};"
218 f" actual {alen}, expected {elen}")
219
220
221def _remove_dups_flatten(parameters):
Ivan Levkivskyif65e31f2018-05-18 16:00:38 -0700222 """An internal helper for Union creation and substitution: flatten Unions
223 among parameters, then remove duplicates.
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000224 """
225 # Flatten out Union[Union[...], ...].
226 params = []
227 for p in parameters:
228 if isinstance(p, _GenericAlias) and p.__origin__ is Union:
229 params.extend(p.__args__)
230 elif isinstance(p, tuple) and len(p) > 0 and p[0] is Union:
231 params.extend(p[1:])
232 else:
233 params.append(p)
234 # Weed out strict duplicates, preserving the first of each occurrence.
235 all_params = set(params)
236 if len(all_params) < len(params):
237 new_params = []
238 for t in params:
239 if t in all_params:
240 new_params.append(t)
241 all_params.remove(t)
242 params = new_params
243 assert not all_params, all_params
Ivan Levkivskyif65e31f2018-05-18 16:00:38 -0700244 return tuple(params)
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000245
246
247_cleanups = []
248
249
250def _tp_cache(func):
251 """Internal wrapper caching __getitem__ of generic types with a fallback to
252 original function for non-hashable arguments.
253 """
254 cached = functools.lru_cache()(func)
255 _cleanups.append(cached.cache_clear)
256
257 @functools.wraps(func)
258 def inner(*args, **kwds):
259 try:
260 return cached(*args, **kwds)
261 except TypeError:
262 pass # All real errors (not unhashable args) are raised below.
263 return func(*args, **kwds)
264 return inner
265
266
267def _eval_type(t, globalns, localns):
268 """Evaluate all forward reverences in the given type t.
269 For use of globalns and localns see the docstring for get_type_hints().
270 """
271 if isinstance(t, ForwardRef):
272 return t._evaluate(globalns, localns)
273 if isinstance(t, _GenericAlias):
274 ev_args = tuple(_eval_type(a, globalns, localns) for a in t.__args__)
275 if ev_args == t.__args__:
276 return t
277 res = t.copy_with(ev_args)
278 res._special = t._special
279 return res
280 return t
281
282
283class _Final:
284 """Mixin to prohibit subclassing"""
Guido van Rossum4cefe742016-09-27 15:20:12 -0700285
Guido van Rossum83ec3022017-01-17 20:43:28 -0800286 __slots__ = ('__weakref__',)
Guido van Rossum4cefe742016-09-27 15:20:12 -0700287
Serhiy Storchaka2085bd02019-06-01 11:00:15 +0300288 def __init_subclass__(self, /, *args, **kwds):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000289 if '_root' not in kwds:
290 raise TypeError("Cannot subclass special typing classes")
291
Ivan Levkivskyi83494032018-03-26 23:01:12 +0100292class _Immutable:
293 """Mixin to indicate that object should not be copied."""
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000294
Ivan Levkivskyi83494032018-03-26 23:01:12 +0100295 def __copy__(self):
296 return self
297
298 def __deepcopy__(self, memo):
299 return self
300
301
302class _SpecialForm(_Final, _Immutable, _root=True):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000303 """Internal indicator of special typing constructs.
304 See _doc instance attribute for specific docs.
305 """
306
307 __slots__ = ('_name', '_doc')
308
Guido van Rossum4cefe742016-09-27 15:20:12 -0700309 def __new__(cls, *args, **kwds):
310 """Constructor.
311
312 This only exists to give a better error message in case
313 someone tries to subclass a special typing object (not a good idea).
314 """
315 if (len(args) == 3 and
316 isinstance(args[0], str) and
317 isinstance(args[1], tuple)):
318 # Close enough.
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000319 raise TypeError(f"Cannot subclass {cls!r}")
Guido van Rossumb47c9d22016-10-03 08:40:50 -0700320 return super().__new__(cls)
Guido van Rossum4cefe742016-09-27 15:20:12 -0700321
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000322 def __init__(self, name, doc):
323 self._name = name
324 self._doc = doc
Guido van Rossum4cefe742016-09-27 15:20:12 -0700325
Serhiy Storchaka7e644142020-04-18 17:13:21 +0300326 @property
327 def __doc__(self):
328 return self._doc
329
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000330 def __eq__(self, other):
331 if not isinstance(other, _SpecialForm):
332 return NotImplemented
333 return self._name == other._name
334
335 def __hash__(self):
336 return hash((self._name,))
Guido van Rossum4cefe742016-09-27 15:20:12 -0700337
338 def __repr__(self):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000339 return 'typing.' + self._name
340
Ivan Levkivskyi83494032018-03-26 23:01:12 +0100341 def __reduce__(self):
342 return self._name
Guido van Rossum4cefe742016-09-27 15:20:12 -0700343
344 def __call__(self, *args, **kwds):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000345 raise TypeError(f"Cannot instantiate {self!r}")
346
347 def __instancecheck__(self, obj):
348 raise TypeError(f"{self} cannot be used with isinstance()")
349
350 def __subclasscheck__(self, cls):
351 raise TypeError(f"{self} cannot be used with issubclass()")
352
353 @_tp_cache
354 def __getitem__(self, parameters):
Ivan Levkivskyif3672422019-05-26 09:37:07 +0100355 if self._name in ('ClassVar', 'Final'):
356 item = _type_check(parameters, f'{self._name} accepts only single type.')
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000357 return _GenericAlias(self, (item,))
358 if self._name == 'Union':
359 if parameters == ():
360 raise TypeError("Cannot take a Union of no types.")
361 if not isinstance(parameters, tuple):
362 parameters = (parameters,)
363 msg = "Union[arg, ...]: each arg must be a type."
364 parameters = tuple(_type_check(p, msg) for p in parameters)
365 parameters = _remove_dups_flatten(parameters)
366 if len(parameters) == 1:
367 return parameters[0]
368 return _GenericAlias(self, parameters)
369 if self._name == 'Optional':
370 arg = _type_check(parameters, "Optional[t] requires a single type.")
371 return Union[arg, type(None)]
Ivan Levkivskyib891c462019-05-26 09:37:48 +0100372 if self._name == 'Literal':
373 # There is no '_type_check' call because arguments to Literal[...] are
374 # values, not types.
375 return _GenericAlias(self, parameters)
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000376 raise TypeError(f"{self} is not subscriptable")
Guido van Rossum4cefe742016-09-27 15:20:12 -0700377
378
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000379Any = _SpecialForm('Any', doc=
380 """Special type indicating an unconstrained type.
Guido van Rossumb47c9d22016-10-03 08:40:50 -0700381
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000382 - Any is compatible with every type.
383 - Any assumed to have all methods.
384 - All values assumed to be instances of Any.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700385
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000386 Note that all the above statements are true from the point of view of
387 static type checkers. At runtime, Any should not be used with instance
388 or class checks.
389 """)
Guido van Rossumd70fe632015-08-05 12:11:06 +0200390
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000391NoReturn = _SpecialForm('NoReturn', doc=
392 """Special type indicating functions that never return.
393 Example::
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700394
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000395 from typing import NoReturn
396
397 def stop() -> NoReturn:
398 raise Exception('no way')
399
400 This type is invalid in other positions, e.g., ``List[NoReturn]``
401 will fail in static type checkers.
402 """)
403
404ClassVar = _SpecialForm('ClassVar', doc=
405 """Special type construct to mark class variables.
406
407 An annotation wrapped in ClassVar indicates that a given
408 attribute is intended to be used as a class variable and
409 should not be set on instances of that class. Usage::
410
411 class Starship:
412 stats: ClassVar[Dict[str, int]] = {} # class variable
413 damage: int = 10 # instance variable
414
415 ClassVar accepts only types and cannot be further subscribed.
416
417 Note that ClassVar is not a class itself, and should not
418 be used with isinstance() or issubclass().
419 """)
420
Ivan Levkivskyif3672422019-05-26 09:37:07 +0100421Final = _SpecialForm('Final', doc=
422 """Special typing construct to indicate final names to type checkers.
423
424 A final name cannot be re-assigned or overridden in a subclass.
425 For example:
426
427 MAX_SIZE: Final = 9000
428 MAX_SIZE += 1 # Error reported by type checker
429
430 class Connection:
431 TIMEOUT: Final[int] = 10
432
433 class FastConnector(Connection):
434 TIMEOUT = 1 # Error reported by type checker
435
436 There is no runtime checking of these properties.
437 """)
438
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000439Union = _SpecialForm('Union', doc=
440 """Union type; Union[X, Y] means either X or Y.
441
442 To define a union, use e.g. Union[int, str]. Details:
443 - The arguments must be types and there must be at least one.
444 - None as an argument is a special case and is replaced by
445 type(None).
446 - Unions of unions are flattened, e.g.::
447
448 Union[Union[int, str], float] == Union[int, str, float]
449
450 - Unions of a single argument vanish, e.g.::
451
452 Union[int] == int # The constructor actually returns int
453
454 - Redundant arguments are skipped, e.g.::
455
456 Union[int, str, int] == Union[int, str]
457
458 - When comparing unions, the argument order is ignored, e.g.::
459
460 Union[int, str] == Union[str, int]
461
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000462 - You cannot subclass or instantiate a union.
463 - You can use Optional[X] as a shorthand for Union[X, None].
464 """)
465
466Optional = _SpecialForm('Optional', doc=
467 """Optional type.
468
469 Optional[X] is equivalent to Union[X, None].
470 """)
Guido van Rossumb7dedc82016-10-29 12:44:29 -0700471
Ivan Levkivskyib891c462019-05-26 09:37:48 +0100472Literal = _SpecialForm('Literal', doc=
473 """Special typing form to define literal types (a.k.a. value types).
474
475 This form can be used to indicate to type checkers that the corresponding
476 variable or function parameter has a value equivalent to the provided
477 literal (or one of several literals):
478
479 def validate_simple(data: Any) -> Literal[True]: # always returns True
480 ...
481
482 MODE = Literal['r', 'rb', 'w', 'wb']
483 def open_helper(file: str, mode: MODE) -> str:
484 ...
485
486 open_helper('/some/path', 'r') # Passes type check
487 open_helper('/other/path', 'typo') # Error in type checker
488
489 Literal[...] cannot be subclassed. At runtime, an arbitrary value
490 is allowed as type argument to Literal[...], but type checkers may
491 impose restrictions.
492 """)
493
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700494
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000495class ForwardRef(_Final, _root=True):
Guido van Rossumb24569a2016-11-20 18:01:29 -0800496 """Internal wrapper to hold a forward reference."""
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700497
Guido van Rossum4cefe742016-09-27 15:20:12 -0700498 __slots__ = ('__forward_arg__', '__forward_code__',
Nina Zakharenko2d2d3b12018-05-16 12:27:03 -0400499 '__forward_evaluated__', '__forward_value__',
500 '__forward_is_argument__')
Guido van Rossum4cefe742016-09-27 15:20:12 -0700501
Nina Zakharenko0e61dff2018-05-22 20:32:10 -0700502 def __init__(self, arg, is_argument=True):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700503 if not isinstance(arg, str):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000504 raise TypeError(f"Forward reference must be a string -- got {arg!r}")
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700505 try:
506 code = compile(arg, '<string>', 'eval')
507 except SyntaxError:
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000508 raise SyntaxError(f"Forward reference must be an expression -- got {arg!r}")
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700509 self.__forward_arg__ = arg
510 self.__forward_code__ = code
511 self.__forward_evaluated__ = False
512 self.__forward_value__ = None
Nina Zakharenko2d2d3b12018-05-16 12:27:03 -0400513 self.__forward_is_argument__ = is_argument
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700514
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000515 def _evaluate(self, globalns, localns):
Guido van Rossumdad17902016-11-10 08:29:18 -0800516 if not self.__forward_evaluated__ or localns is not globalns:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700517 if globalns is None and localns is None:
518 globalns = localns = {}
519 elif globalns is None:
520 globalns = localns
521 elif localns is None:
522 localns = globalns
523 self.__forward_value__ = _type_check(
524 eval(self.__forward_code__, globalns, localns),
Nina Zakharenko2d2d3b12018-05-16 12:27:03 -0400525 "Forward references must evaluate to types.",
526 is_argument=self.__forward_is_argument__)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700527 self.__forward_evaluated__ = True
528 return self.__forward_value__
529
Guido van Rossum4cefe742016-09-27 15:20:12 -0700530 def __eq__(self, other):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000531 if not isinstance(other, ForwardRef):
Guido van Rossum4cefe742016-09-27 15:20:12 -0700532 return NotImplemented
plokmijnuhbye082e7c2019-09-13 20:40:54 +0100533 if self.__forward_evaluated__ and other.__forward_evaluated__:
534 return (self.__forward_arg__ == other.__forward_arg__ and
535 self.__forward_value__ == other.__forward_value__)
536 return self.__forward_arg__ == other.__forward_arg__
Guido van Rossum4cefe742016-09-27 15:20:12 -0700537
538 def __hash__(self):
plokmijnuhbye082e7c2019-09-13 20:40:54 +0100539 return hash(self.__forward_arg__)
Guido van Rossum4cefe742016-09-27 15:20:12 -0700540
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700541 def __repr__(self):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000542 return f'ForwardRef({self.__forward_arg__!r})'
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700543
544
Ivan Levkivskyi83494032018-03-26 23:01:12 +0100545class TypeVar(_Final, _Immutable, _root=True):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700546 """Type variable.
547
548 Usage::
549
550 T = TypeVar('T') # Can be anything
551 A = TypeVar('A', str, bytes) # Must be str or bytes
552
553 Type variables exist primarily for the benefit of static type
554 checkers. They serve as the parameters for generic types as well
555 as for generic function definitions. See class Generic for more
556 information on generic types. Generic functions work as follows:
557
Guido van Rossumb24569a2016-11-20 18:01:29 -0800558 def repeat(x: T, n: int) -> List[T]:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700559 '''Return a list containing n references to x.'''
560 return [x]*n
561
562 def longest(x: A, y: A) -> A:
563 '''Return the longest of two strings.'''
564 return x if len(x) >= len(y) else y
565
566 The latter example's signature is essentially the overloading
567 of (str, str) -> str and (bytes, bytes) -> bytes. Also note
568 that if the arguments are instances of some subclass of str,
569 the return type is still plain str.
570
Guido van Rossumb24569a2016-11-20 18:01:29 -0800571 At runtime, isinstance(x, T) and issubclass(C, T) will raise TypeError.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700572
Guido van Rossumefa798d2016-08-23 11:01:50 -0700573 Type variables defined with covariant=True or contravariant=True
João D. Ferreira86bfed32018-07-07 16:41:20 +0100574 can be used to declare covariant or contravariant generic types.
Guido van Rossumefa798d2016-08-23 11:01:50 -0700575 See PEP 484 for more details. By default generic types are invariant
576 in all type variables.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700577
578 Type variables can be introspected. e.g.:
579
580 T.__name__ == 'T'
581 T.__constraints__ == ()
582 T.__covariant__ == False
583 T.__contravariant__ = False
584 A.__constraints__ == (str, bytes)
Ivan Levkivskyi83494032018-03-26 23:01:12 +0100585
586 Note that only type variables defined in global scope can be pickled.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700587 """
588
Guido van Rossum4cefe742016-09-27 15:20:12 -0700589 __slots__ = ('__name__', '__bound__', '__constraints__',
Serhiy Storchaka09f32212018-05-26 21:19:26 +0300590 '__covariant__', '__contravariant__')
Guido van Rossum4cefe742016-09-27 15:20:12 -0700591
592 def __init__(self, name, *constraints, bound=None,
Guido van Rossumd7adfe12017-01-22 17:43:53 -0800593 covariant=False, contravariant=False):
Guido van Rossum4cefe742016-09-27 15:20:12 -0700594 self.__name__ = name
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700595 if covariant and contravariant:
Guido van Rossumefa798d2016-08-23 11:01:50 -0700596 raise ValueError("Bivariant types are not supported.")
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700597 self.__covariant__ = bool(covariant)
598 self.__contravariant__ = bool(contravariant)
599 if constraints and bound is not None:
600 raise TypeError("Constraints cannot be combined with bound=...")
601 if constraints and len(constraints) == 1:
602 raise TypeError("A single constraint is not allowed")
603 msg = "TypeVar(name, constraint, ...): constraints must be types."
604 self.__constraints__ = tuple(_type_check(t, msg) for t in constraints)
605 if bound:
606 self.__bound__ = _type_check(bound, "Bound must be a type.")
607 else:
608 self.__bound__ = None
Serhiy Storchaka09f32212018-05-26 21:19:26 +0300609 def_mod = sys._getframe(1).f_globals['__name__'] # for pickling
610 if def_mod != 'typing':
611 self.__module__ = def_mod
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700612
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700613 def __repr__(self):
614 if self.__covariant__:
615 prefix = '+'
616 elif self.__contravariant__:
617 prefix = '-'
618 else:
619 prefix = '~'
620 return prefix + self.__name__
621
Ivan Levkivskyi83494032018-03-26 23:01:12 +0100622 def __reduce__(self):
Serhiy Storchaka09f32212018-05-26 21:19:26 +0300623 return self.__name__
Ivan Levkivskyi83494032018-03-26 23:01:12 +0100624
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700625
Guido van Rossum83ec3022017-01-17 20:43:28 -0800626# Special typing constructs Union, Optional, Generic, Callable and Tuple
627# use three special attributes for internal bookkeeping of generic types:
628# * __parameters__ is a tuple of unique free type parameters of a generic
629# type, for example, Dict[T, T].__parameters__ == (T,);
630# * __origin__ keeps a reference to a type that was subscripted,
Ivan Levkivskyi43d12a62018-05-09 02:23:46 +0100631# e.g., Union[T, int].__origin__ == Union, or the non-generic version of
632# the type.
Guido van Rossum83ec3022017-01-17 20:43:28 -0800633# * __args__ is a tuple of all arguments used in subscripting,
634# e.g., Dict[T, int].__args__ == (T, int).
635
Ivan Levkivskyi2a363d22018-04-05 01:25:15 +0100636
637# Mapping from non-generic type names that have a generic alias in typing
638# but with a different name.
639_normalize_alias = {'list': 'List',
640 'tuple': 'Tuple',
641 'dict': 'Dict',
642 'set': 'Set',
643 'frozenset': 'FrozenSet',
644 'deque': 'Deque',
645 'defaultdict': 'DefaultDict',
646 'type': 'Type',
647 'Set': 'AbstractSet'}
648
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000649def _is_dunder(attr):
650 return attr.startswith('__') and attr.endswith('__')
Guido van Rossum83ec3022017-01-17 20:43:28 -0800651
Guido van Rossumb24569a2016-11-20 18:01:29 -0800652
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000653class _GenericAlias(_Final, _root=True):
654 """The central part of internal API.
655
656 This represents a generic version of type 'origin' with type arguments 'params'.
657 There are two kind of these aliases: user defined and special. The special ones
658 are wrappers around builtin collections and ABCs in collections.abc. These must
659 have 'name' always set. If 'inst' is False, then the alias can't be instantiated,
660 this is used by e.g. typing.List and typing.Dict.
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700661 """
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000662 def __init__(self, origin, params, *, inst=True, special=False, name=None):
663 self._inst = inst
664 self._special = special
665 if special and name is None:
666 orig_name = origin.__name__
Ivan Levkivskyi2a363d22018-04-05 01:25:15 +0100667 name = _normalize_alias.get(orig_name, orig_name)
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000668 self._name = name
669 if not isinstance(params, tuple):
670 params = (params,)
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700671 self.__origin__ = origin
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700672 self.__args__ = tuple(... if a is _TypingEllipsis else
673 () if a is _TypingEmpty else
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000674 a for a in params)
675 self.__parameters__ = _collect_type_vars(params)
676 self.__slots__ = None # This is not documented.
677 if not name:
678 self.__module__ = origin.__module__
Serhiy Storchaka7e644142020-04-18 17:13:21 +0300679 if special:
680 self.__doc__ = f'A generic version of {origin.__module__}.{origin.__qualname__}'
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700681
Guido van Rossum4cefe742016-09-27 15:20:12 -0700682 @_tp_cache
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700683 def __getitem__(self, params):
Ivan Levkivskyi74d7f762019-05-28 08:40:15 +0100684 if self.__origin__ in (Generic, Protocol):
685 # Can't subscript Generic[...] or Protocol[...].
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000686 raise TypeError(f"Cannot subscript already-subscripted {self}")
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700687 if not isinstance(params, tuple):
688 params = (params,)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700689 msg = "Parameters to generic types must be types."
690 params = tuple(_type_check(p, msg) for p in params)
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000691 _check_generic(self, params)
692 return _subs_tvars(self, self.__parameters__, params)
Ivan Levkivskyib692dc82017-02-13 22:50:14 +0100693
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000694 def copy_with(self, params):
695 # We don't copy self._special.
696 return _GenericAlias(self.__origin__, params, name=self._name, inst=self._inst)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700697
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000698 def __repr__(self):
699 if (self._name != 'Callable' or
700 len(self.__args__) == 2 and self.__args__[0] is Ellipsis):
701 if self._name:
702 name = 'typing.' + self._name
703 else:
704 name = _type_repr(self.__origin__)
705 if not self._special:
706 args = f'[{", ".join([_type_repr(a) for a in self.__args__])}]'
707 else:
708 args = ''
709 return (f'{name}{args}')
710 if self._special:
711 return 'typing.Callable'
712 return (f'typing.Callable'
713 f'[[{", ".join([_type_repr(a) for a in self.__args__[:-1]])}], '
714 f'{_type_repr(self.__args__[-1])}]')
715
716 def __eq__(self, other):
717 if not isinstance(other, _GenericAlias):
718 return NotImplemented
719 if self.__origin__ != other.__origin__:
Ivan Levkivskyib692dc82017-02-13 22:50:14 +0100720 return False
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000721 if self.__origin__ is Union and other.__origin__ is Union:
722 return frozenset(self.__args__) == frozenset(other.__args__)
723 return self.__args__ == other.__args__
Ivan Levkivskyib692dc82017-02-13 22:50:14 +0100724
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000725 def __hash__(self):
726 if self.__origin__ is Union:
727 return hash((Union, frozenset(self.__args__)))
728 return hash((self.__origin__, self.__args__))
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700729
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000730 def __call__(self, *args, **kwargs):
731 if not self._inst:
732 raise TypeError(f"Type {self._name} cannot be instantiated; "
733 f"use {self._name.lower()}() instead")
734 result = self.__origin__(*args, **kwargs)
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700735 try:
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000736 result.__orig_class__ = self
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700737 except AttributeError:
738 pass
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000739 return result
740
741 def __mro_entries__(self, bases):
742 if self._name: # generic version of an ABC or built-in class
743 res = []
744 if self.__origin__ not in bases:
745 res.append(self.__origin__)
746 i = bases.index(self)
747 if not any(isinstance(b, _GenericAlias) or issubclass(b, Generic)
748 for b in bases[i+1:]):
749 res.append(Generic)
750 return tuple(res)
751 if self.__origin__ is Generic:
Ivan Levkivskyi74d7f762019-05-28 08:40:15 +0100752 if Protocol in bases:
753 return ()
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000754 i = bases.index(self)
755 for b in bases[i+1:]:
756 if isinstance(b, _GenericAlias) and b is not self:
757 return ()
758 return (self.__origin__,)
759
760 def __getattr__(self, attr):
Ville Skyttä61f82e02018-04-20 23:08:45 +0300761 # We are careful for copy and pickle.
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000762 # Also for simplicity we just don't relay all dunder names
763 if '__origin__' in self.__dict__ and not _is_dunder(attr):
764 return getattr(self.__origin__, attr)
765 raise AttributeError(attr)
766
767 def __setattr__(self, attr, val):
768 if _is_dunder(attr) or attr in ('_name', '_inst', '_special'):
769 super().__setattr__(attr, val)
770 else:
771 setattr(self.__origin__, attr, val)
772
773 def __instancecheck__(self, obj):
774 return self.__subclasscheck__(type(obj))
775
776 def __subclasscheck__(self, cls):
777 if self._special:
778 if not isinstance(cls, _GenericAlias):
779 return issubclass(cls, self.__origin__)
780 if cls._special:
781 return issubclass(cls.__origin__, self.__origin__)
782 raise TypeError("Subscripted generics cannot be used with"
783 " class and instance checks")
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700784
Ivan Levkivskyi83494032018-03-26 23:01:12 +0100785 def __reduce__(self):
786 if self._special:
787 return self._name
Serhiy Storchaka09f32212018-05-26 21:19:26 +0300788
789 if self._name:
790 origin = globals()[self._name]
791 else:
792 origin = self.__origin__
793 if (origin is Callable and
794 not (len(self.__args__) == 2 and self.__args__[0] is Ellipsis)):
795 args = list(self.__args__[:-1]), self.__args__[-1]
796 else:
797 args = tuple(self.__args__)
798 if len(args) == 1 and not isinstance(args[0], tuple):
799 args, = args
800 return operator.getitem, (origin, args)
Ivan Levkivskyi83494032018-03-26 23:01:12 +0100801
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700802
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000803class _VariadicGenericAlias(_GenericAlias, _root=True):
804 """Same as _GenericAlias above but for variadic aliases. Currently,
805 this is used only by special internal aliases: Tuple and Callable.
806 """
807 def __getitem__(self, params):
808 if self._name != 'Callable' or not self._special:
809 return self.__getitem_inner__(params)
810 if not isinstance(params, tuple) or len(params) != 2:
811 raise TypeError("Callable must be used as "
812 "Callable[[arg, ...], result].")
813 args, result = params
814 if args is Ellipsis:
815 params = (Ellipsis, result)
816 else:
817 if not isinstance(args, list):
818 raise TypeError(f"Callable[args, result]: args must be a list."
819 f" Got {args}")
820 params = (tuple(args), result)
821 return self.__getitem_inner__(params)
822
823 @_tp_cache
824 def __getitem_inner__(self, params):
825 if self.__origin__ is tuple and self._special:
826 if params == ():
827 return self.copy_with((_TypingEmpty,))
828 if not isinstance(params, tuple):
829 params = (params,)
830 if len(params) == 2 and params[1] is ...:
831 msg = "Tuple[t, ...]: t must be a type."
832 p = _type_check(params[0], msg)
833 return self.copy_with((p, _TypingEllipsis))
834 msg = "Tuple[t0, t1, ...]: each t must be a type."
835 params = tuple(_type_check(p, msg) for p in params)
836 return self.copy_with(params)
837 if self.__origin__ is collections.abc.Callable and self._special:
838 args, result = params
839 msg = "Callable[args, result]: result must be a type."
840 result = _type_check(result, msg)
841 if args is Ellipsis:
842 return self.copy_with((_TypingEllipsis, result))
843 msg = "Callable[[arg, ...], result]: each arg must be a type."
844 args = tuple(_type_check(arg, msg) for arg in args)
845 params = args + (result,)
846 return self.copy_with(params)
847 return super().__getitem__(params)
848
849
850class Generic:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700851 """Abstract base class for generic types.
852
Guido van Rossumb24569a2016-11-20 18:01:29 -0800853 A generic type is typically declared by inheriting from
854 this class parameterized with one or more type variables.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700855 For example, a generic mapping type might be defined as::
856
857 class Mapping(Generic[KT, VT]):
858 def __getitem__(self, key: KT) -> VT:
859 ...
860 # Etc.
861
862 This class can then be used as follows::
863
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700864 def lookup_name(mapping: Mapping[KT, VT], key: KT, default: VT) -> VT:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700865 try:
866 return mapping[key]
867 except KeyError:
868 return default
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700869 """
Guido van Rossumd70fe632015-08-05 12:11:06 +0200870 __slots__ = ()
Ivan Levkivskyi74d7f762019-05-28 08:40:15 +0100871 _is_protocol = False
Guido van Rossumd70fe632015-08-05 12:11:06 +0200872
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700873 def __new__(cls, *args, **kwds):
Ivan Levkivskyi74d7f762019-05-28 08:40:15 +0100874 if cls in (Generic, Protocol):
875 raise TypeError(f"Type {cls.__name__} cannot be instantiated; "
Guido van Rossum62fe1bb2016-10-29 16:05:26 -0700876 "it can be used only as a base class")
Ivan Levkivskyib551e9f2018-05-10 23:10:10 -0400877 if super().__new__ is object.__new__ and cls.__init__ is not object.__init__:
Ivan Levkivskyi43d12a62018-05-09 02:23:46 +0100878 obj = super().__new__(cls)
879 else:
880 obj = super().__new__(cls, *args, **kwds)
881 return obj
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000882
883 @_tp_cache
884 def __class_getitem__(cls, params):
885 if not isinstance(params, tuple):
886 params = (params,)
887 if not params and cls is not Tuple:
888 raise TypeError(
889 f"Parameter list to {cls.__qualname__}[...] cannot be empty")
890 msg = "Parameters to generic types must be types."
891 params = tuple(_type_check(p, msg) for p in params)
Ivan Levkivskyi74d7f762019-05-28 08:40:15 +0100892 if cls in (Generic, Protocol):
893 # Generic and Protocol can only be subscripted with unique type variables.
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000894 if not all(isinstance(p, TypeVar) for p in params):
895 raise TypeError(
Ivan Levkivskyi74d7f762019-05-28 08:40:15 +0100896 f"Parameters to {cls.__name__}[...] must all be type variables")
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000897 if len(set(params)) != len(params):
898 raise TypeError(
Ivan Levkivskyi74d7f762019-05-28 08:40:15 +0100899 f"Parameters to {cls.__name__}[...] must all be unique")
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000900 else:
901 # Subscripting a regular Generic subclass.
902 _check_generic(cls, params)
903 return _GenericAlias(cls, params)
904
905 def __init_subclass__(cls, *args, **kwargs):
Ivan Levkivskyiee566fe2018-04-04 17:00:15 +0100906 super().__init_subclass__(*args, **kwargs)
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000907 tvars = []
908 if '__orig_bases__' in cls.__dict__:
909 error = Generic in cls.__orig_bases__
910 else:
Ivan Levkivskyi74d7f762019-05-28 08:40:15 +0100911 error = Generic in cls.__bases__ and cls.__name__ != 'Protocol'
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000912 if error:
913 raise TypeError("Cannot inherit from plain Generic")
914 if '__orig_bases__' in cls.__dict__:
915 tvars = _collect_type_vars(cls.__orig_bases__)
916 # Look for Generic[T1, ..., Tn].
917 # If found, tvars must be a subset of it.
918 # If not found, tvars is it.
919 # Also check for and reject plain Generic,
920 # and reject multiple Generic[...].
921 gvars = None
922 for base in cls.__orig_bases__:
923 if (isinstance(base, _GenericAlias) and
924 base.__origin__ is Generic):
925 if gvars is not None:
926 raise TypeError(
927 "Cannot inherit from Generic[...] multiple types.")
928 gvars = base.__parameters__
Ivan Levkivskyi74d7f762019-05-28 08:40:15 +0100929 if gvars is not None:
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000930 tvarset = set(tvars)
931 gvarset = set(gvars)
932 if not tvarset <= gvarset:
933 s_vars = ', '.join(str(t) for t in tvars if t not in gvarset)
934 s_args = ', '.join(str(g) for g in gvars)
935 raise TypeError(f"Some type variables ({s_vars}) are"
936 f" not listed in Generic[{s_args}]")
937 tvars = gvars
938 cls.__parameters__ = tuple(tvars)
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700939
940
941class _TypingEmpty:
Guido van Rossumb24569a2016-11-20 18:01:29 -0800942 """Internal placeholder for () or []. Used by TupleMeta and CallableMeta
943 to allow empty list/tuple in specific places, without allowing them
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700944 to sneak in where prohibited.
945 """
946
947
948class _TypingEllipsis:
Guido van Rossumb24569a2016-11-20 18:01:29 -0800949 """Internal placeholder for ... (ellipsis)."""
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700950
951
Ivan Levkivskyi74d7f762019-05-28 08:40:15 +0100952_TYPING_INTERNALS = ['__parameters__', '__orig_bases__', '__orig_class__',
953 '_is_protocol', '_is_runtime_protocol']
954
955_SPECIAL_NAMES = ['__abstractmethods__', '__annotations__', '__dict__', '__doc__',
956 '__init__', '__module__', '__new__', '__slots__',
Guido van Rossum48b069a2020-04-07 09:50:06 -0700957 '__subclasshook__', '__weakref__', '__class_getitem__']
Ivan Levkivskyi74d7f762019-05-28 08:40:15 +0100958
959# These special attributes will be not collected as protocol members.
960EXCLUDED_ATTRIBUTES = _TYPING_INTERNALS + _SPECIAL_NAMES + ['_MutableMapping__marker']
961
962
963def _get_protocol_attrs(cls):
964 """Collect protocol members from a protocol class objects.
965
966 This includes names actually defined in the class dictionary, as well
967 as names that appear in annotations. Special names (above) are skipped.
968 """
969 attrs = set()
970 for base in cls.__mro__[:-1]: # without object
971 if base.__name__ in ('Protocol', 'Generic'):
972 continue
973 annotations = getattr(base, '__annotations__', {})
974 for attr in list(base.__dict__.keys()) + list(annotations.keys()):
975 if not attr.startswith('_abc_') and attr not in EXCLUDED_ATTRIBUTES:
976 attrs.add(attr)
977 return attrs
978
979
980def _is_callable_members_only(cls):
981 # PEP 544 prohibits using issubclass() with protocols that have non-method members.
982 return all(callable(getattr(cls, attr, None)) for attr in _get_protocol_attrs(cls))
983
984
985def _no_init(self, *args, **kwargs):
986 if type(self)._is_protocol:
987 raise TypeError('Protocols cannot be instantiated')
988
989
990def _allow_reckless_class_cheks():
991 """Allow instnance and class checks for special stdlib modules.
992
993 The abc and functools modules indiscriminately call isinstance() and
994 issubclass() on the whole MRO of a user class, which may contain protocols.
995 """
996 try:
997 return sys._getframe(3).f_globals['__name__'] in ['abc', 'functools']
998 except (AttributeError, ValueError): # For platforms without _getframe().
999 return True
1000
1001
Divij Rajkumar692a0dc2019-09-12 11:13:51 +01001002_PROTO_WHITELIST = {
1003 'collections.abc': [
1004 'Callable', 'Awaitable', 'Iterable', 'Iterator', 'AsyncIterable',
1005 'Hashable', 'Sized', 'Container', 'Collection', 'Reversible',
1006 ],
1007 'contextlib': ['AbstractContextManager', 'AbstractAsyncContextManager'],
1008}
Ivan Levkivskyi74d7f762019-05-28 08:40:15 +01001009
1010
1011class _ProtocolMeta(ABCMeta):
1012 # This metaclass is really unfortunate and exists only because of
1013 # the lack of __instancehook__.
1014 def __instancecheck__(cls, instance):
1015 # We need this method for situations where attributes are
1016 # assigned in __init__.
1017 if ((not getattr(cls, '_is_protocol', False) or
1018 _is_callable_members_only(cls)) and
1019 issubclass(instance.__class__, cls)):
1020 return True
1021 if cls._is_protocol:
1022 if all(hasattr(instance, attr) and
1023 # All *methods* can be blocked by setting them to None.
1024 (not callable(getattr(cls, attr, None)) or
1025 getattr(instance, attr) is not None)
1026 for attr in _get_protocol_attrs(cls)):
1027 return True
1028 return super().__instancecheck__(instance)
1029
1030
1031class Protocol(Generic, metaclass=_ProtocolMeta):
1032 """Base class for protocol classes.
1033
1034 Protocol classes are defined as::
1035
1036 class Proto(Protocol):
1037 def meth(self) -> int:
1038 ...
1039
1040 Such classes are primarily used with static type checkers that recognize
1041 structural subtyping (static duck-typing), for example::
1042
1043 class C:
1044 def meth(self) -> int:
1045 return 0
1046
1047 def func(x: Proto) -> int:
1048 return x.meth()
1049
1050 func(C()) # Passes static type check
1051
1052 See PEP 544 for details. Protocol classes decorated with
1053 @typing.runtime_checkable act as simple-minded runtime protocols that check
1054 only the presence of given attributes, ignoring their type signatures.
1055 Protocol classes can be generic, they are defined as::
1056
1057 class GenProto(Protocol[T]):
1058 def meth(self) -> T:
1059 ...
1060 """
1061 __slots__ = ()
1062 _is_protocol = True
1063 _is_runtime_protocol = False
1064
1065 def __init_subclass__(cls, *args, **kwargs):
1066 super().__init_subclass__(*args, **kwargs)
1067
1068 # Determine if this is a protocol or a concrete subclass.
1069 if not cls.__dict__.get('_is_protocol', False):
1070 cls._is_protocol = any(b is Protocol for b in cls.__bases__)
1071
1072 # Set (or override) the protocol subclass hook.
1073 def _proto_hook(other):
1074 if not cls.__dict__.get('_is_protocol', False):
1075 return NotImplemented
1076
1077 # First, perform various sanity checks.
1078 if not getattr(cls, '_is_runtime_protocol', False):
1079 if _allow_reckless_class_cheks():
1080 return NotImplemented
1081 raise TypeError("Instance and class checks can only be used with"
1082 " @runtime_checkable protocols")
1083 if not _is_callable_members_only(cls):
1084 if _allow_reckless_class_cheks():
1085 return NotImplemented
1086 raise TypeError("Protocols with non-method members"
1087 " don't support issubclass()")
1088 if not isinstance(other, type):
1089 # Same error message as for issubclass(1, int).
1090 raise TypeError('issubclass() arg 1 must be a class')
1091
1092 # Second, perform the actual structural compatibility check.
1093 for attr in _get_protocol_attrs(cls):
1094 for base in other.__mro__:
1095 # Check if the members appears in the class dictionary...
1096 if attr in base.__dict__:
1097 if base.__dict__[attr] is None:
1098 return NotImplemented
1099 break
1100
1101 # ...or in annotations, if it is a sub-protocol.
1102 annotations = getattr(base, '__annotations__', {})
1103 if (isinstance(annotations, collections.abc.Mapping) and
1104 attr in annotations and
1105 issubclass(other, Generic) and other._is_protocol):
1106 break
1107 else:
1108 return NotImplemented
1109 return True
1110
1111 if '__subclasshook__' not in cls.__dict__:
1112 cls.__subclasshook__ = _proto_hook
1113
1114 # We have nothing more to do for non-protocols...
1115 if not cls._is_protocol:
1116 return
1117
1118 # ... otherwise check consistency of bases, and prohibit instantiation.
1119 for base in cls.__bases__:
1120 if not (base in (object, Generic) or
Divij Rajkumar692a0dc2019-09-12 11:13:51 +01001121 base.__module__ in _PROTO_WHITELIST and
1122 base.__name__ in _PROTO_WHITELIST[base.__module__] or
Ivan Levkivskyi74d7f762019-05-28 08:40:15 +01001123 issubclass(base, Generic) and base._is_protocol):
1124 raise TypeError('Protocols can only inherit from other'
1125 ' protocols, got %r' % base)
1126 cls.__init__ = _no_init
1127
1128
Jakub Stasiakcf5b1092020-02-05 02:10:19 +01001129class _AnnotatedAlias(_GenericAlias, _root=True):
1130 """Runtime representation of an annotated type.
1131
1132 At its core 'Annotated[t, dec1, dec2, ...]' is an alias for the type 't'
1133 with extra annotations. The alias behaves like a normal typing alias,
1134 instantiating is the same as instantiating the underlying type, binding
1135 it to types is also the same.
1136 """
1137 def __init__(self, origin, metadata):
1138 if isinstance(origin, _AnnotatedAlias):
1139 metadata = origin.__metadata__ + metadata
1140 origin = origin.__origin__
1141 super().__init__(origin, origin)
1142 self.__metadata__ = metadata
1143
1144 def copy_with(self, params):
1145 assert len(params) == 1
1146 new_type = params[0]
1147 return _AnnotatedAlias(new_type, self.__metadata__)
1148
1149 def __repr__(self):
1150 return "typing.Annotated[{}, {}]".format(
1151 _type_repr(self.__origin__),
1152 ", ".join(repr(a) for a in self.__metadata__)
1153 )
1154
1155 def __reduce__(self):
1156 return operator.getitem, (
1157 Annotated, (self.__origin__,) + self.__metadata__
1158 )
1159
1160 def __eq__(self, other):
1161 if not isinstance(other, _AnnotatedAlias):
1162 return NotImplemented
1163 if self.__origin__ != other.__origin__:
1164 return False
1165 return self.__metadata__ == other.__metadata__
1166
1167 def __hash__(self):
1168 return hash((self.__origin__, self.__metadata__))
1169
1170
1171class Annotated:
1172 """Add context specific metadata to a type.
1173
1174 Example: Annotated[int, runtime_check.Unsigned] indicates to the
1175 hypothetical runtime_check module that this type is an unsigned int.
1176 Every other consumer of this type can ignore this metadata and treat
1177 this type as int.
1178
1179 The first argument to Annotated must be a valid type.
1180
1181 Details:
1182
1183 - It's an error to call `Annotated` with less than two arguments.
1184 - Nested Annotated are flattened::
1185
1186 Annotated[Annotated[T, Ann1, Ann2], Ann3] == Annotated[T, Ann1, Ann2, Ann3]
1187
1188 - Instantiating an annotated type is equivalent to instantiating the
1189 underlying type::
1190
1191 Annotated[C, Ann1](5) == C(5)
1192
1193 - Annotated can be used as a generic type alias::
1194
1195 Optimized = Annotated[T, runtime.Optimize()]
1196 Optimized[int] == Annotated[int, runtime.Optimize()]
1197
1198 OptimizedList = Annotated[List[T], runtime.Optimize()]
1199 OptimizedList[int] == Annotated[List[int], runtime.Optimize()]
1200 """
1201
1202 __slots__ = ()
1203
1204 def __new__(cls, *args, **kwargs):
1205 raise TypeError("Type Annotated cannot be instantiated.")
1206
1207 @_tp_cache
1208 def __class_getitem__(cls, params):
1209 if not isinstance(params, tuple) or len(params) < 2:
1210 raise TypeError("Annotated[...] should be used "
1211 "with at least two arguments (a type and an "
1212 "annotation).")
1213 msg = "Annotated[t, ...]: t must be a type."
1214 origin = _type_check(params[0], msg)
1215 metadata = tuple(params[1:])
1216 return _AnnotatedAlias(origin, metadata)
1217
1218 def __init_subclass__(cls, *args, **kwargs):
1219 raise TypeError(
1220 "Cannot subclass {}.Annotated".format(cls.__module__)
1221 )
1222
1223
Ivan Levkivskyi74d7f762019-05-28 08:40:15 +01001224def runtime_checkable(cls):
1225 """Mark a protocol class as a runtime protocol.
1226
1227 Such protocol can be used with isinstance() and issubclass().
1228 Raise TypeError if applied to a non-protocol class.
1229 This allows a simple-minded structural check very similar to
1230 one trick ponies in collections.abc such as Iterable.
1231 For example::
1232
1233 @runtime_checkable
1234 class Closable(Protocol):
1235 def close(self): ...
1236
1237 assert isinstance(open('/some/file'), Closable)
1238
1239 Warning: this will check only the presence of the required methods,
1240 not their type signatures!
1241 """
1242 if not issubclass(cls, Generic) or not cls._is_protocol:
1243 raise TypeError('@runtime_checkable can be only applied to protocol classes,'
1244 ' got %r' % cls)
1245 cls._is_runtime_protocol = True
1246 return cls
1247
1248
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001249def cast(typ, val):
1250 """Cast a value to a type.
1251
1252 This returns the value unchanged. To the type checker this
1253 signals that the return value has the designated type, but at
1254 runtime we intentionally don't check anything (we want this
1255 to be as fast as possible).
1256 """
1257 return val
1258
1259
1260def _get_defaults(func):
1261 """Internal helper to extract the default arguments, by name."""
Guido van Rossum991d14f2016-11-09 13:12:51 -08001262 try:
1263 code = func.__code__
1264 except AttributeError:
1265 # Some built-in functions don't have __code__, __defaults__, etc.
1266 return {}
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001267 pos_count = code.co_argcount
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001268 arg_names = code.co_varnames
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001269 arg_names = arg_names[:pos_count]
1270 defaults = func.__defaults__ or ()
1271 kwdefaults = func.__kwdefaults__
1272 res = dict(kwdefaults) if kwdefaults else {}
1273 pos_offset = pos_count - len(defaults)
1274 for name, value in zip(arg_names[pos_offset:], defaults):
1275 assert name not in res
1276 res[name] = value
1277 return res
1278
1279
Ivan Levkivskyib692dc82017-02-13 22:50:14 +01001280_allowed_types = (types.FunctionType, types.BuiltinFunctionType,
1281 types.MethodType, types.ModuleType,
Ivan Levkivskyif06e0212017-05-02 19:14:07 +02001282 WrapperDescriptorType, MethodWrapperType, MethodDescriptorType)
Ivan Levkivskyib692dc82017-02-13 22:50:14 +01001283
1284
Jakub Stasiakcf5b1092020-02-05 02:10:19 +01001285def get_type_hints(obj, globalns=None, localns=None, include_extras=False):
Guido van Rossum991d14f2016-11-09 13:12:51 -08001286 """Return type hints for an object.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001287
Guido van Rossum991d14f2016-11-09 13:12:51 -08001288 This is often the same as obj.__annotations__, but it handles
Jakub Stasiakcf5b1092020-02-05 02:10:19 +01001289 forward references encoded as string literals, adds Optional[t] if a
1290 default value equal to None is set and recursively replaces all
1291 'Annotated[T, ...]' with 'T' (unless 'include_extras=True').
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001292
Guido van Rossum991d14f2016-11-09 13:12:51 -08001293 The argument may be a module, class, method, or function. The annotations
1294 are returned as a dictionary. For classes, annotations include also
1295 inherited members.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001296
Guido van Rossum991d14f2016-11-09 13:12:51 -08001297 TypeError is raised if the argument is not of a type that can contain
1298 annotations, and an empty dictionary is returned if no annotations are
1299 present.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001300
Guido van Rossum991d14f2016-11-09 13:12:51 -08001301 BEWARE -- the behavior of globalns and localns is counterintuitive
1302 (unless you are familiar with how eval() and exec() work). The
1303 search order is locals first, then globals.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001304
Guido van Rossum991d14f2016-11-09 13:12:51 -08001305 - If no dict arguments are passed, an attempt is made to use the
Łukasz Langaf350a262017-09-14 14:33:00 -04001306 globals from obj (or the respective module's globals for classes),
1307 and these are also used as the locals. If the object does not appear
1308 to have globals, an empty dictionary is used.
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001309
Guido van Rossum991d14f2016-11-09 13:12:51 -08001310 - If one dict argument is passed, it is used for both globals and
1311 locals.
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001312
Guido van Rossum991d14f2016-11-09 13:12:51 -08001313 - If two dict arguments are passed, they specify globals and
1314 locals, respectively.
1315 """
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001316
Guido van Rossum991d14f2016-11-09 13:12:51 -08001317 if getattr(obj, '__no_type_check__', None):
1318 return {}
Guido van Rossum991d14f2016-11-09 13:12:51 -08001319 # Classes require a special treatment.
1320 if isinstance(obj, type):
1321 hints = {}
1322 for base in reversed(obj.__mro__):
Łukasz Langaf350a262017-09-14 14:33:00 -04001323 if globalns is None:
1324 base_globals = sys.modules[base.__module__].__dict__
1325 else:
1326 base_globals = globalns
Guido van Rossum991d14f2016-11-09 13:12:51 -08001327 ann = base.__dict__.get('__annotations__', {})
1328 for name, value in ann.items():
1329 if value is None:
1330 value = type(None)
1331 if isinstance(value, str):
Nina Zakharenko0e61dff2018-05-22 20:32:10 -07001332 value = ForwardRef(value, is_argument=False)
Łukasz Langaf350a262017-09-14 14:33:00 -04001333 value = _eval_type(value, base_globals, localns)
Guido van Rossum991d14f2016-11-09 13:12:51 -08001334 hints[name] = value
Jakub Stasiakcf5b1092020-02-05 02:10:19 +01001335 return hints if include_extras else {k: _strip_annotations(t) for k, t in hints.items()}
Łukasz Langaf350a262017-09-14 14:33:00 -04001336
1337 if globalns is None:
1338 if isinstance(obj, types.ModuleType):
1339 globalns = obj.__dict__
1340 else:
benedwards140aca3a32019-11-21 17:24:58 +00001341 nsobj = obj
1342 # Find globalns for the unwrapped object.
1343 while hasattr(nsobj, '__wrapped__'):
1344 nsobj = nsobj.__wrapped__
1345 globalns = getattr(nsobj, '__globals__', {})
Łukasz Langaf350a262017-09-14 14:33:00 -04001346 if localns is None:
1347 localns = globalns
1348 elif localns is None:
1349 localns = globalns
Guido van Rossum991d14f2016-11-09 13:12:51 -08001350 hints = getattr(obj, '__annotations__', None)
1351 if hints is None:
1352 # Return empty annotations for something that _could_ have them.
Ivan Levkivskyib692dc82017-02-13 22:50:14 +01001353 if isinstance(obj, _allowed_types):
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001354 return {}
Guido van Rossum991d14f2016-11-09 13:12:51 -08001355 else:
1356 raise TypeError('{!r} is not a module, class, method, '
1357 'or function.'.format(obj))
1358 defaults = _get_defaults(obj)
1359 hints = dict(hints)
1360 for name, value in hints.items():
1361 if value is None:
1362 value = type(None)
1363 if isinstance(value, str):
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001364 value = ForwardRef(value)
Guido van Rossum991d14f2016-11-09 13:12:51 -08001365 value = _eval_type(value, globalns, localns)
1366 if name in defaults and defaults[name] is None:
1367 value = Optional[value]
1368 hints[name] = value
Jakub Stasiakcf5b1092020-02-05 02:10:19 +01001369 return hints if include_extras else {k: _strip_annotations(t) for k, t in hints.items()}
1370
1371
1372def _strip_annotations(t):
1373 """Strips the annotations from a given type.
1374 """
1375 if isinstance(t, _AnnotatedAlias):
1376 return _strip_annotations(t.__origin__)
1377 if isinstance(t, _GenericAlias):
1378 stripped_args = tuple(_strip_annotations(a) for a in t.__args__)
1379 if stripped_args == t.__args__:
1380 return t
1381 res = t.copy_with(stripped_args)
1382 res._special = t._special
1383 return res
1384 return t
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001385
1386
Ivan Levkivskyi4c23aff2019-05-31 00:10:07 +01001387def get_origin(tp):
1388 """Get the unsubscripted version of a type.
1389
Jakub Stasiak38aaaaa2020-02-07 02:15:12 +01001390 This supports generic types, Callable, Tuple, Union, Literal, Final, ClassVar
1391 and Annotated. Return None for unsupported types. Examples::
Ivan Levkivskyi4c23aff2019-05-31 00:10:07 +01001392
1393 get_origin(Literal[42]) is Literal
1394 get_origin(int) is None
1395 get_origin(ClassVar[int]) is ClassVar
1396 get_origin(Generic) is Generic
1397 get_origin(Generic[T]) is Generic
1398 get_origin(Union[T, int]) is Union
1399 get_origin(List[Tuple[T, T]][int]) == list
1400 """
Jakub Stasiakcf5b1092020-02-05 02:10:19 +01001401 if isinstance(tp, _AnnotatedAlias):
1402 return Annotated
Ivan Levkivskyi4c23aff2019-05-31 00:10:07 +01001403 if isinstance(tp, _GenericAlias):
1404 return tp.__origin__
1405 if tp is Generic:
1406 return Generic
1407 return None
1408
1409
1410def get_args(tp):
1411 """Get type arguments with all substitutions performed.
1412
1413 For unions, basic simplifications used by Union constructor are performed.
1414 Examples::
1415 get_args(Dict[str, int]) == (str, int)
1416 get_args(int) == ()
1417 get_args(Union[int, Union[T, int], str][int]) == (int, str)
1418 get_args(Union[int, Tuple[T, int]][str]) == (int, Tuple[str, int])
1419 get_args(Callable[[], T][int]) == ([], int)
1420 """
Jakub Stasiakcf5b1092020-02-05 02:10:19 +01001421 if isinstance(tp, _AnnotatedAlias):
1422 return (tp.__origin__,) + tp.__metadata__
Ivan Levkivskyi4c23aff2019-05-31 00:10:07 +01001423 if isinstance(tp, _GenericAlias):
1424 res = tp.__args__
1425 if get_origin(tp) is collections.abc.Callable and res[0] is not Ellipsis:
1426 res = (list(res[:-1]), res[-1])
1427 return res
1428 return ()
1429
1430
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001431def no_type_check(arg):
1432 """Decorator to indicate that annotations are not type hints.
1433
1434 The argument must be a class or function; if it is a class, it
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001435 applies recursively to all methods and classes defined in that class
1436 (but not to methods defined in its superclasses or subclasses).
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001437
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001438 This mutates the function(s) or class(es) in place.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001439 """
1440 if isinstance(arg, type):
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001441 arg_attrs = arg.__dict__.copy()
1442 for attr, val in arg.__dict__.items():
Ivan Levkivskyi65bc6202017-09-14 01:25:15 +02001443 if val in arg.__bases__ + (arg,):
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001444 arg_attrs.pop(attr)
1445 for obj in arg_attrs.values():
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001446 if isinstance(obj, types.FunctionType):
1447 obj.__no_type_check__ = True
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001448 if isinstance(obj, type):
1449 no_type_check(obj)
1450 try:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001451 arg.__no_type_check__ = True
Guido van Rossumd7adfe12017-01-22 17:43:53 -08001452 except TypeError: # built-in classes
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001453 pass
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001454 return arg
1455
1456
1457def no_type_check_decorator(decorator):
1458 """Decorator to give another decorator the @no_type_check effect.
1459
1460 This wraps the decorator with something that wraps the decorated
1461 function in @no_type_check.
1462 """
1463
1464 @functools.wraps(decorator)
1465 def wrapped_decorator(*args, **kwds):
1466 func = decorator(*args, **kwds)
1467 func = no_type_check(func)
1468 return func
1469
1470 return wrapped_decorator
1471
1472
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001473def _overload_dummy(*args, **kwds):
1474 """Helper for @overload to raise when called."""
1475 raise NotImplementedError(
1476 "You should not call an overloaded function. "
1477 "A series of @overload-decorated functions "
1478 "outside a stub module should always be followed "
1479 "by an implementation that is not @overload-ed.")
1480
1481
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001482def overload(func):
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001483 """Decorator for overloaded functions/methods.
1484
1485 In a stub file, place two or more stub definitions for the same
1486 function in a row, each decorated with @overload. For example:
1487
1488 @overload
1489 def utf8(value: None) -> None: ...
1490 @overload
1491 def utf8(value: bytes) -> bytes: ...
1492 @overload
1493 def utf8(value: str) -> bytes: ...
1494
1495 In a non-stub file (i.e. a regular .py file), do the same but
1496 follow it with an implementation. The implementation should *not*
1497 be decorated with @overload. For example:
1498
1499 @overload
1500 def utf8(value: None) -> None: ...
1501 @overload
1502 def utf8(value: bytes) -> bytes: ...
1503 @overload
1504 def utf8(value: str) -> bytes: ...
1505 def utf8(value):
1506 # implementation goes here
1507 """
1508 return _overload_dummy
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001509
1510
Ivan Levkivskyif3672422019-05-26 09:37:07 +01001511def final(f):
1512 """A decorator to indicate final methods and final classes.
1513
1514 Use this decorator to indicate to type checkers that the decorated
1515 method cannot be overridden, and decorated class cannot be subclassed.
1516 For example:
1517
1518 class Base:
1519 @final
1520 def done(self) -> None:
1521 ...
1522 class Sub(Base):
1523 def done(self) -> None: # Error reported by type checker
1524 ...
1525
1526 @final
1527 class Leaf:
1528 ...
1529 class Other(Leaf): # Error reported by type checker
1530 ...
1531
1532 There is no runtime checking of these properties.
1533 """
1534 return f
1535
1536
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001537# Some unconstrained type variables. These are used by the container types.
1538# (These are not for export.)
1539T = TypeVar('T') # Any type.
1540KT = TypeVar('KT') # Key type.
1541VT = TypeVar('VT') # Value type.
1542T_co = TypeVar('T_co', covariant=True) # Any type covariant containers.
1543V_co = TypeVar('V_co', covariant=True) # Any type covariant containers.
1544VT_co = TypeVar('VT_co', covariant=True) # Value type covariant containers.
1545T_contra = TypeVar('T_contra', contravariant=True) # Ditto contravariant.
1546# Internal type variable used for Type[].
1547CT_co = TypeVar('CT_co', covariant=True, bound=type)
1548
1549# A useful type variable with constraints. This represents string types.
1550# (This one *is* for export!)
1551AnyStr = TypeVar('AnyStr', bytes, str)
1552
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001553
1554# Various ABCs mimicking those in collections.abc.
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001555def _alias(origin, params, inst=True):
1556 return _GenericAlias(origin, params, special=True, inst=inst)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001557
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001558Hashable = _alias(collections.abc.Hashable, ()) # Not generic.
1559Awaitable = _alias(collections.abc.Awaitable, T_co)
1560Coroutine = _alias(collections.abc.Coroutine, (T_co, T_contra, V_co))
1561AsyncIterable = _alias(collections.abc.AsyncIterable, T_co)
1562AsyncIterator = _alias(collections.abc.AsyncIterator, T_co)
1563Iterable = _alias(collections.abc.Iterable, T_co)
1564Iterator = _alias(collections.abc.Iterator, T_co)
1565Reversible = _alias(collections.abc.Reversible, T_co)
1566Sized = _alias(collections.abc.Sized, ()) # Not generic.
1567Container = _alias(collections.abc.Container, T_co)
1568Collection = _alias(collections.abc.Collection, T_co)
1569Callable = _VariadicGenericAlias(collections.abc.Callable, (), special=True)
1570Callable.__doc__ = \
1571 """Callable type; Callable[[int], str] is a function of (int) -> str.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001572
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001573 The subscription syntax must always be used with exactly two
1574 values: the argument list and the return type. The argument list
1575 must be a list of types or ellipsis; the return type must be a single type.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001576
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001577 There is no syntax to indicate optional or keyword arguments,
1578 such function types are rarely used as callback types.
1579 """
1580AbstractSet = _alias(collections.abc.Set, T_co)
1581MutableSet = _alias(collections.abc.MutableSet, T)
1582# NOTE: Mapping is only covariant in the value type.
1583Mapping = _alias(collections.abc.Mapping, (KT, VT_co))
1584MutableMapping = _alias(collections.abc.MutableMapping, (KT, VT))
1585Sequence = _alias(collections.abc.Sequence, T_co)
1586MutableSequence = _alias(collections.abc.MutableSequence, T)
1587ByteString = _alias(collections.abc.ByteString, ()) # Not generic
1588Tuple = _VariadicGenericAlias(tuple, (), inst=False, special=True)
1589Tuple.__doc__ = \
1590 """Tuple type; Tuple[X, Y] is the cross-product type of X and Y.
Guido van Rossum62fe1bb2016-10-29 16:05:26 -07001591
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001592 Example: Tuple[T1, T2] is a tuple of two elements corresponding
1593 to type variables T1 and T2. Tuple[int, float, str] is a tuple
1594 of an int, a float and a string.
Guido van Rossum62fe1bb2016-10-29 16:05:26 -07001595
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001596 To specify a variable-length tuple of homogeneous type, use Tuple[T, ...].
1597 """
1598List = _alias(list, T, inst=False)
1599Deque = _alias(collections.deque, T)
1600Set = _alias(set, T, inst=False)
1601FrozenSet = _alias(frozenset, T_co, inst=False)
1602MappingView = _alias(collections.abc.MappingView, T_co)
1603KeysView = _alias(collections.abc.KeysView, KT)
1604ItemsView = _alias(collections.abc.ItemsView, (KT, VT_co))
1605ValuesView = _alias(collections.abc.ValuesView, VT_co)
1606ContextManager = _alias(contextlib.AbstractContextManager, T_co)
1607AsyncContextManager = _alias(contextlib.AbstractAsyncContextManager, T_co)
1608Dict = _alias(dict, (KT, VT), inst=False)
1609DefaultDict = _alias(collections.defaultdict, (KT, VT))
Ismo Toijala68b56d02018-12-02 17:53:14 +02001610OrderedDict = _alias(collections.OrderedDict, (KT, VT))
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001611Counter = _alias(collections.Counter, T)
1612ChainMap = _alias(collections.ChainMap, (KT, VT))
1613Generator = _alias(collections.abc.Generator, (T_co, T_contra, V_co))
1614AsyncGenerator = _alias(collections.abc.AsyncGenerator, (T_co, T_contra))
1615Type = _alias(type, CT_co, inst=False)
1616Type.__doc__ = \
1617 """A special construct usable to annotate class objects.
Guido van Rossum62fe1bb2016-10-29 16:05:26 -07001618
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001619 For example, suppose we have the following classes::
Guido van Rossum62fe1bb2016-10-29 16:05:26 -07001620
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001621 class User: ... # Abstract base for User classes
1622 class BasicUser(User): ...
1623 class ProUser(User): ...
1624 class TeamUser(User): ...
Guido van Rossumf17c2002015-12-03 17:31:24 -08001625
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001626 And a function that takes a class argument that's a subclass of
1627 User and returns an instance of the corresponding class::
Guido van Rossumf17c2002015-12-03 17:31:24 -08001628
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001629 U = TypeVar('U', bound=User)
1630 def new_user(user_class: Type[U]) -> U:
1631 user = user_class()
1632 # (Here we could write the user object to a database)
1633 return user
Guido van Rossumf17c2002015-12-03 17:31:24 -08001634
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001635 joe = new_user(BasicUser)
Guido van Rossumf17c2002015-12-03 17:31:24 -08001636
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001637 At this point the type checker knows that joe has type BasicUser.
1638 """
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001639
1640
Ivan Levkivskyi74d7f762019-05-28 08:40:15 +01001641@runtime_checkable
1642class SupportsInt(Protocol):
Serhiy Storchaka8252c522019-10-08 16:30:17 +03001643 """An ABC with one abstract method __int__."""
Guido van Rossumd70fe632015-08-05 12:11:06 +02001644 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001645
1646 @abstractmethod
1647 def __int__(self) -> int:
1648 pass
1649
1650
Ivan Levkivskyi74d7f762019-05-28 08:40:15 +01001651@runtime_checkable
1652class SupportsFloat(Protocol):
Serhiy Storchaka8252c522019-10-08 16:30:17 +03001653 """An ABC with one abstract method __float__."""
Guido van Rossumd70fe632015-08-05 12:11:06 +02001654 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001655
1656 @abstractmethod
1657 def __float__(self) -> float:
1658 pass
1659
1660
Ivan Levkivskyi74d7f762019-05-28 08:40:15 +01001661@runtime_checkable
1662class SupportsComplex(Protocol):
Serhiy Storchaka8252c522019-10-08 16:30:17 +03001663 """An ABC with one abstract method __complex__."""
Guido van Rossumd70fe632015-08-05 12:11:06 +02001664 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001665
1666 @abstractmethod
1667 def __complex__(self) -> complex:
1668 pass
1669
1670
Ivan Levkivskyi74d7f762019-05-28 08:40:15 +01001671@runtime_checkable
1672class SupportsBytes(Protocol):
Serhiy Storchaka8252c522019-10-08 16:30:17 +03001673 """An ABC with one abstract method __bytes__."""
Guido van Rossumd70fe632015-08-05 12:11:06 +02001674 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001675
1676 @abstractmethod
1677 def __bytes__(self) -> bytes:
1678 pass
1679
1680
Ivan Levkivskyi74d7f762019-05-28 08:40:15 +01001681@runtime_checkable
1682class SupportsIndex(Protocol):
Serhiy Storchaka8252c522019-10-08 16:30:17 +03001683 """An ABC with one abstract method __index__."""
Paul Dagnelie4c7a46e2019-05-22 07:23:01 -07001684 __slots__ = ()
1685
1686 @abstractmethod
1687 def __index__(self) -> int:
1688 pass
1689
1690
Ivan Levkivskyi74d7f762019-05-28 08:40:15 +01001691@runtime_checkable
1692class SupportsAbs(Protocol[T_co]):
Serhiy Storchaka8252c522019-10-08 16:30:17 +03001693 """An ABC with one abstract method __abs__ that is covariant in its return type."""
Guido van Rossumd70fe632015-08-05 12:11:06 +02001694 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001695
1696 @abstractmethod
Guido van Rossumd70fe632015-08-05 12:11:06 +02001697 def __abs__(self) -> T_co:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001698 pass
1699
1700
Ivan Levkivskyi74d7f762019-05-28 08:40:15 +01001701@runtime_checkable
1702class SupportsRound(Protocol[T_co]):
Serhiy Storchaka8252c522019-10-08 16:30:17 +03001703 """An ABC with one abstract method __round__ that is covariant in its return type."""
Guido van Rossumd70fe632015-08-05 12:11:06 +02001704 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001705
1706 @abstractmethod
Guido van Rossumd70fe632015-08-05 12:11:06 +02001707 def __round__(self, ndigits: int = 0) -> T_co:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001708 pass
1709
1710
Serhiy Storchakaa2ec0692020-04-08 10:59:04 +03001711def _make_nmtuple(name, types, module, defaults = ()):
1712 fields = [n for n, t in types]
1713 types = {n: _type_check(t, f"field {n} annotation must be a type")
1714 for n, t in types}
1715 nm_tpl = collections.namedtuple(name, fields,
1716 defaults=defaults, module=module)
1717 nm_tpl.__annotations__ = nm_tpl.__new__.__annotations__ = types
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001718 return nm_tpl
1719
1720
Ivan Levkivskyib692dc82017-02-13 22:50:14 +01001721# attributes prohibited to set in NamedTuple class syntax
Serhiy Storchakaa2ec0692020-04-08 10:59:04 +03001722_prohibited = frozenset({'__new__', '__init__', '__slots__', '__getnewargs__',
1723 '_fields', '_field_defaults',
1724 '_make', '_replace', '_asdict', '_source'})
Ivan Levkivskyib692dc82017-02-13 22:50:14 +01001725
Serhiy Storchakaa2ec0692020-04-08 10:59:04 +03001726_special = frozenset({'__module__', '__name__', '__annotations__'})
Ivan Levkivskyib692dc82017-02-13 22:50:14 +01001727
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001728
Guido van Rossum2f841442016-11-15 09:48:06 -08001729class NamedTupleMeta(type):
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001730
Guido van Rossum2f841442016-11-15 09:48:06 -08001731 def __new__(cls, typename, bases, ns):
Serhiy Storchakaa2ec0692020-04-08 10:59:04 +03001732 assert bases[0] is _NamedTuple
Guido van Rossum2f841442016-11-15 09:48:06 -08001733 types = ns.get('__annotations__', {})
Serhiy Storchakaa2ec0692020-04-08 10:59:04 +03001734 default_names = []
Guido van Rossum3c268be2017-01-18 08:03:50 -08001735 for field_name in types:
1736 if field_name in ns:
Serhiy Storchakaa2ec0692020-04-08 10:59:04 +03001737 default_names.append(field_name)
1738 elif default_names:
1739 raise TypeError(f"Non-default namedtuple field {field_name} "
1740 f"cannot follow default field"
1741 f"{'s' if len(default_names) > 1 else ''} "
1742 f"{', '.join(default_names)}")
1743 nm_tpl = _make_nmtuple(typename, types.items(),
1744 defaults=[ns[n] for n in default_names],
1745 module=ns['__module__'])
Guido van Rossum95919c02017-01-22 17:47:20 -08001746 # update from user namespace without overriding special namedtuple attributes
1747 for key in ns:
Ivan Levkivskyib692dc82017-02-13 22:50:14 +01001748 if key in _prohibited:
1749 raise AttributeError("Cannot overwrite NamedTuple attribute " + key)
1750 elif key not in _special and key not in nm_tpl._fields:
Guido van Rossum95919c02017-01-22 17:47:20 -08001751 setattr(nm_tpl, key, ns[key])
Guido van Rossum3c268be2017-01-18 08:03:50 -08001752 return nm_tpl
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001753
Guido van Rossumd7adfe12017-01-22 17:43:53 -08001754
Serhiy Storchakaa2ec0692020-04-08 10:59:04 +03001755def NamedTuple(typename, fields=None, /, **kwargs):
Guido van Rossum2f841442016-11-15 09:48:06 -08001756 """Typed version of namedtuple.
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001757
Guido van Rossum2f841442016-11-15 09:48:06 -08001758 Usage in Python versions >= 3.6::
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001759
Guido van Rossum2f841442016-11-15 09:48:06 -08001760 class Employee(NamedTuple):
1761 name: str
1762 id: int
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001763
Guido van Rossum2f841442016-11-15 09:48:06 -08001764 This is equivalent to::
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001765
Guido van Rossum2f841442016-11-15 09:48:06 -08001766 Employee = collections.namedtuple('Employee', ['name', 'id'])
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001767
Raymond Hettingerf7b57df2019-03-18 09:53:56 -07001768 The resulting class has an extra __annotations__ attribute, giving a
1769 dict that maps field names to types. (The field names are also in
1770 the _fields attribute, which is part of the namedtuple API.)
1771 Alternative equivalent keyword syntax is also accepted::
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001772
Guido van Rossum2f841442016-11-15 09:48:06 -08001773 Employee = NamedTuple('Employee', name=str, id=int)
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001774
Guido van Rossum2f841442016-11-15 09:48:06 -08001775 In Python versions <= 3.5 use::
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001776
Guido van Rossum2f841442016-11-15 09:48:06 -08001777 Employee = NamedTuple('Employee', [('name', str), ('id', int)])
1778 """
Serhiy Storchakaa2ec0692020-04-08 10:59:04 +03001779 if fields is None:
1780 fields = kwargs.items()
1781 elif kwargs:
1782 raise TypeError("Either list of fields or keywords"
1783 " can be provided to NamedTuple, not both")
1784 try:
1785 module = sys._getframe(1).f_globals.get('__name__', '__main__')
1786 except (AttributeError, ValueError):
1787 module = None
1788 return _make_nmtuple(typename, fields, module=module)
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001789
Serhiy Storchakaa2ec0692020-04-08 10:59:04 +03001790_NamedTuple = type.__new__(NamedTupleMeta, 'NamedTuple', (), {})
1791
1792def _namedtuple_mro_entries(bases):
1793 if len(bases) > 1:
1794 raise TypeError("Multiple inheritance with NamedTuple is not supported")
1795 assert bases[0] is NamedTuple
1796 return (_NamedTuple,)
1797
1798NamedTuple.__mro_entries__ = _namedtuple_mro_entries
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001799
1800
Ivan Levkivskyi135c6a52019-05-26 09:39:24 +01001801class _TypedDictMeta(type):
1802 def __new__(cls, name, bases, ns, total=True):
1803 """Create new typed dict class object.
1804
Serhiy Storchakaf228bf22020-04-08 11:03:27 +03001805 This method is called when TypedDict is subclassed,
1806 or when TypedDict is instantiated. This way
Ivan Levkivskyi135c6a52019-05-26 09:39:24 +01001807 TypedDict supports all three syntax forms described in its docstring.
Serhiy Storchakaf228bf22020-04-08 11:03:27 +03001808 Subclasses and instances of TypedDict return actual dictionaries.
Ivan Levkivskyi135c6a52019-05-26 09:39:24 +01001809 """
Serhiy Storchakaf228bf22020-04-08 11:03:27 +03001810 for base in bases:
1811 if type(base) is not _TypedDictMeta:
1812 raise TypeError('cannot inherit from both a TypedDict type '
1813 'and a non-TypedDict base class')
1814 tp_dict = type.__new__(_TypedDictMeta, name, (dict,), ns)
Ivan Levkivskyi135c6a52019-05-26 09:39:24 +01001815
Vlad Emelianov10e87e52020-02-13 20:53:29 +01001816 annotations = {}
1817 own_annotations = ns.get('__annotations__', {})
1818 own_annotation_keys = set(own_annotations.keys())
Ivan Levkivskyi135c6a52019-05-26 09:39:24 +01001819 msg = "TypedDict('Name', {f0: t0, f1: t1, ...}); each t must be a type"
Vlad Emelianov10e87e52020-02-13 20:53:29 +01001820 own_annotations = {
1821 n: _type_check(tp, msg) for n, tp in own_annotations.items()
1822 }
1823 required_keys = set()
1824 optional_keys = set()
Zac Hatfield-Dodds665ad3d2019-11-24 21:48:48 +11001825
Ivan Levkivskyi135c6a52019-05-26 09:39:24 +01001826 for base in bases:
Vlad Emelianov10e87e52020-02-13 20:53:29 +01001827 annotations.update(base.__dict__.get('__annotations__', {}))
1828 required_keys.update(base.__dict__.get('__required_keys__', ()))
1829 optional_keys.update(base.__dict__.get('__optional_keys__', ()))
Zac Hatfield-Dodds665ad3d2019-11-24 21:48:48 +11001830
Vlad Emelianov10e87e52020-02-13 20:53:29 +01001831 annotations.update(own_annotations)
1832 if total:
1833 required_keys.update(own_annotation_keys)
1834 else:
1835 optional_keys.update(own_annotation_keys)
1836
1837 tp_dict.__annotations__ = annotations
1838 tp_dict.__required_keys__ = frozenset(required_keys)
1839 tp_dict.__optional_keys__ = frozenset(optional_keys)
Ivan Levkivskyi135c6a52019-05-26 09:39:24 +01001840 if not hasattr(tp_dict, '__total__'):
1841 tp_dict.__total__ = total
1842 return tp_dict
1843
Serhiy Storchakaf228bf22020-04-08 11:03:27 +03001844 __call__ = dict # static method
1845
1846 def __subclasscheck__(cls, other):
1847 # Typed dicts are only for static structural subtyping.
1848 raise TypeError('TypedDict does not support instance and class checks')
1849
1850 __instancecheck__ = __subclasscheck__
Ivan Levkivskyi135c6a52019-05-26 09:39:24 +01001851
1852
Serhiy Storchakaf228bf22020-04-08 11:03:27 +03001853def TypedDict(typename, fields=None, /, *, total=True, **kwargs):
Ivan Levkivskyi135c6a52019-05-26 09:39:24 +01001854 """A simple typed namespace. At runtime it is equivalent to a plain dict.
1855
1856 TypedDict creates a dictionary type that expects all of its
1857 instances to have a certain set of keys, where each key is
1858 associated with a value of a consistent type. This expectation
1859 is not checked at runtime but is only enforced by type checkers.
1860 Usage::
1861
1862 class Point2D(TypedDict):
1863 x: int
1864 y: int
1865 label: str
1866
1867 a: Point2D = {'x': 1, 'y': 2, 'label': 'good'} # OK
1868 b: Point2D = {'z': 3, 'label': 'bad'} # Fails type check
1869
1870 assert Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first')
1871
Zac Hatfield-Dodds665ad3d2019-11-24 21:48:48 +11001872 The type info can be accessed via the Point2D.__annotations__ dict, and
1873 the Point2D.__required_keys__ and Point2D.__optional_keys__ frozensets.
1874 TypedDict supports two additional equivalent forms::
Ivan Levkivskyi135c6a52019-05-26 09:39:24 +01001875
1876 Point2D = TypedDict('Point2D', x=int, y=int, label=str)
1877 Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str})
1878
ananthan-123ab6423f2020-02-19 10:03:05 +05301879 By default, all keys must be present in a TypedDict. It is possible
1880 to override this by specifying totality.
1881 Usage::
1882
1883 class point2D(TypedDict, total=False):
1884 x: int
1885 y: int
1886
1887 This means that a point2D TypedDict can have any of the keys omitted.A type
1888 checker is only expected to support a literal False or True as the value of
1889 the total argument. True is the default, and makes all items defined in the
1890 class body be required.
1891
Ivan Levkivskyi135c6a52019-05-26 09:39:24 +01001892 The class syntax is only supported in Python 3.6+, while two other
1893 syntax forms work for Python 2.7 and 3.2+
1894 """
Serhiy Storchakaf228bf22020-04-08 11:03:27 +03001895 if fields is None:
1896 fields = kwargs
1897 elif kwargs:
1898 raise TypeError("TypedDict takes either a dict or keyword arguments,"
1899 " but not both")
1900
1901 ns = {'__annotations__': dict(fields), '__total__': total}
1902 try:
1903 # Setting correct module is necessary to make typed dict classes pickleable.
1904 ns['__module__'] = sys._getframe(1).f_globals.get('__name__', '__main__')
1905 except (AttributeError, ValueError):
1906 pass
1907
1908 return _TypedDictMeta(typename, (), ns)
1909
1910_TypedDict = type.__new__(_TypedDictMeta, 'TypedDict', (), {})
1911TypedDict.__mro_entries__ = lambda bases: (_TypedDict,)
Ivan Levkivskyi135c6a52019-05-26 09:39:24 +01001912
1913
Guido van Rossum91185fe2016-06-08 11:19:11 -07001914def NewType(name, tp):
1915 """NewType creates simple unique types with almost zero
1916 runtime overhead. NewType(name, tp) is considered a subtype of tp
1917 by static type checkers. At runtime, NewType(name, tp) returns
1918 a dummy function that simply returns its argument. Usage::
1919
1920 UserId = NewType('UserId', int)
1921
1922 def name_by_id(user_id: UserId) -> str:
1923 ...
1924
1925 UserId('user') # Fails type check
1926
1927 name_by_id(42) # Fails type check
1928 name_by_id(UserId(42)) # OK
1929
1930 num = UserId(5) + 1 # type: int
1931 """
1932
1933 def new_type(x):
1934 return x
1935
1936 new_type.__name__ = name
1937 new_type.__supertype__ = tp
1938 return new_type
1939
1940
Guido van Rossum0e0563c2016-04-05 14:54:25 -07001941# Python-version-specific alias (Python 2: unicode; Python 3: str)
1942Text = str
1943
1944
Guido van Rossum91185fe2016-06-08 11:19:11 -07001945# Constant that's True when type checking, but False here.
1946TYPE_CHECKING = False
1947
1948
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001949class IO(Generic[AnyStr]):
1950 """Generic base class for TextIO and BinaryIO.
1951
1952 This is an abstract, generic version of the return of open().
1953
1954 NOTE: This does not distinguish between the different possible
1955 classes (text vs. binary, read vs. write vs. read/write,
1956 append-only, unbuffered). The TextIO and BinaryIO subclasses
1957 below capture the distinctions between text vs. binary, which is
1958 pervasive in the interface; however we currently do not offer a
1959 way to track the other distinctions in the type system.
1960 """
1961
Guido van Rossumd70fe632015-08-05 12:11:06 +02001962 __slots__ = ()
1963
HongWeipeng6ce03ec2019-09-27 15:54:26 +08001964 @property
1965 @abstractmethod
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001966 def mode(self) -> str:
1967 pass
1968
HongWeipeng6ce03ec2019-09-27 15:54:26 +08001969 @property
1970 @abstractmethod
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001971 def name(self) -> str:
1972 pass
1973
1974 @abstractmethod
1975 def close(self) -> None:
1976 pass
1977
Shantanu2e6569b2020-01-29 18:52:36 -08001978 @property
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001979 @abstractmethod
1980 def closed(self) -> bool:
1981 pass
1982
1983 @abstractmethod
1984 def fileno(self) -> int:
1985 pass
1986
1987 @abstractmethod
1988 def flush(self) -> None:
1989 pass
1990
1991 @abstractmethod
1992 def isatty(self) -> bool:
1993 pass
1994
1995 @abstractmethod
1996 def read(self, n: int = -1) -> AnyStr:
1997 pass
1998
1999 @abstractmethod
2000 def readable(self) -> bool:
2001 pass
2002
2003 @abstractmethod
2004 def readline(self, limit: int = -1) -> AnyStr:
2005 pass
2006
2007 @abstractmethod
2008 def readlines(self, hint: int = -1) -> List[AnyStr]:
2009 pass
2010
2011 @abstractmethod
2012 def seek(self, offset: int, whence: int = 0) -> int:
2013 pass
2014
2015 @abstractmethod
2016 def seekable(self) -> bool:
2017 pass
2018
2019 @abstractmethod
2020 def tell(self) -> int:
2021 pass
2022
2023 @abstractmethod
2024 def truncate(self, size: int = None) -> int:
2025 pass
2026
2027 @abstractmethod
2028 def writable(self) -> bool:
2029 pass
2030
2031 @abstractmethod
2032 def write(self, s: AnyStr) -> int:
2033 pass
2034
2035 @abstractmethod
2036 def writelines(self, lines: List[AnyStr]) -> None:
2037 pass
2038
2039 @abstractmethod
2040 def __enter__(self) -> 'IO[AnyStr]':
2041 pass
2042
2043 @abstractmethod
2044 def __exit__(self, type, value, traceback) -> None:
2045 pass
2046
2047
2048class BinaryIO(IO[bytes]):
2049 """Typed version of the return of open() in binary mode."""
2050
Guido van Rossumd70fe632015-08-05 12:11:06 +02002051 __slots__ = ()
2052
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07002053 @abstractmethod
2054 def write(self, s: Union[bytes, bytearray]) -> int:
2055 pass
2056
2057 @abstractmethod
2058 def __enter__(self) -> 'BinaryIO':
2059 pass
2060
2061
2062class TextIO(IO[str]):
2063 """Typed version of the return of open() in text mode."""
2064
Guido van Rossumd70fe632015-08-05 12:11:06 +02002065 __slots__ = ()
2066
HongWeipeng6ce03ec2019-09-27 15:54:26 +08002067 @property
2068 @abstractmethod
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07002069 def buffer(self) -> BinaryIO:
2070 pass
2071
HongWeipeng6ce03ec2019-09-27 15:54:26 +08002072 @property
2073 @abstractmethod
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07002074 def encoding(self) -> str:
2075 pass
2076
HongWeipeng6ce03ec2019-09-27 15:54:26 +08002077 @property
2078 @abstractmethod
Guido van Rossum991d14f2016-11-09 13:12:51 -08002079 def errors(self) -> Optional[str]:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07002080 pass
2081
HongWeipeng6ce03ec2019-09-27 15:54:26 +08002082 @property
2083 @abstractmethod
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07002084 def line_buffering(self) -> bool:
2085 pass
2086
HongWeipeng6ce03ec2019-09-27 15:54:26 +08002087 @property
2088 @abstractmethod
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07002089 def newlines(self) -> Any:
2090 pass
2091
2092 @abstractmethod
2093 def __enter__(self) -> 'TextIO':
2094 pass
2095
2096
2097class io:
2098 """Wrapper namespace for IO generic classes."""
2099
2100 __all__ = ['IO', 'TextIO', 'BinaryIO']
2101 IO = IO
2102 TextIO = TextIO
2103 BinaryIO = BinaryIO
2104
Guido van Rossumd7adfe12017-01-22 17:43:53 -08002105
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07002106io.__name__ = __name__ + '.io'
2107sys.modules[io.__name__] = io
2108
Ivan Levkivskyid911e402018-01-20 11:23:59 +00002109Pattern = _alias(stdlib_re.Pattern, AnyStr)
2110Match = _alias(stdlib_re.Match, AnyStr)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07002111
2112class re:
2113 """Wrapper namespace for re type aliases."""
2114
2115 __all__ = ['Pattern', 'Match']
2116 Pattern = Pattern
2117 Match = Match
2118
Guido van Rossumd7adfe12017-01-22 17:43:53 -08002119
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07002120re.__name__ = __name__ + '.re'
2121sys.modules[re.__name__] = re