blob: 3243e2af1119d353212a9e839dbbd5535d850c11 [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.
12* The public counterpart of the generics API consists of two classes: Generic and Protocol
13 (the latter is currently private, but will be made public after PEP 544 acceptance).
14* Public helper functions: get_type_hints, overload, cast, no_type_check,
15 no_type_check_decorator.
16* Generic aliases for collections.abc ABCs and few additional protocols.
17* Special types: NewType, NamedTuple, TypedDict (may be added soon).
18* Wrapper submodules for re and io related types.
19"""
20
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070021from abc import abstractmethod, abstractproperty
22import collections
Ivan Levkivskyid911e402018-01-20 11:23:59 +000023import collections.abc
Brett Cannonf3ad0422016-04-15 10:51:30 -070024import contextlib
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070025import functools
Serhiy Storchaka09f32212018-05-26 21:19:26 +030026import operator
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070027import re as stdlib_re # Avoid confusion with the re we export.
28import sys
29import types
Ivan Levkivskyid911e402018-01-20 11:23:59 +000030from types import WrapperDescriptorType, MethodWrapperType, MethodDescriptorType
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070031
32# Please keep __all__ alphabetized within each category.
33__all__ = [
34 # Super-special typing primitives.
35 'Any',
36 'Callable',
Guido van Rossum0a6976d2016-09-11 15:34:56 -070037 'ClassVar',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070038 'Generic',
39 'Optional',
Guido van Rossumeb9aca32016-05-24 16:38:22 -070040 'Tuple',
41 'Type',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070042 'TypeVar',
43 'Union',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070044
45 # ABCs (from collections.abc).
46 'AbstractSet', # collections.abc.Set.
47 'ByteString',
48 'Container',
Ivan Levkivskyi29fda8d2017-06-10 21:57:56 +020049 'ContextManager',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070050 'Hashable',
51 'ItemsView',
52 'Iterable',
53 'Iterator',
54 'KeysView',
55 'Mapping',
56 'MappingView',
57 'MutableMapping',
58 'MutableSequence',
59 'MutableSet',
60 'Sequence',
61 'Sized',
62 'ValuesView',
Ivan Levkivskyid911e402018-01-20 11:23:59 +000063 'Awaitable',
64 'AsyncIterator',
65 'AsyncIterable',
66 'Coroutine',
67 'Collection',
68 'AsyncGenerator',
69 'AsyncContextManager',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070070
71 # Structural checks, a.k.a. protocols.
72 'Reversible',
73 'SupportsAbs',
Ivan Levkivskyif06e0212017-05-02 19:14:07 +020074 'SupportsBytes',
75 'SupportsComplex',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070076 'SupportsFloat',
77 'SupportsInt',
78 'SupportsRound',
79
80 # Concrete collection types.
Ivan Levkivskyib692dc82017-02-13 22:50:14 +010081 'Counter',
Raymond Hettinger80490522017-01-16 22:42:37 -080082 'Deque',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070083 'Dict',
Guido van Rossumbd5b9a02016-04-05 08:28:52 -070084 'DefaultDict',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070085 'List',
86 'Set',
Guido van Rossumefa798d2016-08-23 11:01:50 -070087 'FrozenSet',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070088 'NamedTuple', # Not really a type.
89 'Generator',
90
91 # One-off things.
92 'AnyStr',
93 'cast',
94 'get_type_hints',
Guido van Rossum91185fe2016-06-08 11:19:11 -070095 'NewType',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070096 'no_type_check',
97 'no_type_check_decorator',
aetracht45738202018-03-19 14:41:32 -040098 'NoReturn',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070099 'overload',
Guido van Rossum0e0563c2016-04-05 14:54:25 -0700100 'Text',
Guido van Rossum91185fe2016-06-08 11:19:11 -0700101 'TYPE_CHECKING',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700102]
103
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700104# The pseudo-submodules 're' and 'io' are part of the public
105# namespace, but excluded from __all__ because they might stomp on
106# legitimate imports of those modules.
107
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700108
Nina Zakharenko0e61dff2018-05-22 20:32:10 -0700109def _type_check(arg, msg, is_argument=True):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000110 """Check that the argument is a type, and return it (internal helper).
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700111
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000112 As a special case, accept None and return type(None) instead. Also wrap strings
113 into ForwardRef instances. Consider several corner cases, for example plain
114 special forms like Union are not valid, while Union[int, str] is OK, etc.
115 The msg argument is a human-readable error message, e.g::
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700116
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000117 "Union[arg, ...]: arg should be a type."
Guido van Rossum4cefe742016-09-27 15:20:12 -0700118
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000119 We append the repr() of the actual value (truncated to 100 chars).
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700120 """
Nina Zakharenko2d2d3b12018-05-16 12:27:03 -0400121 invalid_generic_forms = (Generic, _Protocol)
Nina Zakharenko0e61dff2018-05-22 20:32:10 -0700122 if is_argument:
Nina Zakharenko2d2d3b12018-05-16 12:27:03 -0400123 invalid_generic_forms = invalid_generic_forms + (ClassVar, )
124
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000125 if arg is None:
126 return type(None)
127 if isinstance(arg, str):
128 return ForwardRef(arg)
129 if (isinstance(arg, _GenericAlias) and
Nina Zakharenko2d2d3b12018-05-16 12:27:03 -0400130 arg.__origin__ in invalid_generic_forms):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000131 raise TypeError(f"{arg} is not valid as type argument")
Noah Wood5eea0ad2018-10-08 14:50:16 -0400132 if (isinstance(arg, _SpecialForm) and arg not in (Any, NoReturn) or
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000133 arg in (Generic, _Protocol)):
134 raise TypeError(f"Plain {arg} is not valid as type argument")
135 if isinstance(arg, (type, TypeVar, ForwardRef)):
136 return arg
137 if not callable(arg):
138 raise TypeError(f"{msg} Got {arg!r:.100}.")
139 return arg
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700140
141
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000142def _type_repr(obj):
143 """Return the repr() of an object, special-casing types (internal helper).
144
145 If obj is a type, we return a shorter version than the default
146 type.__repr__, based on the module and qualified name, which is
147 typically enough to uniquely identify a type. For everything
148 else, we fall back on repr(obj).
149 """
150 if isinstance(obj, type):
151 if obj.__module__ == 'builtins':
152 return obj.__qualname__
153 return f'{obj.__module__}.{obj.__qualname__}'
154 if obj is ...:
155 return('...')
156 if isinstance(obj, types.FunctionType):
157 return obj.__name__
158 return repr(obj)
159
160
161def _collect_type_vars(types):
162 """Collect all type variable contained in types in order of
163 first appearance (lexicographic order). For example::
164
165 _collect_type_vars((T, List[S, T])) == (T, S)
166 """
167 tvars = []
168 for t in types:
169 if isinstance(t, TypeVar) and t not in tvars:
170 tvars.append(t)
171 if isinstance(t, _GenericAlias) and not t._special:
172 tvars.extend([t for t in t.__parameters__ if t not in tvars])
173 return tuple(tvars)
174
175
176def _subs_tvars(tp, tvars, subs):
177 """Substitute type variables 'tvars' with substitutions 'subs'.
178 These two must have the same length.
179 """
180 if not isinstance(tp, _GenericAlias):
181 return tp
182 new_args = list(tp.__args__)
183 for a, arg in enumerate(tp.__args__):
184 if isinstance(arg, TypeVar):
185 for i, tvar in enumerate(tvars):
186 if arg == tvar:
187 new_args[a] = subs[i]
188 else:
189 new_args[a] = _subs_tvars(arg, tvars, subs)
190 if tp.__origin__ is Union:
191 return Union[tuple(new_args)]
192 return tp.copy_with(tuple(new_args))
193
194
195def _check_generic(cls, parameters):
196 """Check correct count for parameters of a generic cls (internal helper).
197 This gives a nice error message in case of count mismatch.
198 """
199 if not cls.__parameters__:
200 raise TypeError(f"{cls} is not a generic class")
201 alen = len(parameters)
202 elen = len(cls.__parameters__)
203 if alen != elen:
204 raise TypeError(f"Too {'many' if alen > elen else 'few'} parameters for {cls};"
205 f" actual {alen}, expected {elen}")
206
207
208def _remove_dups_flatten(parameters):
Ivan Levkivskyif65e31f2018-05-18 16:00:38 -0700209 """An internal helper for Union creation and substitution: flatten Unions
210 among parameters, then remove duplicates.
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000211 """
212 # Flatten out Union[Union[...], ...].
213 params = []
214 for p in parameters:
215 if isinstance(p, _GenericAlias) and p.__origin__ is Union:
216 params.extend(p.__args__)
217 elif isinstance(p, tuple) and len(p) > 0 and p[0] is Union:
218 params.extend(p[1:])
219 else:
220 params.append(p)
221 # Weed out strict duplicates, preserving the first of each occurrence.
222 all_params = set(params)
223 if len(all_params) < len(params):
224 new_params = []
225 for t in params:
226 if t in all_params:
227 new_params.append(t)
228 all_params.remove(t)
229 params = new_params
230 assert not all_params, all_params
Ivan Levkivskyif65e31f2018-05-18 16:00:38 -0700231 return tuple(params)
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000232
233
234_cleanups = []
235
236
237def _tp_cache(func):
238 """Internal wrapper caching __getitem__ of generic types with a fallback to
239 original function for non-hashable arguments.
240 """
241 cached = functools.lru_cache()(func)
242 _cleanups.append(cached.cache_clear)
243
244 @functools.wraps(func)
245 def inner(*args, **kwds):
246 try:
247 return cached(*args, **kwds)
248 except TypeError:
249 pass # All real errors (not unhashable args) are raised below.
250 return func(*args, **kwds)
251 return inner
252
253
254def _eval_type(t, globalns, localns):
255 """Evaluate all forward reverences in the given type t.
256 For use of globalns and localns see the docstring for get_type_hints().
257 """
258 if isinstance(t, ForwardRef):
259 return t._evaluate(globalns, localns)
260 if isinstance(t, _GenericAlias):
261 ev_args = tuple(_eval_type(a, globalns, localns) for a in t.__args__)
262 if ev_args == t.__args__:
263 return t
264 res = t.copy_with(ev_args)
265 res._special = t._special
266 return res
267 return t
268
269
270class _Final:
271 """Mixin to prohibit subclassing"""
Guido van Rossum4cefe742016-09-27 15:20:12 -0700272
Guido van Rossum83ec3022017-01-17 20:43:28 -0800273 __slots__ = ('__weakref__',)
Guido van Rossum4cefe742016-09-27 15:20:12 -0700274
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000275 def __init_subclass__(self, *args, **kwds):
276 if '_root' not in kwds:
277 raise TypeError("Cannot subclass special typing classes")
278
Ivan Levkivskyi83494032018-03-26 23:01:12 +0100279class _Immutable:
280 """Mixin to indicate that object should not be copied."""
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000281
Ivan Levkivskyi83494032018-03-26 23:01:12 +0100282 def __copy__(self):
283 return self
284
285 def __deepcopy__(self, memo):
286 return self
287
288
289class _SpecialForm(_Final, _Immutable, _root=True):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000290 """Internal indicator of special typing constructs.
291 See _doc instance attribute for specific docs.
292 """
293
294 __slots__ = ('_name', '_doc')
295
Guido van Rossum4cefe742016-09-27 15:20:12 -0700296 def __new__(cls, *args, **kwds):
297 """Constructor.
298
299 This only exists to give a better error message in case
300 someone tries to subclass a special typing object (not a good idea).
301 """
302 if (len(args) == 3 and
303 isinstance(args[0], str) and
304 isinstance(args[1], tuple)):
305 # Close enough.
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000306 raise TypeError(f"Cannot subclass {cls!r}")
Guido van Rossumb47c9d22016-10-03 08:40:50 -0700307 return super().__new__(cls)
Guido van Rossum4cefe742016-09-27 15:20:12 -0700308
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000309 def __init__(self, name, doc):
310 self._name = name
311 self._doc = doc
Guido van Rossum4cefe742016-09-27 15:20:12 -0700312
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000313 def __eq__(self, other):
314 if not isinstance(other, _SpecialForm):
315 return NotImplemented
316 return self._name == other._name
317
318 def __hash__(self):
319 return hash((self._name,))
Guido van Rossum4cefe742016-09-27 15:20:12 -0700320
321 def __repr__(self):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000322 return 'typing.' + self._name
323
Ivan Levkivskyi83494032018-03-26 23:01:12 +0100324 def __reduce__(self):
325 return self._name
Guido van Rossum4cefe742016-09-27 15:20:12 -0700326
327 def __call__(self, *args, **kwds):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000328 raise TypeError(f"Cannot instantiate {self!r}")
329
330 def __instancecheck__(self, obj):
331 raise TypeError(f"{self} cannot be used with isinstance()")
332
333 def __subclasscheck__(self, cls):
334 raise TypeError(f"{self} cannot be used with issubclass()")
335
336 @_tp_cache
337 def __getitem__(self, parameters):
338 if self._name == 'ClassVar':
339 item = _type_check(parameters, 'ClassVar accepts only single type.')
340 return _GenericAlias(self, (item,))
341 if self._name == 'Union':
342 if parameters == ():
343 raise TypeError("Cannot take a Union of no types.")
344 if not isinstance(parameters, tuple):
345 parameters = (parameters,)
346 msg = "Union[arg, ...]: each arg must be a type."
347 parameters = tuple(_type_check(p, msg) for p in parameters)
348 parameters = _remove_dups_flatten(parameters)
349 if len(parameters) == 1:
350 return parameters[0]
351 return _GenericAlias(self, parameters)
352 if self._name == 'Optional':
353 arg = _type_check(parameters, "Optional[t] requires a single type.")
354 return Union[arg, type(None)]
355 raise TypeError(f"{self} is not subscriptable")
Guido van Rossum4cefe742016-09-27 15:20:12 -0700356
357
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000358Any = _SpecialForm('Any', doc=
359 """Special type indicating an unconstrained type.
Guido van Rossumb47c9d22016-10-03 08:40:50 -0700360
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000361 - Any is compatible with every type.
362 - Any assumed to have all methods.
363 - All values assumed to be instances of Any.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700364
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000365 Note that all the above statements are true from the point of view of
366 static type checkers. At runtime, Any should not be used with instance
367 or class checks.
368 """)
Guido van Rossumd70fe632015-08-05 12:11:06 +0200369
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000370NoReturn = _SpecialForm('NoReturn', doc=
371 """Special type indicating functions that never return.
372 Example::
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700373
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000374 from typing import NoReturn
375
376 def stop() -> NoReturn:
377 raise Exception('no way')
378
379 This type is invalid in other positions, e.g., ``List[NoReturn]``
380 will fail in static type checkers.
381 """)
382
383ClassVar = _SpecialForm('ClassVar', doc=
384 """Special type construct to mark class variables.
385
386 An annotation wrapped in ClassVar indicates that a given
387 attribute is intended to be used as a class variable and
388 should not be set on instances of that class. Usage::
389
390 class Starship:
391 stats: ClassVar[Dict[str, int]] = {} # class variable
392 damage: int = 10 # instance variable
393
394 ClassVar accepts only types and cannot be further subscribed.
395
396 Note that ClassVar is not a class itself, and should not
397 be used with isinstance() or issubclass().
398 """)
399
400Union = _SpecialForm('Union', doc=
401 """Union type; Union[X, Y] means either X or Y.
402
403 To define a union, use e.g. Union[int, str]. Details:
404 - The arguments must be types and there must be at least one.
405 - None as an argument is a special case and is replaced by
406 type(None).
407 - Unions of unions are flattened, e.g.::
408
409 Union[Union[int, str], float] == Union[int, str, float]
410
411 - Unions of a single argument vanish, e.g.::
412
413 Union[int] == int # The constructor actually returns int
414
415 - Redundant arguments are skipped, e.g.::
416
417 Union[int, str, int] == Union[int, str]
418
419 - When comparing unions, the argument order is ignored, e.g.::
420
421 Union[int, str] == Union[str, int]
422
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000423 - You cannot subclass or instantiate a union.
424 - You can use Optional[X] as a shorthand for Union[X, None].
425 """)
426
427Optional = _SpecialForm('Optional', doc=
428 """Optional type.
429
430 Optional[X] is equivalent to Union[X, None].
431 """)
Guido van Rossumb7dedc82016-10-29 12:44:29 -0700432
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700433
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000434class ForwardRef(_Final, _root=True):
Guido van Rossumb24569a2016-11-20 18:01:29 -0800435 """Internal wrapper to hold a forward reference."""
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700436
Guido van Rossum4cefe742016-09-27 15:20:12 -0700437 __slots__ = ('__forward_arg__', '__forward_code__',
Nina Zakharenko2d2d3b12018-05-16 12:27:03 -0400438 '__forward_evaluated__', '__forward_value__',
439 '__forward_is_argument__')
Guido van Rossum4cefe742016-09-27 15:20:12 -0700440
Nina Zakharenko0e61dff2018-05-22 20:32:10 -0700441 def __init__(self, arg, is_argument=True):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700442 if not isinstance(arg, str):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000443 raise TypeError(f"Forward reference must be a string -- got {arg!r}")
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700444 try:
445 code = compile(arg, '<string>', 'eval')
446 except SyntaxError:
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000447 raise SyntaxError(f"Forward reference must be an expression -- got {arg!r}")
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700448 self.__forward_arg__ = arg
449 self.__forward_code__ = code
450 self.__forward_evaluated__ = False
451 self.__forward_value__ = None
Nina Zakharenko2d2d3b12018-05-16 12:27:03 -0400452 self.__forward_is_argument__ = is_argument
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700453
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000454 def _evaluate(self, globalns, localns):
Guido van Rossumdad17902016-11-10 08:29:18 -0800455 if not self.__forward_evaluated__ or localns is not globalns:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700456 if globalns is None and localns is None:
457 globalns = localns = {}
458 elif globalns is None:
459 globalns = localns
460 elif localns is None:
461 localns = globalns
462 self.__forward_value__ = _type_check(
463 eval(self.__forward_code__, globalns, localns),
Nina Zakharenko2d2d3b12018-05-16 12:27:03 -0400464 "Forward references must evaluate to types.",
465 is_argument=self.__forward_is_argument__)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700466 self.__forward_evaluated__ = True
467 return self.__forward_value__
468
Guido van Rossum4cefe742016-09-27 15:20:12 -0700469 def __eq__(self, other):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000470 if not isinstance(other, ForwardRef):
Guido van Rossum4cefe742016-09-27 15:20:12 -0700471 return NotImplemented
472 return (self.__forward_arg__ == other.__forward_arg__ and
Guido van Rossumc7b92952016-11-10 08:24:06 -0800473 self.__forward_value__ == other.__forward_value__)
Guido van Rossum4cefe742016-09-27 15:20:12 -0700474
475 def __hash__(self):
Guido van Rossumc7b92952016-11-10 08:24:06 -0800476 return hash((self.__forward_arg__, self.__forward_value__))
Guido van Rossum4cefe742016-09-27 15:20:12 -0700477
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700478 def __repr__(self):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000479 return f'ForwardRef({self.__forward_arg__!r})'
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700480
481
Ivan Levkivskyi83494032018-03-26 23:01:12 +0100482class TypeVar(_Final, _Immutable, _root=True):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700483 """Type variable.
484
485 Usage::
486
487 T = TypeVar('T') # Can be anything
488 A = TypeVar('A', str, bytes) # Must be str or bytes
489
490 Type variables exist primarily for the benefit of static type
491 checkers. They serve as the parameters for generic types as well
492 as for generic function definitions. See class Generic for more
493 information on generic types. Generic functions work as follows:
494
Guido van Rossumb24569a2016-11-20 18:01:29 -0800495 def repeat(x: T, n: int) -> List[T]:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700496 '''Return a list containing n references to x.'''
497 return [x]*n
498
499 def longest(x: A, y: A) -> A:
500 '''Return the longest of two strings.'''
501 return x if len(x) >= len(y) else y
502
503 The latter example's signature is essentially the overloading
504 of (str, str) -> str and (bytes, bytes) -> bytes. Also note
505 that if the arguments are instances of some subclass of str,
506 the return type is still plain str.
507
Guido van Rossumb24569a2016-11-20 18:01:29 -0800508 At runtime, isinstance(x, T) and issubclass(C, T) will raise TypeError.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700509
Guido van Rossumefa798d2016-08-23 11:01:50 -0700510 Type variables defined with covariant=True or contravariant=True
João D. Ferreira86bfed32018-07-07 16:41:20 +0100511 can be used to declare covariant or contravariant generic types.
Guido van Rossumefa798d2016-08-23 11:01:50 -0700512 See PEP 484 for more details. By default generic types are invariant
513 in all type variables.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700514
515 Type variables can be introspected. e.g.:
516
517 T.__name__ == 'T'
518 T.__constraints__ == ()
519 T.__covariant__ == False
520 T.__contravariant__ = False
521 A.__constraints__ == (str, bytes)
Ivan Levkivskyi83494032018-03-26 23:01:12 +0100522
523 Note that only type variables defined in global scope can be pickled.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700524 """
525
Guido van Rossum4cefe742016-09-27 15:20:12 -0700526 __slots__ = ('__name__', '__bound__', '__constraints__',
Serhiy Storchaka09f32212018-05-26 21:19:26 +0300527 '__covariant__', '__contravariant__')
Guido van Rossum4cefe742016-09-27 15:20:12 -0700528
529 def __init__(self, name, *constraints, bound=None,
Guido van Rossumd7adfe12017-01-22 17:43:53 -0800530 covariant=False, contravariant=False):
Guido van Rossum4cefe742016-09-27 15:20:12 -0700531 self.__name__ = name
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700532 if covariant and contravariant:
Guido van Rossumefa798d2016-08-23 11:01:50 -0700533 raise ValueError("Bivariant types are not supported.")
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700534 self.__covariant__ = bool(covariant)
535 self.__contravariant__ = bool(contravariant)
536 if constraints and bound is not None:
537 raise TypeError("Constraints cannot be combined with bound=...")
538 if constraints and len(constraints) == 1:
539 raise TypeError("A single constraint is not allowed")
540 msg = "TypeVar(name, constraint, ...): constraints must be types."
541 self.__constraints__ = tuple(_type_check(t, msg) for t in constraints)
542 if bound:
543 self.__bound__ = _type_check(bound, "Bound must be a type.")
544 else:
545 self.__bound__ = None
Serhiy Storchaka09f32212018-05-26 21:19:26 +0300546 def_mod = sys._getframe(1).f_globals['__name__'] # for pickling
547 if def_mod != 'typing':
548 self.__module__ = def_mod
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700549
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700550 def __repr__(self):
551 if self.__covariant__:
552 prefix = '+'
553 elif self.__contravariant__:
554 prefix = '-'
555 else:
556 prefix = '~'
557 return prefix + self.__name__
558
Ivan Levkivskyi83494032018-03-26 23:01:12 +0100559 def __reduce__(self):
Serhiy Storchaka09f32212018-05-26 21:19:26 +0300560 return self.__name__
Ivan Levkivskyi83494032018-03-26 23:01:12 +0100561
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700562
Guido van Rossum83ec3022017-01-17 20:43:28 -0800563# Special typing constructs Union, Optional, Generic, Callable and Tuple
564# use three special attributes for internal bookkeeping of generic types:
565# * __parameters__ is a tuple of unique free type parameters of a generic
566# type, for example, Dict[T, T].__parameters__ == (T,);
567# * __origin__ keeps a reference to a type that was subscripted,
Ivan Levkivskyi43d12a62018-05-09 02:23:46 +0100568# e.g., Union[T, int].__origin__ == Union, or the non-generic version of
569# the type.
Guido van Rossum83ec3022017-01-17 20:43:28 -0800570# * __args__ is a tuple of all arguments used in subscripting,
571# e.g., Dict[T, int].__args__ == (T, int).
572
Ivan Levkivskyi2a363d22018-04-05 01:25:15 +0100573
574# Mapping from non-generic type names that have a generic alias in typing
575# but with a different name.
576_normalize_alias = {'list': 'List',
577 'tuple': 'Tuple',
578 'dict': 'Dict',
579 'set': 'Set',
580 'frozenset': 'FrozenSet',
581 'deque': 'Deque',
582 'defaultdict': 'DefaultDict',
583 'type': 'Type',
584 'Set': 'AbstractSet'}
585
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000586def _is_dunder(attr):
587 return attr.startswith('__') and attr.endswith('__')
Guido van Rossum83ec3022017-01-17 20:43:28 -0800588
Guido van Rossumb24569a2016-11-20 18:01:29 -0800589
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000590class _GenericAlias(_Final, _root=True):
591 """The central part of internal API.
592
593 This represents a generic version of type 'origin' with type arguments 'params'.
594 There are two kind of these aliases: user defined and special. The special ones
595 are wrappers around builtin collections and ABCs in collections.abc. These must
596 have 'name' always set. If 'inst' is False, then the alias can't be instantiated,
597 this is used by e.g. typing.List and typing.Dict.
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700598 """
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000599 def __init__(self, origin, params, *, inst=True, special=False, name=None):
600 self._inst = inst
601 self._special = special
602 if special and name is None:
603 orig_name = origin.__name__
Ivan Levkivskyi2a363d22018-04-05 01:25:15 +0100604 name = _normalize_alias.get(orig_name, orig_name)
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000605 self._name = name
606 if not isinstance(params, tuple):
607 params = (params,)
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700608 self.__origin__ = origin
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700609 self.__args__ = tuple(... if a is _TypingEllipsis else
610 () if a is _TypingEmpty else
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000611 a for a in params)
612 self.__parameters__ = _collect_type_vars(params)
613 self.__slots__ = None # This is not documented.
614 if not name:
615 self.__module__ = origin.__module__
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700616
Guido van Rossum4cefe742016-09-27 15:20:12 -0700617 @_tp_cache
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700618 def __getitem__(self, params):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000619 if self.__origin__ in (Generic, _Protocol):
620 # Can't subscript Generic[...] or _Protocol[...].
621 raise TypeError(f"Cannot subscript already-subscripted {self}")
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700622 if not isinstance(params, tuple):
623 params = (params,)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700624 msg = "Parameters to generic types must be types."
625 params = tuple(_type_check(p, msg) for p in params)
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000626 _check_generic(self, params)
627 return _subs_tvars(self, self.__parameters__, params)
Ivan Levkivskyib692dc82017-02-13 22:50:14 +0100628
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000629 def copy_with(self, params):
630 # We don't copy self._special.
631 return _GenericAlias(self.__origin__, params, name=self._name, inst=self._inst)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700632
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000633 def __repr__(self):
634 if (self._name != 'Callable' or
635 len(self.__args__) == 2 and self.__args__[0] is Ellipsis):
636 if self._name:
637 name = 'typing.' + self._name
638 else:
639 name = _type_repr(self.__origin__)
640 if not self._special:
641 args = f'[{", ".join([_type_repr(a) for a in self.__args__])}]'
642 else:
643 args = ''
644 return (f'{name}{args}')
645 if self._special:
646 return 'typing.Callable'
647 return (f'typing.Callable'
648 f'[[{", ".join([_type_repr(a) for a in self.__args__[:-1]])}], '
649 f'{_type_repr(self.__args__[-1])}]')
650
651 def __eq__(self, other):
652 if not isinstance(other, _GenericAlias):
653 return NotImplemented
654 if self.__origin__ != other.__origin__:
Ivan Levkivskyib692dc82017-02-13 22:50:14 +0100655 return False
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000656 if self.__origin__ is Union and other.__origin__ is Union:
657 return frozenset(self.__args__) == frozenset(other.__args__)
658 return self.__args__ == other.__args__
Ivan Levkivskyib692dc82017-02-13 22:50:14 +0100659
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000660 def __hash__(self):
661 if self.__origin__ is Union:
662 return hash((Union, frozenset(self.__args__)))
663 return hash((self.__origin__, self.__args__))
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700664
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000665 def __call__(self, *args, **kwargs):
666 if not self._inst:
667 raise TypeError(f"Type {self._name} cannot be instantiated; "
668 f"use {self._name.lower()}() instead")
669 result = self.__origin__(*args, **kwargs)
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700670 try:
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000671 result.__orig_class__ = self
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700672 except AttributeError:
673 pass
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000674 return result
675
676 def __mro_entries__(self, bases):
677 if self._name: # generic version of an ABC or built-in class
678 res = []
679 if self.__origin__ not in bases:
680 res.append(self.__origin__)
681 i = bases.index(self)
682 if not any(isinstance(b, _GenericAlias) or issubclass(b, Generic)
683 for b in bases[i+1:]):
684 res.append(Generic)
685 return tuple(res)
686 if self.__origin__ is Generic:
687 i = bases.index(self)
688 for b in bases[i+1:]:
689 if isinstance(b, _GenericAlias) and b is not self:
690 return ()
691 return (self.__origin__,)
692
693 def __getattr__(self, attr):
Ville Skyttä61f82e02018-04-20 23:08:45 +0300694 # We are careful for copy and pickle.
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000695 # Also for simplicity we just don't relay all dunder names
696 if '__origin__' in self.__dict__ and not _is_dunder(attr):
697 return getattr(self.__origin__, attr)
698 raise AttributeError(attr)
699
700 def __setattr__(self, attr, val):
701 if _is_dunder(attr) or attr in ('_name', '_inst', '_special'):
702 super().__setattr__(attr, val)
703 else:
704 setattr(self.__origin__, attr, val)
705
706 def __instancecheck__(self, obj):
707 return self.__subclasscheck__(type(obj))
708
709 def __subclasscheck__(self, cls):
710 if self._special:
711 if not isinstance(cls, _GenericAlias):
712 return issubclass(cls, self.__origin__)
713 if cls._special:
714 return issubclass(cls.__origin__, self.__origin__)
715 raise TypeError("Subscripted generics cannot be used with"
716 " class and instance checks")
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700717
Ivan Levkivskyi83494032018-03-26 23:01:12 +0100718 def __reduce__(self):
719 if self._special:
720 return self._name
Serhiy Storchaka09f32212018-05-26 21:19:26 +0300721
722 if self._name:
723 origin = globals()[self._name]
724 else:
725 origin = self.__origin__
726 if (origin is Callable and
727 not (len(self.__args__) == 2 and self.__args__[0] is Ellipsis)):
728 args = list(self.__args__[:-1]), self.__args__[-1]
729 else:
730 args = tuple(self.__args__)
731 if len(args) == 1 and not isinstance(args[0], tuple):
732 args, = args
733 return operator.getitem, (origin, args)
Ivan Levkivskyi83494032018-03-26 23:01:12 +0100734
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700735
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000736class _VariadicGenericAlias(_GenericAlias, _root=True):
737 """Same as _GenericAlias above but for variadic aliases. Currently,
738 this is used only by special internal aliases: Tuple and Callable.
739 """
740 def __getitem__(self, params):
741 if self._name != 'Callable' or not self._special:
742 return self.__getitem_inner__(params)
743 if not isinstance(params, tuple) or len(params) != 2:
744 raise TypeError("Callable must be used as "
745 "Callable[[arg, ...], result].")
746 args, result = params
747 if args is Ellipsis:
748 params = (Ellipsis, result)
749 else:
750 if not isinstance(args, list):
751 raise TypeError(f"Callable[args, result]: args must be a list."
752 f" Got {args}")
753 params = (tuple(args), result)
754 return self.__getitem_inner__(params)
755
756 @_tp_cache
757 def __getitem_inner__(self, params):
758 if self.__origin__ is tuple and self._special:
759 if params == ():
760 return self.copy_with((_TypingEmpty,))
761 if not isinstance(params, tuple):
762 params = (params,)
763 if len(params) == 2 and params[1] is ...:
764 msg = "Tuple[t, ...]: t must be a type."
765 p = _type_check(params[0], msg)
766 return self.copy_with((p, _TypingEllipsis))
767 msg = "Tuple[t0, t1, ...]: each t must be a type."
768 params = tuple(_type_check(p, msg) for p in params)
769 return self.copy_with(params)
770 if self.__origin__ is collections.abc.Callable and self._special:
771 args, result = params
772 msg = "Callable[args, result]: result must be a type."
773 result = _type_check(result, msg)
774 if args is Ellipsis:
775 return self.copy_with((_TypingEllipsis, result))
776 msg = "Callable[[arg, ...], result]: each arg must be a type."
777 args = tuple(_type_check(arg, msg) for arg in args)
778 params = args + (result,)
779 return self.copy_with(params)
780 return super().__getitem__(params)
781
782
783class Generic:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700784 """Abstract base class for generic types.
785
Guido van Rossumb24569a2016-11-20 18:01:29 -0800786 A generic type is typically declared by inheriting from
787 this class parameterized with one or more type variables.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700788 For example, a generic mapping type might be defined as::
789
790 class Mapping(Generic[KT, VT]):
791 def __getitem__(self, key: KT) -> VT:
792 ...
793 # Etc.
794
795 This class can then be used as follows::
796
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700797 def lookup_name(mapping: Mapping[KT, VT], key: KT, default: VT) -> VT:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700798 try:
799 return mapping[key]
800 except KeyError:
801 return default
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700802 """
Guido van Rossumd70fe632015-08-05 12:11:06 +0200803 __slots__ = ()
804
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700805 def __new__(cls, *args, **kwds):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000806 if cls is Generic:
Guido van Rossum62fe1bb2016-10-29 16:05:26 -0700807 raise TypeError("Type Generic cannot be instantiated; "
808 "it can be used only as a base class")
Ivan Levkivskyib551e9f2018-05-10 23:10:10 -0400809 if super().__new__ is object.__new__ and cls.__init__ is not object.__init__:
Ivan Levkivskyi43d12a62018-05-09 02:23:46 +0100810 obj = super().__new__(cls)
811 else:
812 obj = super().__new__(cls, *args, **kwds)
813 return obj
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000814
815 @_tp_cache
816 def __class_getitem__(cls, params):
817 if not isinstance(params, tuple):
818 params = (params,)
819 if not params and cls is not Tuple:
820 raise TypeError(
821 f"Parameter list to {cls.__qualname__}[...] cannot be empty")
822 msg = "Parameters to generic types must be types."
823 params = tuple(_type_check(p, msg) for p in params)
824 if cls is Generic:
825 # Generic can only be subscripted with unique type variables.
826 if not all(isinstance(p, TypeVar) for p in params):
827 raise TypeError(
828 "Parameters to Generic[...] must all be type variables")
829 if len(set(params)) != len(params):
830 raise TypeError(
831 "Parameters to Generic[...] must all be unique")
832 elif cls is _Protocol:
833 # _Protocol is internal at the moment, just skip the check
834 pass
835 else:
836 # Subscripting a regular Generic subclass.
837 _check_generic(cls, params)
838 return _GenericAlias(cls, params)
839
840 def __init_subclass__(cls, *args, **kwargs):
Ivan Levkivskyiee566fe2018-04-04 17:00:15 +0100841 super().__init_subclass__(*args, **kwargs)
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000842 tvars = []
843 if '__orig_bases__' in cls.__dict__:
844 error = Generic in cls.__orig_bases__
845 else:
846 error = Generic in cls.__bases__ and cls.__name__ != '_Protocol'
847 if error:
848 raise TypeError("Cannot inherit from plain Generic")
849 if '__orig_bases__' in cls.__dict__:
850 tvars = _collect_type_vars(cls.__orig_bases__)
851 # Look for Generic[T1, ..., Tn].
852 # If found, tvars must be a subset of it.
853 # If not found, tvars is it.
854 # Also check for and reject plain Generic,
855 # and reject multiple Generic[...].
856 gvars = None
857 for base in cls.__orig_bases__:
858 if (isinstance(base, _GenericAlias) and
859 base.__origin__ is Generic):
860 if gvars is not None:
861 raise TypeError(
862 "Cannot inherit from Generic[...] multiple types.")
863 gvars = base.__parameters__
864 if gvars is None:
865 gvars = tvars
866 else:
867 tvarset = set(tvars)
868 gvarset = set(gvars)
869 if not tvarset <= gvarset:
870 s_vars = ', '.join(str(t) for t in tvars if t not in gvarset)
871 s_args = ', '.join(str(g) for g in gvars)
872 raise TypeError(f"Some type variables ({s_vars}) are"
873 f" not listed in Generic[{s_args}]")
874 tvars = gvars
875 cls.__parameters__ = tuple(tvars)
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700876
877
878class _TypingEmpty:
Guido van Rossumb24569a2016-11-20 18:01:29 -0800879 """Internal placeholder for () or []. Used by TupleMeta and CallableMeta
880 to allow empty list/tuple in specific places, without allowing them
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700881 to sneak in where prohibited.
882 """
883
884
885class _TypingEllipsis:
Guido van Rossumb24569a2016-11-20 18:01:29 -0800886 """Internal placeholder for ... (ellipsis)."""
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700887
888
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700889def cast(typ, val):
890 """Cast a value to a type.
891
892 This returns the value unchanged. To the type checker this
893 signals that the return value has the designated type, but at
894 runtime we intentionally don't check anything (we want this
895 to be as fast as possible).
896 """
897 return val
898
899
900def _get_defaults(func):
901 """Internal helper to extract the default arguments, by name."""
Guido van Rossum991d14f2016-11-09 13:12:51 -0800902 try:
903 code = func.__code__
904 except AttributeError:
905 # Some built-in functions don't have __code__, __defaults__, etc.
906 return {}
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700907 pos_count = code.co_argcount
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700908 arg_names = code.co_varnames
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700909 arg_names = arg_names[:pos_count]
910 defaults = func.__defaults__ or ()
911 kwdefaults = func.__kwdefaults__
912 res = dict(kwdefaults) if kwdefaults else {}
913 pos_offset = pos_count - len(defaults)
914 for name, value in zip(arg_names[pos_offset:], defaults):
915 assert name not in res
916 res[name] = value
917 return res
918
919
Ivan Levkivskyib692dc82017-02-13 22:50:14 +0100920_allowed_types = (types.FunctionType, types.BuiltinFunctionType,
921 types.MethodType, types.ModuleType,
Ivan Levkivskyif06e0212017-05-02 19:14:07 +0200922 WrapperDescriptorType, MethodWrapperType, MethodDescriptorType)
Ivan Levkivskyib692dc82017-02-13 22:50:14 +0100923
924
Guido van Rossum991d14f2016-11-09 13:12:51 -0800925def get_type_hints(obj, globalns=None, localns=None):
926 """Return type hints for an object.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700927
Guido van Rossum991d14f2016-11-09 13:12:51 -0800928 This is often the same as obj.__annotations__, but it handles
929 forward references encoded as string literals, and if necessary
930 adds Optional[t] if a default value equal to None is set.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700931
Guido van Rossum991d14f2016-11-09 13:12:51 -0800932 The argument may be a module, class, method, or function. The annotations
933 are returned as a dictionary. For classes, annotations include also
934 inherited members.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700935
Guido van Rossum991d14f2016-11-09 13:12:51 -0800936 TypeError is raised if the argument is not of a type that can contain
937 annotations, and an empty dictionary is returned if no annotations are
938 present.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700939
Guido van Rossum991d14f2016-11-09 13:12:51 -0800940 BEWARE -- the behavior of globalns and localns is counterintuitive
941 (unless you are familiar with how eval() and exec() work). The
942 search order is locals first, then globals.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700943
Guido van Rossum991d14f2016-11-09 13:12:51 -0800944 - If no dict arguments are passed, an attempt is made to use the
Łukasz Langaf350a262017-09-14 14:33:00 -0400945 globals from obj (or the respective module's globals for classes),
946 and these are also used as the locals. If the object does not appear
947 to have globals, an empty dictionary is used.
Guido van Rossum0a6976d2016-09-11 15:34:56 -0700948
Guido van Rossum991d14f2016-11-09 13:12:51 -0800949 - If one dict argument is passed, it is used for both globals and
950 locals.
Guido van Rossum0a6976d2016-09-11 15:34:56 -0700951
Guido van Rossum991d14f2016-11-09 13:12:51 -0800952 - If two dict arguments are passed, they specify globals and
953 locals, respectively.
954 """
Guido van Rossum0a6976d2016-09-11 15:34:56 -0700955
Guido van Rossum991d14f2016-11-09 13:12:51 -0800956 if getattr(obj, '__no_type_check__', None):
957 return {}
Guido van Rossum991d14f2016-11-09 13:12:51 -0800958 # Classes require a special treatment.
959 if isinstance(obj, type):
960 hints = {}
961 for base in reversed(obj.__mro__):
Łukasz Langaf350a262017-09-14 14:33:00 -0400962 if globalns is None:
963 base_globals = sys.modules[base.__module__].__dict__
964 else:
965 base_globals = globalns
Guido van Rossum991d14f2016-11-09 13:12:51 -0800966 ann = base.__dict__.get('__annotations__', {})
967 for name, value in ann.items():
968 if value is None:
969 value = type(None)
970 if isinstance(value, str):
Nina Zakharenko0e61dff2018-05-22 20:32:10 -0700971 value = ForwardRef(value, is_argument=False)
Łukasz Langaf350a262017-09-14 14:33:00 -0400972 value = _eval_type(value, base_globals, localns)
Guido van Rossum991d14f2016-11-09 13:12:51 -0800973 hints[name] = value
974 return hints
Łukasz Langaf350a262017-09-14 14:33:00 -0400975
976 if globalns is None:
977 if isinstance(obj, types.ModuleType):
978 globalns = obj.__dict__
979 else:
980 globalns = getattr(obj, '__globals__', {})
981 if localns is None:
982 localns = globalns
983 elif localns is None:
984 localns = globalns
Guido van Rossum991d14f2016-11-09 13:12:51 -0800985 hints = getattr(obj, '__annotations__', None)
986 if hints is None:
987 # Return empty annotations for something that _could_ have them.
Ivan Levkivskyib692dc82017-02-13 22:50:14 +0100988 if isinstance(obj, _allowed_types):
Guido van Rossum0a6976d2016-09-11 15:34:56 -0700989 return {}
Guido van Rossum991d14f2016-11-09 13:12:51 -0800990 else:
991 raise TypeError('{!r} is not a module, class, method, '
992 'or function.'.format(obj))
993 defaults = _get_defaults(obj)
994 hints = dict(hints)
995 for name, value in hints.items():
996 if value is None:
997 value = type(None)
998 if isinstance(value, str):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000999 value = ForwardRef(value)
Guido van Rossum991d14f2016-11-09 13:12:51 -08001000 value = _eval_type(value, globalns, localns)
1001 if name in defaults and defaults[name] is None:
1002 value = Optional[value]
1003 hints[name] = value
1004 return hints
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001005
1006
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001007def no_type_check(arg):
1008 """Decorator to indicate that annotations are not type hints.
1009
1010 The argument must be a class or function; if it is a class, it
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001011 applies recursively to all methods and classes defined in that class
1012 (but not to methods defined in its superclasses or subclasses).
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001013
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001014 This mutates the function(s) or class(es) in place.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001015 """
1016 if isinstance(arg, type):
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001017 arg_attrs = arg.__dict__.copy()
1018 for attr, val in arg.__dict__.items():
Ivan Levkivskyi65bc6202017-09-14 01:25:15 +02001019 if val in arg.__bases__ + (arg,):
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001020 arg_attrs.pop(attr)
1021 for obj in arg_attrs.values():
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001022 if isinstance(obj, types.FunctionType):
1023 obj.__no_type_check__ = True
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001024 if isinstance(obj, type):
1025 no_type_check(obj)
1026 try:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001027 arg.__no_type_check__ = True
Guido van Rossumd7adfe12017-01-22 17:43:53 -08001028 except TypeError: # built-in classes
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001029 pass
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001030 return arg
1031
1032
1033def no_type_check_decorator(decorator):
1034 """Decorator to give another decorator the @no_type_check effect.
1035
1036 This wraps the decorator with something that wraps the decorated
1037 function in @no_type_check.
1038 """
1039
1040 @functools.wraps(decorator)
1041 def wrapped_decorator(*args, **kwds):
1042 func = decorator(*args, **kwds)
1043 func = no_type_check(func)
1044 return func
1045
1046 return wrapped_decorator
1047
1048
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001049def _overload_dummy(*args, **kwds):
1050 """Helper for @overload to raise when called."""
1051 raise NotImplementedError(
1052 "You should not call an overloaded function. "
1053 "A series of @overload-decorated functions "
1054 "outside a stub module should always be followed "
1055 "by an implementation that is not @overload-ed.")
1056
1057
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001058def overload(func):
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001059 """Decorator for overloaded functions/methods.
1060
1061 In a stub file, place two or more stub definitions for the same
1062 function in a row, each decorated with @overload. For example:
1063
1064 @overload
1065 def utf8(value: None) -> None: ...
1066 @overload
1067 def utf8(value: bytes) -> bytes: ...
1068 @overload
1069 def utf8(value: str) -> bytes: ...
1070
1071 In a non-stub file (i.e. a regular .py file), do the same but
1072 follow it with an implementation. The implementation should *not*
1073 be decorated with @overload. For example:
1074
1075 @overload
1076 def utf8(value: None) -> None: ...
1077 @overload
1078 def utf8(value: bytes) -> bytes: ...
1079 @overload
1080 def utf8(value: str) -> bytes: ...
1081 def utf8(value):
1082 # implementation goes here
1083 """
1084 return _overload_dummy
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001085
1086
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001087class _ProtocolMeta(type):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001088 """Internal metaclass for _Protocol.
1089
1090 This exists so _Protocol classes can be generic without deriving
1091 from Generic.
1092 """
1093
Guido van Rossumd70fe632015-08-05 12:11:06 +02001094 def __instancecheck__(self, obj):
Guido van Rossumca4b2522016-11-19 10:32:41 -08001095 if _Protocol not in self.__bases__:
1096 return super().__instancecheck__(obj)
Guido van Rossumd70fe632015-08-05 12:11:06 +02001097 raise TypeError("Protocols cannot be used with isinstance().")
1098
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001099 def __subclasscheck__(self, cls):
1100 if not self._is_protocol:
1101 # No structural checks since this isn't a protocol.
1102 return NotImplemented
1103
1104 if self is _Protocol:
1105 # Every class is a subclass of the empty protocol.
1106 return True
1107
1108 # Find all attributes defined in the protocol.
1109 attrs = self._get_protocol_attrs()
1110
1111 for attr in attrs:
1112 if not any(attr in d.__dict__ for d in cls.__mro__):
1113 return False
1114 return True
1115
1116 def _get_protocol_attrs(self):
1117 # Get all Protocol base classes.
1118 protocol_bases = []
1119 for c in self.__mro__:
1120 if getattr(c, '_is_protocol', False) and c.__name__ != '_Protocol':
1121 protocol_bases.append(c)
1122
1123 # Get attributes included in protocol.
1124 attrs = set()
1125 for base in protocol_bases:
1126 for attr in base.__dict__.keys():
1127 # Include attributes not defined in any non-protocol bases.
1128 for c in self.__mro__:
1129 if (c is not base and attr in c.__dict__ and
1130 not getattr(c, '_is_protocol', False)):
1131 break
1132 else:
1133 if (not attr.startswith('_abc_') and
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001134 attr != '__abstractmethods__' and
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001135 attr != '__annotations__' and
1136 attr != '__weakref__' and
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001137 attr != '_is_protocol' and
Ivan Levkivskyi65bc6202017-09-14 01:25:15 +02001138 attr != '_gorg' and
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001139 attr != '__dict__' and
1140 attr != '__args__' and
1141 attr != '__slots__' and
1142 attr != '_get_protocol_attrs' and
1143 attr != '__next_in_mro__' and
1144 attr != '__parameters__' and
1145 attr != '__origin__' and
Guido van Rossum7ef22d62016-10-21 14:27:58 -07001146 attr != '__orig_bases__' and
Guido van Rossum1cea70f2016-05-18 08:35:00 -07001147 attr != '__extra__' and
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001148 attr != '__tree_hash__' and
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001149 attr != '__module__'):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001150 attrs.add(attr)
1151
1152 return attrs
1153
1154
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001155class _Protocol(Generic, metaclass=_ProtocolMeta):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001156 """Internal base class for protocol classes.
1157
Guido van Rossumb24569a2016-11-20 18:01:29 -08001158 This implements a simple-minded structural issubclass check
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001159 (similar but more general than the one-offs in collections.abc
1160 such as Hashable).
1161 """
1162
Guido van Rossumd70fe632015-08-05 12:11:06 +02001163 __slots__ = ()
1164
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001165 _is_protocol = True
1166
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001167 def __class_getitem__(cls, params):
1168 return super().__class_getitem__(params)
1169
1170
1171# Some unconstrained type variables. These are used by the container types.
1172# (These are not for export.)
1173T = TypeVar('T') # Any type.
1174KT = TypeVar('KT') # Key type.
1175VT = TypeVar('VT') # Value type.
1176T_co = TypeVar('T_co', covariant=True) # Any type covariant containers.
1177V_co = TypeVar('V_co', covariant=True) # Any type covariant containers.
1178VT_co = TypeVar('VT_co', covariant=True) # Value type covariant containers.
1179T_contra = TypeVar('T_contra', contravariant=True) # Ditto contravariant.
1180# Internal type variable used for Type[].
1181CT_co = TypeVar('CT_co', covariant=True, bound=type)
1182
1183# A useful type variable with constraints. This represents string types.
1184# (This one *is* for export!)
1185AnyStr = TypeVar('AnyStr', bytes, str)
1186
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001187
1188# Various ABCs mimicking those in collections.abc.
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001189def _alias(origin, params, inst=True):
1190 return _GenericAlias(origin, params, special=True, inst=inst)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001191
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001192Hashable = _alias(collections.abc.Hashable, ()) # Not generic.
1193Awaitable = _alias(collections.abc.Awaitable, T_co)
1194Coroutine = _alias(collections.abc.Coroutine, (T_co, T_contra, V_co))
1195AsyncIterable = _alias(collections.abc.AsyncIterable, T_co)
1196AsyncIterator = _alias(collections.abc.AsyncIterator, T_co)
1197Iterable = _alias(collections.abc.Iterable, T_co)
1198Iterator = _alias(collections.abc.Iterator, T_co)
1199Reversible = _alias(collections.abc.Reversible, T_co)
1200Sized = _alias(collections.abc.Sized, ()) # Not generic.
1201Container = _alias(collections.abc.Container, T_co)
1202Collection = _alias(collections.abc.Collection, T_co)
1203Callable = _VariadicGenericAlias(collections.abc.Callable, (), special=True)
1204Callable.__doc__ = \
1205 """Callable type; Callable[[int], str] is a function of (int) -> str.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001206
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001207 The subscription syntax must always be used with exactly two
1208 values: the argument list and the return type. The argument list
1209 must be a list of types or ellipsis; the return type must be a single type.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001210
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001211 There is no syntax to indicate optional or keyword arguments,
1212 such function types are rarely used as callback types.
1213 """
1214AbstractSet = _alias(collections.abc.Set, T_co)
1215MutableSet = _alias(collections.abc.MutableSet, T)
1216# NOTE: Mapping is only covariant in the value type.
1217Mapping = _alias(collections.abc.Mapping, (KT, VT_co))
1218MutableMapping = _alias(collections.abc.MutableMapping, (KT, VT))
1219Sequence = _alias(collections.abc.Sequence, T_co)
1220MutableSequence = _alias(collections.abc.MutableSequence, T)
1221ByteString = _alias(collections.abc.ByteString, ()) # Not generic
1222Tuple = _VariadicGenericAlias(tuple, (), inst=False, special=True)
1223Tuple.__doc__ = \
1224 """Tuple type; Tuple[X, Y] is the cross-product type of X and Y.
Guido van Rossum62fe1bb2016-10-29 16:05:26 -07001225
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001226 Example: Tuple[T1, T2] is a tuple of two elements corresponding
1227 to type variables T1 and T2. Tuple[int, float, str] is a tuple
1228 of an int, a float and a string.
Guido van Rossum62fe1bb2016-10-29 16:05:26 -07001229
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001230 To specify a variable-length tuple of homogeneous type, use Tuple[T, ...].
1231 """
1232List = _alias(list, T, inst=False)
1233Deque = _alias(collections.deque, T)
1234Set = _alias(set, T, inst=False)
1235FrozenSet = _alias(frozenset, T_co, inst=False)
1236MappingView = _alias(collections.abc.MappingView, T_co)
1237KeysView = _alias(collections.abc.KeysView, KT)
1238ItemsView = _alias(collections.abc.ItemsView, (KT, VT_co))
1239ValuesView = _alias(collections.abc.ValuesView, VT_co)
1240ContextManager = _alias(contextlib.AbstractContextManager, T_co)
1241AsyncContextManager = _alias(contextlib.AbstractAsyncContextManager, T_co)
1242Dict = _alias(dict, (KT, VT), inst=False)
1243DefaultDict = _alias(collections.defaultdict, (KT, VT))
Ismo Toijala68b56d02018-12-02 17:53:14 +02001244OrderedDict = _alias(collections.OrderedDict, (KT, VT))
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001245Counter = _alias(collections.Counter, T)
1246ChainMap = _alias(collections.ChainMap, (KT, VT))
1247Generator = _alias(collections.abc.Generator, (T_co, T_contra, V_co))
1248AsyncGenerator = _alias(collections.abc.AsyncGenerator, (T_co, T_contra))
1249Type = _alias(type, CT_co, inst=False)
1250Type.__doc__ = \
1251 """A special construct usable to annotate class objects.
Guido van Rossum62fe1bb2016-10-29 16:05:26 -07001252
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001253 For example, suppose we have the following classes::
Guido van Rossum62fe1bb2016-10-29 16:05:26 -07001254
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001255 class User: ... # Abstract base for User classes
1256 class BasicUser(User): ...
1257 class ProUser(User): ...
1258 class TeamUser(User): ...
Guido van Rossumf17c2002015-12-03 17:31:24 -08001259
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001260 And a function that takes a class argument that's a subclass of
1261 User and returns an instance of the corresponding class::
Guido van Rossumf17c2002015-12-03 17:31:24 -08001262
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001263 U = TypeVar('U', bound=User)
1264 def new_user(user_class: Type[U]) -> U:
1265 user = user_class()
1266 # (Here we could write the user object to a database)
1267 return user
Guido van Rossumf17c2002015-12-03 17:31:24 -08001268
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001269 joe = new_user(BasicUser)
Guido van Rossumf17c2002015-12-03 17:31:24 -08001270
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001271 At this point the type checker knows that joe has type BasicUser.
1272 """
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001273
1274
1275class SupportsInt(_Protocol):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001276 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001277
1278 @abstractmethod
1279 def __int__(self) -> int:
1280 pass
1281
1282
1283class SupportsFloat(_Protocol):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001284 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001285
1286 @abstractmethod
1287 def __float__(self) -> float:
1288 pass
1289
1290
1291class SupportsComplex(_Protocol):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001292 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001293
1294 @abstractmethod
1295 def __complex__(self) -> complex:
1296 pass
1297
1298
1299class SupportsBytes(_Protocol):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001300 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001301
1302 @abstractmethod
1303 def __bytes__(self) -> bytes:
1304 pass
1305
1306
Guido van Rossumd70fe632015-08-05 12:11:06 +02001307class SupportsAbs(_Protocol[T_co]):
1308 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001309
1310 @abstractmethod
Guido van Rossumd70fe632015-08-05 12:11:06 +02001311 def __abs__(self) -> T_co:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001312 pass
1313
1314
Guido van Rossumd70fe632015-08-05 12:11:06 +02001315class SupportsRound(_Protocol[T_co]):
1316 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001317
1318 @abstractmethod
Guido van Rossumd70fe632015-08-05 12:11:06 +02001319 def __round__(self, ndigits: int = 0) -> T_co:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001320 pass
1321
1322
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001323def _make_nmtuple(name, types):
Guido van Rossum2f841442016-11-15 09:48:06 -08001324 msg = "NamedTuple('Name', [(f0, t0), (f1, t1), ...]); each t must be a type"
1325 types = [(n, _type_check(t, msg)) for n, t in types]
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001326 nm_tpl = collections.namedtuple(name, [n for n, t in types])
Guido van Rossum83ec3022017-01-17 20:43:28 -08001327 # Prior to PEP 526, only _field_types attribute was assigned.
1328 # Now, both __annotations__ and _field_types are used to maintain compatibility.
1329 nm_tpl.__annotations__ = nm_tpl._field_types = collections.OrderedDict(types)
Guido van Rossum557d1eb2015-11-19 08:16:31 -08001330 try:
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001331 nm_tpl.__module__ = sys._getframe(2).f_globals.get('__name__', '__main__')
Guido van Rossum557d1eb2015-11-19 08:16:31 -08001332 except (AttributeError, ValueError):
1333 pass
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001334 return nm_tpl
1335
1336
Ivan Levkivskyib692dc82017-02-13 22:50:14 +01001337# attributes prohibited to set in NamedTuple class syntax
1338_prohibited = ('__new__', '__init__', '__slots__', '__getnewargs__',
1339 '_fields', '_field_defaults', '_field_types',
Ivan Levkivskyif06e0212017-05-02 19:14:07 +02001340 '_make', '_replace', '_asdict', '_source')
Ivan Levkivskyib692dc82017-02-13 22:50:14 +01001341
1342_special = ('__module__', '__name__', '__qualname__', '__annotations__')
1343
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001344
Guido van Rossum2f841442016-11-15 09:48:06 -08001345class NamedTupleMeta(type):
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001346
Guido van Rossum2f841442016-11-15 09:48:06 -08001347 def __new__(cls, typename, bases, ns):
1348 if ns.get('_root', False):
1349 return super().__new__(cls, typename, bases, ns)
Guido van Rossum2f841442016-11-15 09:48:06 -08001350 types = ns.get('__annotations__', {})
Guido van Rossum3c268be2017-01-18 08:03:50 -08001351 nm_tpl = _make_nmtuple(typename, types.items())
1352 defaults = []
1353 defaults_dict = {}
1354 for field_name in types:
1355 if field_name in ns:
1356 default_value = ns[field_name]
1357 defaults.append(default_value)
1358 defaults_dict[field_name] = default_value
1359 elif defaults:
Guido van Rossumd7adfe12017-01-22 17:43:53 -08001360 raise TypeError("Non-default namedtuple field {field_name} cannot "
1361 "follow default field(s) {default_names}"
Guido van Rossum3c268be2017-01-18 08:03:50 -08001362 .format(field_name=field_name,
1363 default_names=', '.join(defaults_dict.keys())))
Ivan Levkivskyi43d12a62018-05-09 02:23:46 +01001364 nm_tpl.__new__.__annotations__ = collections.OrderedDict(types)
Guido van Rossum3c268be2017-01-18 08:03:50 -08001365 nm_tpl.__new__.__defaults__ = tuple(defaults)
1366 nm_tpl._field_defaults = defaults_dict
Guido van Rossum95919c02017-01-22 17:47:20 -08001367 # update from user namespace without overriding special namedtuple attributes
1368 for key in ns:
Ivan Levkivskyib692dc82017-02-13 22:50:14 +01001369 if key in _prohibited:
1370 raise AttributeError("Cannot overwrite NamedTuple attribute " + key)
1371 elif key not in _special and key not in nm_tpl._fields:
Guido van Rossum95919c02017-01-22 17:47:20 -08001372 setattr(nm_tpl, key, ns[key])
Guido van Rossum3c268be2017-01-18 08:03:50 -08001373 return nm_tpl
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001374
Guido van Rossumd7adfe12017-01-22 17:43:53 -08001375
Guido van Rossum2f841442016-11-15 09:48:06 -08001376class NamedTuple(metaclass=NamedTupleMeta):
1377 """Typed version of namedtuple.
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001378
Guido van Rossum2f841442016-11-15 09:48:06 -08001379 Usage in Python versions >= 3.6::
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001380
Guido van Rossum2f841442016-11-15 09:48:06 -08001381 class Employee(NamedTuple):
1382 name: str
1383 id: int
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001384
Guido van Rossum2f841442016-11-15 09:48:06 -08001385 This is equivalent to::
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001386
Guido van Rossum2f841442016-11-15 09:48:06 -08001387 Employee = collections.namedtuple('Employee', ['name', 'id'])
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001388
Guido van Rossum83ec3022017-01-17 20:43:28 -08001389 The resulting class has extra __annotations__ and _field_types
1390 attributes, giving an ordered dict mapping field names to types.
1391 __annotations__ should be preferred, while _field_types
1392 is kept to maintain pre PEP 526 compatibility. (The field names
Guido van Rossum2f841442016-11-15 09:48:06 -08001393 are in the _fields attribute, which is part of the namedtuple
1394 API.) Alternative equivalent keyword syntax is also accepted::
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001395
Guido van Rossum2f841442016-11-15 09:48:06 -08001396 Employee = NamedTuple('Employee', name=str, id=int)
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001397
Guido van Rossum2f841442016-11-15 09:48:06 -08001398 In Python versions <= 3.5 use::
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001399
Guido van Rossum2f841442016-11-15 09:48:06 -08001400 Employee = NamedTuple('Employee', [('name', str), ('id', int)])
1401 """
1402 _root = True
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001403
Guido van Rossum2f841442016-11-15 09:48:06 -08001404 def __new__(self, typename, fields=None, **kwargs):
Guido van Rossum2f841442016-11-15 09:48:06 -08001405 if fields is None:
1406 fields = kwargs.items()
1407 elif kwargs:
1408 raise TypeError("Either list of fields or keywords"
1409 " can be provided to NamedTuple, not both")
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001410 return _make_nmtuple(typename, fields)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001411
1412
Guido van Rossum91185fe2016-06-08 11:19:11 -07001413def NewType(name, tp):
1414 """NewType creates simple unique types with almost zero
1415 runtime overhead. NewType(name, tp) is considered a subtype of tp
1416 by static type checkers. At runtime, NewType(name, tp) returns
1417 a dummy function that simply returns its argument. Usage::
1418
1419 UserId = NewType('UserId', int)
1420
1421 def name_by_id(user_id: UserId) -> str:
1422 ...
1423
1424 UserId('user') # Fails type check
1425
1426 name_by_id(42) # Fails type check
1427 name_by_id(UserId(42)) # OK
1428
1429 num = UserId(5) + 1 # type: int
1430 """
1431
1432 def new_type(x):
1433 return x
1434
1435 new_type.__name__ = name
1436 new_type.__supertype__ = tp
1437 return new_type
1438
1439
Guido van Rossum0e0563c2016-04-05 14:54:25 -07001440# Python-version-specific alias (Python 2: unicode; Python 3: str)
1441Text = str
1442
1443
Guido van Rossum91185fe2016-06-08 11:19:11 -07001444# Constant that's True when type checking, but False here.
1445TYPE_CHECKING = False
1446
1447
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001448class IO(Generic[AnyStr]):
1449 """Generic base class for TextIO and BinaryIO.
1450
1451 This is an abstract, generic version of the return of open().
1452
1453 NOTE: This does not distinguish between the different possible
1454 classes (text vs. binary, read vs. write vs. read/write,
1455 append-only, unbuffered). The TextIO and BinaryIO subclasses
1456 below capture the distinctions between text vs. binary, which is
1457 pervasive in the interface; however we currently do not offer a
1458 way to track the other distinctions in the type system.
1459 """
1460
Guido van Rossumd70fe632015-08-05 12:11:06 +02001461 __slots__ = ()
1462
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001463 @abstractproperty
1464 def mode(self) -> str:
1465 pass
1466
1467 @abstractproperty
1468 def name(self) -> str:
1469 pass
1470
1471 @abstractmethod
1472 def close(self) -> None:
1473 pass
1474
1475 @abstractmethod
1476 def closed(self) -> bool:
1477 pass
1478
1479 @abstractmethod
1480 def fileno(self) -> int:
1481 pass
1482
1483 @abstractmethod
1484 def flush(self) -> None:
1485 pass
1486
1487 @abstractmethod
1488 def isatty(self) -> bool:
1489 pass
1490
1491 @abstractmethod
1492 def read(self, n: int = -1) -> AnyStr:
1493 pass
1494
1495 @abstractmethod
1496 def readable(self) -> bool:
1497 pass
1498
1499 @abstractmethod
1500 def readline(self, limit: int = -1) -> AnyStr:
1501 pass
1502
1503 @abstractmethod
1504 def readlines(self, hint: int = -1) -> List[AnyStr]:
1505 pass
1506
1507 @abstractmethod
1508 def seek(self, offset: int, whence: int = 0) -> int:
1509 pass
1510
1511 @abstractmethod
1512 def seekable(self) -> bool:
1513 pass
1514
1515 @abstractmethod
1516 def tell(self) -> int:
1517 pass
1518
1519 @abstractmethod
1520 def truncate(self, size: int = None) -> int:
1521 pass
1522
1523 @abstractmethod
1524 def writable(self) -> bool:
1525 pass
1526
1527 @abstractmethod
1528 def write(self, s: AnyStr) -> int:
1529 pass
1530
1531 @abstractmethod
1532 def writelines(self, lines: List[AnyStr]) -> None:
1533 pass
1534
1535 @abstractmethod
1536 def __enter__(self) -> 'IO[AnyStr]':
1537 pass
1538
1539 @abstractmethod
1540 def __exit__(self, type, value, traceback) -> None:
1541 pass
1542
1543
1544class BinaryIO(IO[bytes]):
1545 """Typed version of the return of open() in binary mode."""
1546
Guido van Rossumd70fe632015-08-05 12:11:06 +02001547 __slots__ = ()
1548
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001549 @abstractmethod
1550 def write(self, s: Union[bytes, bytearray]) -> int:
1551 pass
1552
1553 @abstractmethod
1554 def __enter__(self) -> 'BinaryIO':
1555 pass
1556
1557
1558class TextIO(IO[str]):
1559 """Typed version of the return of open() in text mode."""
1560
Guido van Rossumd70fe632015-08-05 12:11:06 +02001561 __slots__ = ()
1562
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001563 @abstractproperty
1564 def buffer(self) -> BinaryIO:
1565 pass
1566
1567 @abstractproperty
1568 def encoding(self) -> str:
1569 pass
1570
1571 @abstractproperty
Guido van Rossum991d14f2016-11-09 13:12:51 -08001572 def errors(self) -> Optional[str]:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001573 pass
1574
1575 @abstractproperty
1576 def line_buffering(self) -> bool:
1577 pass
1578
1579 @abstractproperty
1580 def newlines(self) -> Any:
1581 pass
1582
1583 @abstractmethod
1584 def __enter__(self) -> 'TextIO':
1585 pass
1586
1587
1588class io:
1589 """Wrapper namespace for IO generic classes."""
1590
1591 __all__ = ['IO', 'TextIO', 'BinaryIO']
1592 IO = IO
1593 TextIO = TextIO
1594 BinaryIO = BinaryIO
1595
Guido van Rossumd7adfe12017-01-22 17:43:53 -08001596
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001597io.__name__ = __name__ + '.io'
1598sys.modules[io.__name__] = io
1599
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001600Pattern = _alias(stdlib_re.Pattern, AnyStr)
1601Match = _alias(stdlib_re.Match, AnyStr)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001602
1603class re:
1604 """Wrapper namespace for re type aliases."""
1605
1606 __all__ = ['Pattern', 'Match']
1607 Pattern = Pattern
1608 Match = Match
1609
Guido van Rossumd7adfe12017-01-22 17:43:53 -08001610
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001611re.__name__ = __name__ + '.re'
1612sys.modules[re.__name__] = re