blob: 8cf0d00bceafff2410ba5cea8385de013566fdc8 [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:
Miss Islington (bot)f6d70b82018-09-01 05:15:40 -04005* 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 -070021import abc
22from abc import abstractmethod, abstractproperty
23import collections
Ivan Levkivskyid911e402018-01-20 11:23:59 +000024import collections.abc
Brett Cannonf3ad0422016-04-15 10:51:30 -070025import contextlib
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070026import functools
Miss Islington (bot)d4986252018-05-26 11:38:00 -070027import operator
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070028import re as stdlib_re # Avoid confusion with the re we export.
29import sys
30import types
Ivan Levkivskyid911e402018-01-20 11:23:59 +000031from types import WrapperDescriptorType, MethodWrapperType, MethodDescriptorType
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070032
33# Please keep __all__ alphabetized within each category.
34__all__ = [
35 # Super-special typing primitives.
36 'Any',
37 'Callable',
Guido van Rossum0a6976d2016-09-11 15:34:56 -070038 'ClassVar',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070039 'Generic',
40 'Optional',
Guido van Rossumeb9aca32016-05-24 16:38:22 -070041 'Tuple',
42 'Type',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070043 'TypeVar',
44 'Union',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070045
46 # ABCs (from collections.abc).
47 'AbstractSet', # collections.abc.Set.
48 'ByteString',
49 'Container',
Ivan Levkivskyi29fda8d2017-06-10 21:57:56 +020050 'ContextManager',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070051 'Hashable',
52 'ItemsView',
53 'Iterable',
54 'Iterator',
55 'KeysView',
56 'Mapping',
57 'MappingView',
58 'MutableMapping',
59 'MutableSequence',
60 'MutableSet',
61 'Sequence',
62 'Sized',
63 'ValuesView',
Ivan Levkivskyid911e402018-01-20 11:23:59 +000064 'Awaitable',
65 'AsyncIterator',
66 'AsyncIterable',
67 'Coroutine',
68 'Collection',
69 'AsyncGenerator',
70 'AsyncContextManager',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070071
72 # Structural checks, a.k.a. protocols.
73 'Reversible',
74 'SupportsAbs',
Ivan Levkivskyif06e0212017-05-02 19:14:07 +020075 'SupportsBytes',
76 'SupportsComplex',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070077 'SupportsFloat',
78 'SupportsInt',
79 'SupportsRound',
80
81 # Concrete collection types.
Ivan Levkivskyib692dc82017-02-13 22:50:14 +010082 'Counter',
Raymond Hettinger80490522017-01-16 22:42:37 -080083 'Deque',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070084 'Dict',
Guido van Rossumbd5b9a02016-04-05 08:28:52 -070085 'DefaultDict',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070086 'List',
87 'Set',
Guido van Rossumefa798d2016-08-23 11:01:50 -070088 'FrozenSet',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070089 'NamedTuple', # Not really a type.
90 'Generator',
91
92 # One-off things.
93 'AnyStr',
94 'cast',
95 'get_type_hints',
Guido van Rossum91185fe2016-06-08 11:19:11 -070096 'NewType',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070097 'no_type_check',
98 'no_type_check_decorator',
Ivan Levkivskyiac560272018-03-23 21:44:54 +000099 'NoReturn',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700100 'overload',
Guido van Rossum0e0563c2016-04-05 14:54:25 -0700101 'Text',
Guido van Rossum91185fe2016-06-08 11:19:11 -0700102 'TYPE_CHECKING',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700103]
104
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700105# The pseudo-submodules 're' and 'io' are part of the public
106# namespace, but excluded from __all__ because they might stomp on
107# legitimate imports of those modules.
108
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700109
Miss Islington (bot)0f9b68a2018-05-22 20:51:15 -0700110def _type_check(arg, msg, is_argument=True):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000111 """Check that the argument is a type, and return it (internal helper).
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700112
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000113 As a special case, accept None and return type(None) instead. Also wrap strings
114 into ForwardRef instances. Consider several corner cases, for example plain
115 special forms like Union are not valid, while Union[int, str] is OK, etc.
116 The msg argument is a human-readable error message, e.g::
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700117
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000118 "Union[arg, ...]: arg should be a type."
Guido van Rossum4cefe742016-09-27 15:20:12 -0700119
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000120 We append the repr() of the actual value (truncated to 100 chars).
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700121 """
Miss Islington (bot)9c17cd32018-05-16 15:04:39 -0700122 invalid_generic_forms = (Generic, _Protocol)
Miss Islington (bot)0f9b68a2018-05-22 20:51:15 -0700123 if is_argument:
Miss Islington (bot)9c17cd32018-05-16 15:04:39 -0700124 invalid_generic_forms = invalid_generic_forms + (ClassVar, )
125
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000126 if arg is None:
127 return type(None)
128 if isinstance(arg, str):
129 return ForwardRef(arg)
130 if (isinstance(arg, _GenericAlias) and
Miss Islington (bot)9c17cd32018-05-16 15:04:39 -0700131 arg.__origin__ in invalid_generic_forms):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000132 raise TypeError(f"{arg} is not valid as type argument")
Ismo Toijalaf71a5922018-11-28 19:22:09 +0200133 if (isinstance(arg, _SpecialForm) and arg not in (Any, NoReturn) or
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000134 arg in (Generic, _Protocol)):
135 raise TypeError(f"Plain {arg} is not valid as type argument")
136 if isinstance(arg, (type, TypeVar, ForwardRef)):
137 return arg
138 if not callable(arg):
139 raise TypeError(f"{msg} Got {arg!r:.100}.")
140 return arg
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700141
142
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000143def _type_repr(obj):
144 """Return the repr() of an object, special-casing types (internal helper).
145
146 If obj is a type, we return a shorter version than the default
147 type.__repr__, based on the module and qualified name, which is
148 typically enough to uniquely identify a type. For everything
149 else, we fall back on repr(obj).
150 """
151 if isinstance(obj, type):
152 if obj.__module__ == 'builtins':
153 return obj.__qualname__
154 return f'{obj.__module__}.{obj.__qualname__}'
155 if obj is ...:
156 return('...')
157 if isinstance(obj, types.FunctionType):
158 return obj.__name__
159 return repr(obj)
160
161
162def _collect_type_vars(types):
163 """Collect all type variable contained in types in order of
164 first appearance (lexicographic order). For example::
165
166 _collect_type_vars((T, List[S, T])) == (T, S)
167 """
168 tvars = []
169 for t in types:
170 if isinstance(t, TypeVar) and t not in tvars:
171 tvars.append(t)
172 if isinstance(t, _GenericAlias) and not t._special:
173 tvars.extend([t for t in t.__parameters__ if t not in tvars])
174 return tuple(tvars)
175
176
177def _subs_tvars(tp, tvars, subs):
178 """Substitute type variables 'tvars' with substitutions 'subs'.
179 These two must have the same length.
180 """
181 if not isinstance(tp, _GenericAlias):
182 return tp
183 new_args = list(tp.__args__)
184 for a, arg in enumerate(tp.__args__):
185 if isinstance(arg, TypeVar):
186 for i, tvar in enumerate(tvars):
187 if arg == tvar:
188 new_args[a] = subs[i]
189 else:
190 new_args[a] = _subs_tvars(arg, tvars, subs)
191 if tp.__origin__ is Union:
192 return Union[tuple(new_args)]
193 return tp.copy_with(tuple(new_args))
194
195
196def _check_generic(cls, parameters):
197 """Check correct count for parameters of a generic cls (internal helper).
198 This gives a nice error message in case of count mismatch.
199 """
200 if not cls.__parameters__:
201 raise TypeError(f"{cls} is not a generic class")
202 alen = len(parameters)
203 elen = len(cls.__parameters__)
204 if alen != elen:
205 raise TypeError(f"Too {'many' if alen > elen else 'few'} parameters for {cls};"
206 f" actual {alen}, expected {elen}")
207
208
209def _remove_dups_flatten(parameters):
Miss Islington (bot)09ca5902018-05-18 16:27:14 -0700210 """An internal helper for Union creation and substitution: flatten Unions
211 among parameters, then remove duplicates.
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000212 """
213 # Flatten out Union[Union[...], ...].
214 params = []
215 for p in parameters:
216 if isinstance(p, _GenericAlias) and p.__origin__ is Union:
217 params.extend(p.__args__)
218 elif isinstance(p, tuple) and len(p) > 0 and p[0] is Union:
219 params.extend(p[1:])
220 else:
221 params.append(p)
222 # Weed out strict duplicates, preserving the first of each occurrence.
223 all_params = set(params)
224 if len(all_params) < len(params):
225 new_params = []
226 for t in params:
227 if t in all_params:
228 new_params.append(t)
229 all_params.remove(t)
230 params = new_params
231 assert not all_params, all_params
Miss Islington (bot)09ca5902018-05-18 16:27:14 -0700232 return tuple(params)
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000233
234
235_cleanups = []
236
237
238def _tp_cache(func):
239 """Internal wrapper caching __getitem__ of generic types with a fallback to
240 original function for non-hashable arguments.
241 """
242 cached = functools.lru_cache()(func)
243 _cleanups.append(cached.cache_clear)
244
245 @functools.wraps(func)
246 def inner(*args, **kwds):
247 try:
248 return cached(*args, **kwds)
249 except TypeError:
250 pass # All real errors (not unhashable args) are raised below.
251 return func(*args, **kwds)
252 return inner
253
254
255def _eval_type(t, globalns, localns):
256 """Evaluate all forward reverences in the given type t.
257 For use of globalns and localns see the docstring for get_type_hints().
258 """
259 if isinstance(t, ForwardRef):
260 return t._evaluate(globalns, localns)
261 if isinstance(t, _GenericAlias):
262 ev_args = tuple(_eval_type(a, globalns, localns) for a in t.__args__)
263 if ev_args == t.__args__:
264 return t
265 res = t.copy_with(ev_args)
266 res._special = t._special
267 return res
268 return t
269
270
271class _Final:
272 """Mixin to prohibit subclassing"""
Guido van Rossum4cefe742016-09-27 15:20:12 -0700273
Guido van Rossum83ec3022017-01-17 20:43:28 -0800274 __slots__ = ('__weakref__',)
Guido van Rossum4cefe742016-09-27 15:20:12 -0700275
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000276 def __init_subclass__(self, *args, **kwds):
277 if '_root' not in kwds:
278 raise TypeError("Cannot subclass special typing classes")
279
Miss Islington (bot)d0e04c82018-03-26 15:29:06 -0700280class _Immutable:
281 """Mixin to indicate that object should not be copied."""
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000282
Miss Islington (bot)d0e04c82018-03-26 15:29:06 -0700283 def __copy__(self):
284 return self
285
286 def __deepcopy__(self, memo):
287 return self
288
289
290class _SpecialForm(_Final, _Immutable, _root=True):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000291 """Internal indicator of special typing constructs.
292 See _doc instance attribute for specific docs.
293 """
294
295 __slots__ = ('_name', '_doc')
296
Guido van Rossum4cefe742016-09-27 15:20:12 -0700297 def __new__(cls, *args, **kwds):
298 """Constructor.
299
300 This only exists to give a better error message in case
301 someone tries to subclass a special typing object (not a good idea).
302 """
303 if (len(args) == 3 and
304 isinstance(args[0], str) and
305 isinstance(args[1], tuple)):
306 # Close enough.
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000307 raise TypeError(f"Cannot subclass {cls!r}")
Guido van Rossumb47c9d22016-10-03 08:40:50 -0700308 return super().__new__(cls)
Guido van Rossum4cefe742016-09-27 15:20:12 -0700309
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000310 def __init__(self, name, doc):
311 self._name = name
312 self._doc = doc
Guido van Rossum4cefe742016-09-27 15:20:12 -0700313
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000314 def __eq__(self, other):
315 if not isinstance(other, _SpecialForm):
316 return NotImplemented
317 return self._name == other._name
318
319 def __hash__(self):
320 return hash((self._name,))
Guido van Rossum4cefe742016-09-27 15:20:12 -0700321
322 def __repr__(self):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000323 return 'typing.' + self._name
324
Miss Islington (bot)d0e04c82018-03-26 15:29:06 -0700325 def __reduce__(self):
326 return self._name
Guido van Rossum4cefe742016-09-27 15:20:12 -0700327
328 def __call__(self, *args, **kwds):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000329 raise TypeError(f"Cannot instantiate {self!r}")
330
331 def __instancecheck__(self, obj):
332 raise TypeError(f"{self} cannot be used with isinstance()")
333
334 def __subclasscheck__(self, cls):
335 raise TypeError(f"{self} cannot be used with issubclass()")
336
337 @_tp_cache
338 def __getitem__(self, parameters):
339 if self._name == 'ClassVar':
340 item = _type_check(parameters, 'ClassVar accepts only single type.')
341 return _GenericAlias(self, (item,))
342 if self._name == 'Union':
343 if parameters == ():
344 raise TypeError("Cannot take a Union of no types.")
345 if not isinstance(parameters, tuple):
346 parameters = (parameters,)
347 msg = "Union[arg, ...]: each arg must be a type."
348 parameters = tuple(_type_check(p, msg) for p in parameters)
349 parameters = _remove_dups_flatten(parameters)
350 if len(parameters) == 1:
351 return parameters[0]
352 return _GenericAlias(self, parameters)
353 if self._name == 'Optional':
354 arg = _type_check(parameters, "Optional[t] requires a single type.")
355 return Union[arg, type(None)]
356 raise TypeError(f"{self} is not subscriptable")
Guido van Rossum4cefe742016-09-27 15:20:12 -0700357
358
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000359Any = _SpecialForm('Any', doc=
360 """Special type indicating an unconstrained type.
Guido van Rossumb47c9d22016-10-03 08:40:50 -0700361
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000362 - Any is compatible with every type.
363 - Any assumed to have all methods.
364 - All values assumed to be instances of Any.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700365
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000366 Note that all the above statements are true from the point of view of
367 static type checkers. At runtime, Any should not be used with instance
368 or class checks.
369 """)
Guido van Rossumd70fe632015-08-05 12:11:06 +0200370
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000371NoReturn = _SpecialForm('NoReturn', doc=
372 """Special type indicating functions that never return.
373 Example::
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700374
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000375 from typing import NoReturn
376
377 def stop() -> NoReturn:
378 raise Exception('no way')
379
380 This type is invalid in other positions, e.g., ``List[NoReturn]``
381 will fail in static type checkers.
382 """)
383
384ClassVar = _SpecialForm('ClassVar', doc=
385 """Special type construct to mark class variables.
386
387 An annotation wrapped in ClassVar indicates that a given
388 attribute is intended to be used as a class variable and
389 should not be set on instances of that class. Usage::
390
391 class Starship:
392 stats: ClassVar[Dict[str, int]] = {} # class variable
393 damage: int = 10 # instance variable
394
395 ClassVar accepts only types and cannot be further subscribed.
396
397 Note that ClassVar is not a class itself, and should not
398 be used with isinstance() or issubclass().
399 """)
400
401Union = _SpecialForm('Union', doc=
402 """Union type; Union[X, Y] means either X or Y.
403
404 To define a union, use e.g. Union[int, str]. Details:
405 - The arguments must be types and there must be at least one.
406 - None as an argument is a special case and is replaced by
407 type(None).
408 - Unions of unions are flattened, e.g.::
409
410 Union[Union[int, str], float] == Union[int, str, float]
411
412 - Unions of a single argument vanish, e.g.::
413
414 Union[int] == int # The constructor actually returns int
415
416 - Redundant arguments are skipped, e.g.::
417
418 Union[int, str, int] == Union[int, str]
419
420 - When comparing unions, the argument order is ignored, e.g.::
421
422 Union[int, str] == Union[str, int]
423
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000424 - You cannot subclass or instantiate a union.
425 - You can use Optional[X] as a shorthand for Union[X, None].
426 """)
427
428Optional = _SpecialForm('Optional', doc=
429 """Optional type.
430
431 Optional[X] is equivalent to Union[X, None].
432 """)
Guido van Rossumb7dedc82016-10-29 12:44:29 -0700433
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700434
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000435class ForwardRef(_Final, _root=True):
Guido van Rossumb24569a2016-11-20 18:01:29 -0800436 """Internal wrapper to hold a forward reference."""
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700437
Guido van Rossum4cefe742016-09-27 15:20:12 -0700438 __slots__ = ('__forward_arg__', '__forward_code__',
Miss Islington (bot)9c17cd32018-05-16 15:04:39 -0700439 '__forward_evaluated__', '__forward_value__',
440 '__forward_is_argument__')
Guido van Rossum4cefe742016-09-27 15:20:12 -0700441
Miss Islington (bot)0f9b68a2018-05-22 20:51:15 -0700442 def __init__(self, arg, is_argument=True):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700443 if not isinstance(arg, str):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000444 raise TypeError(f"Forward reference must be a string -- got {arg!r}")
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700445 try:
446 code = compile(arg, '<string>', 'eval')
447 except SyntaxError:
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000448 raise SyntaxError(f"Forward reference must be an expression -- got {arg!r}")
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700449 self.__forward_arg__ = arg
450 self.__forward_code__ = code
451 self.__forward_evaluated__ = False
452 self.__forward_value__ = None
Miss Islington (bot)9c17cd32018-05-16 15:04:39 -0700453 self.__forward_is_argument__ = is_argument
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700454
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000455 def _evaluate(self, globalns, localns):
Guido van Rossumdad17902016-11-10 08:29:18 -0800456 if not self.__forward_evaluated__ or localns is not globalns:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700457 if globalns is None and localns is None:
458 globalns = localns = {}
459 elif globalns is None:
460 globalns = localns
461 elif localns is None:
462 localns = globalns
463 self.__forward_value__ = _type_check(
464 eval(self.__forward_code__, globalns, localns),
Miss Islington (bot)9c17cd32018-05-16 15:04:39 -0700465 "Forward references must evaluate to types.",
466 is_argument=self.__forward_is_argument__)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700467 self.__forward_evaluated__ = True
468 return self.__forward_value__
469
Guido van Rossum4cefe742016-09-27 15:20:12 -0700470 def __eq__(self, other):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000471 if not isinstance(other, ForwardRef):
Guido van Rossum4cefe742016-09-27 15:20:12 -0700472 return NotImplemented
473 return (self.__forward_arg__ == other.__forward_arg__ and
Guido van Rossumc7b92952016-11-10 08:24:06 -0800474 self.__forward_value__ == other.__forward_value__)
Guido van Rossum4cefe742016-09-27 15:20:12 -0700475
476 def __hash__(self):
Guido van Rossumc7b92952016-11-10 08:24:06 -0800477 return hash((self.__forward_arg__, self.__forward_value__))
Guido van Rossum4cefe742016-09-27 15:20:12 -0700478
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700479 def __repr__(self):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000480 return f'ForwardRef({self.__forward_arg__!r})'
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700481
482
Miss Islington (bot)d0e04c82018-03-26 15:29:06 -0700483class TypeVar(_Final, _Immutable, _root=True):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700484 """Type variable.
485
486 Usage::
487
488 T = TypeVar('T') # Can be anything
489 A = TypeVar('A', str, bytes) # Must be str or bytes
490
491 Type variables exist primarily for the benefit of static type
492 checkers. They serve as the parameters for generic types as well
493 as for generic function definitions. See class Generic for more
494 information on generic types. Generic functions work as follows:
495
Guido van Rossumb24569a2016-11-20 18:01:29 -0800496 def repeat(x: T, n: int) -> List[T]:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700497 '''Return a list containing n references to x.'''
498 return [x]*n
499
500 def longest(x: A, y: A) -> A:
501 '''Return the longest of two strings.'''
502 return x if len(x) >= len(y) else y
503
504 The latter example's signature is essentially the overloading
505 of (str, str) -> str and (bytes, bytes) -> bytes. Also note
506 that if the arguments are instances of some subclass of str,
507 the return type is still plain str.
508
Guido van Rossumb24569a2016-11-20 18:01:29 -0800509 At runtime, isinstance(x, T) and issubclass(C, T) will raise TypeError.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700510
Guido van Rossumefa798d2016-08-23 11:01:50 -0700511 Type variables defined with covariant=True or contravariant=True
Miss Islington (bot)e019f982018-07-07 09:05:36 -0700512 can be used to declare covariant or contravariant generic types.
Guido van Rossumefa798d2016-08-23 11:01:50 -0700513 See PEP 484 for more details. By default generic types are invariant
514 in all type variables.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700515
516 Type variables can be introspected. e.g.:
517
518 T.__name__ == 'T'
519 T.__constraints__ == ()
520 T.__covariant__ == False
521 T.__contravariant__ = False
522 A.__constraints__ == (str, bytes)
Miss Islington (bot)d0e04c82018-03-26 15:29:06 -0700523
524 Note that only type variables defined in global scope can be pickled.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700525 """
526
Guido van Rossum4cefe742016-09-27 15:20:12 -0700527 __slots__ = ('__name__', '__bound__', '__constraints__',
Miss Islington (bot)d4986252018-05-26 11:38:00 -0700528 '__covariant__', '__contravariant__')
Guido van Rossum4cefe742016-09-27 15:20:12 -0700529
530 def __init__(self, name, *constraints, bound=None,
Guido van Rossumd7adfe12017-01-22 17:43:53 -0800531 covariant=False, contravariant=False):
Guido van Rossum4cefe742016-09-27 15:20:12 -0700532 self.__name__ = name
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700533 if covariant and contravariant:
Guido van Rossumefa798d2016-08-23 11:01:50 -0700534 raise ValueError("Bivariant types are not supported.")
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700535 self.__covariant__ = bool(covariant)
536 self.__contravariant__ = bool(contravariant)
537 if constraints and bound is not None:
538 raise TypeError("Constraints cannot be combined with bound=...")
539 if constraints and len(constraints) == 1:
540 raise TypeError("A single constraint is not allowed")
541 msg = "TypeVar(name, constraint, ...): constraints must be types."
542 self.__constraints__ = tuple(_type_check(t, msg) for t in constraints)
543 if bound:
544 self.__bound__ = _type_check(bound, "Bound must be a type.")
545 else:
546 self.__bound__ = None
Miss Islington (bot)d4986252018-05-26 11:38:00 -0700547 def_mod = sys._getframe(1).f_globals['__name__'] # for pickling
548 if def_mod != 'typing':
549 self.__module__ = def_mod
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700550
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700551 def __repr__(self):
552 if self.__covariant__:
553 prefix = '+'
554 elif self.__contravariant__:
555 prefix = '-'
556 else:
557 prefix = '~'
558 return prefix + self.__name__
559
Miss Islington (bot)d0e04c82018-03-26 15:29:06 -0700560 def __reduce__(self):
Miss Islington (bot)d4986252018-05-26 11:38:00 -0700561 return self.__name__
Miss Islington (bot)d0e04c82018-03-26 15:29:06 -0700562
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700563
Guido van Rossum83ec3022017-01-17 20:43:28 -0800564# Special typing constructs Union, Optional, Generic, Callable and Tuple
565# use three special attributes for internal bookkeeping of generic types:
566# * __parameters__ is a tuple of unique free type parameters of a generic
567# type, for example, Dict[T, T].__parameters__ == (T,);
568# * __origin__ keeps a reference to a type that was subscripted,
Miss Islington (bot)3c28a632018-05-08 18:44:09 -0700569# e.g., Union[T, int].__origin__ == Union, or the non-generic version of
570# the type.
Guido van Rossum83ec3022017-01-17 20:43:28 -0800571# * __args__ is a tuple of all arguments used in subscripting,
572# e.g., Dict[T, int].__args__ == (T, int).
573
Miss Islington (bot)04eac022018-04-04 17:46:40 -0700574
575# Mapping from non-generic type names that have a generic alias in typing
576# but with a different name.
577_normalize_alias = {'list': 'List',
578 'tuple': 'Tuple',
579 'dict': 'Dict',
580 'set': 'Set',
581 'frozenset': 'FrozenSet',
582 'deque': 'Deque',
583 'defaultdict': 'DefaultDict',
584 'type': 'Type',
585 'Set': 'AbstractSet'}
586
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000587def _is_dunder(attr):
588 return attr.startswith('__') and attr.endswith('__')
Guido van Rossum83ec3022017-01-17 20:43:28 -0800589
Guido van Rossumb24569a2016-11-20 18:01:29 -0800590
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000591class _GenericAlias(_Final, _root=True):
592 """The central part of internal API.
593
594 This represents a generic version of type 'origin' with type arguments 'params'.
595 There are two kind of these aliases: user defined and special. The special ones
596 are wrappers around builtin collections and ABCs in collections.abc. These must
597 have 'name' always set. If 'inst' is False, then the alias can't be instantiated,
598 this is used by e.g. typing.List and typing.Dict.
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700599 """
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000600 def __init__(self, origin, params, *, inst=True, special=False, name=None):
601 self._inst = inst
602 self._special = special
603 if special and name is None:
604 orig_name = origin.__name__
Miss Islington (bot)04eac022018-04-04 17:46:40 -0700605 name = _normalize_alias.get(orig_name, orig_name)
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000606 self._name = name
607 if not isinstance(params, tuple):
608 params = (params,)
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700609 self.__origin__ = origin
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700610 self.__args__ = tuple(... if a is _TypingEllipsis else
611 () if a is _TypingEmpty else
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000612 a for a in params)
613 self.__parameters__ = _collect_type_vars(params)
614 self.__slots__ = None # This is not documented.
615 if not name:
616 self.__module__ = origin.__module__
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700617
Guido van Rossum4cefe742016-09-27 15:20:12 -0700618 @_tp_cache
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700619 def __getitem__(self, params):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000620 if self.__origin__ in (Generic, _Protocol):
621 # Can't subscript Generic[...] or _Protocol[...].
622 raise TypeError(f"Cannot subscript already-subscripted {self}")
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700623 if not isinstance(params, tuple):
624 params = (params,)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700625 msg = "Parameters to generic types must be types."
626 params = tuple(_type_check(p, msg) for p in params)
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000627 _check_generic(self, params)
628 return _subs_tvars(self, self.__parameters__, params)
Ivan Levkivskyib692dc82017-02-13 22:50:14 +0100629
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000630 def copy_with(self, params):
631 # We don't copy self._special.
632 return _GenericAlias(self.__origin__, params, name=self._name, inst=self._inst)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700633
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000634 def __repr__(self):
635 if (self._name != 'Callable' or
636 len(self.__args__) == 2 and self.__args__[0] is Ellipsis):
637 if self._name:
638 name = 'typing.' + self._name
639 else:
640 name = _type_repr(self.__origin__)
641 if not self._special:
642 args = f'[{", ".join([_type_repr(a) for a in self.__args__])}]'
643 else:
644 args = ''
645 return (f'{name}{args}')
646 if self._special:
647 return 'typing.Callable'
648 return (f'typing.Callable'
649 f'[[{", ".join([_type_repr(a) for a in self.__args__[:-1]])}], '
650 f'{_type_repr(self.__args__[-1])}]')
651
652 def __eq__(self, other):
653 if not isinstance(other, _GenericAlias):
654 return NotImplemented
655 if self.__origin__ != other.__origin__:
Ivan Levkivskyib692dc82017-02-13 22:50:14 +0100656 return False
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000657 if self.__origin__ is Union and other.__origin__ is Union:
658 return frozenset(self.__args__) == frozenset(other.__args__)
659 return self.__args__ == other.__args__
Ivan Levkivskyib692dc82017-02-13 22:50:14 +0100660
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000661 def __hash__(self):
662 if self.__origin__ is Union:
663 return hash((Union, frozenset(self.__args__)))
664 return hash((self.__origin__, self.__args__))
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700665
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000666 def __call__(self, *args, **kwargs):
667 if not self._inst:
668 raise TypeError(f"Type {self._name} cannot be instantiated; "
669 f"use {self._name.lower()}() instead")
670 result = self.__origin__(*args, **kwargs)
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700671 try:
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000672 result.__orig_class__ = self
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700673 except AttributeError:
674 pass
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000675 return result
676
677 def __mro_entries__(self, bases):
678 if self._name: # generic version of an ABC or built-in class
679 res = []
680 if self.__origin__ not in bases:
681 res.append(self.__origin__)
682 i = bases.index(self)
683 if not any(isinstance(b, _GenericAlias) or issubclass(b, Generic)
684 for b in bases[i+1:]):
685 res.append(Generic)
686 return tuple(res)
687 if self.__origin__ is Generic:
688 i = bases.index(self)
689 for b in bases[i+1:]:
690 if isinstance(b, _GenericAlias) and b is not self:
691 return ()
692 return (self.__origin__,)
693
694 def __getattr__(self, attr):
Miss Islington (bot)32955292018-04-20 14:00:41 -0700695 # We are careful for copy and pickle.
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000696 # Also for simplicity we just don't relay all dunder names
697 if '__origin__' in self.__dict__ and not _is_dunder(attr):
698 return getattr(self.__origin__, attr)
699 raise AttributeError(attr)
700
701 def __setattr__(self, attr, val):
702 if _is_dunder(attr) or attr in ('_name', '_inst', '_special'):
703 super().__setattr__(attr, val)
704 else:
705 setattr(self.__origin__, attr, val)
706
707 def __instancecheck__(self, obj):
708 return self.__subclasscheck__(type(obj))
709
710 def __subclasscheck__(self, cls):
711 if self._special:
712 if not isinstance(cls, _GenericAlias):
713 return issubclass(cls, self.__origin__)
714 if cls._special:
715 return issubclass(cls.__origin__, self.__origin__)
716 raise TypeError("Subscripted generics cannot be used with"
717 " class and instance checks")
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700718
Miss Islington (bot)d0e04c82018-03-26 15:29:06 -0700719 def __reduce__(self):
720 if self._special:
721 return self._name
Miss Islington (bot)d4986252018-05-26 11:38:00 -0700722
723 if self._name:
724 origin = globals()[self._name]
725 else:
726 origin = self.__origin__
727 if (origin is Callable and
728 not (len(self.__args__) == 2 and self.__args__[0] is Ellipsis)):
729 args = list(self.__args__[:-1]), self.__args__[-1]
730 else:
731 args = tuple(self.__args__)
732 if len(args) == 1 and not isinstance(args[0], tuple):
733 args, = args
734 return operator.getitem, (origin, args)
Miss Islington (bot)d0e04c82018-03-26 15:29:06 -0700735
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700736
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000737class _VariadicGenericAlias(_GenericAlias, _root=True):
738 """Same as _GenericAlias above but for variadic aliases. Currently,
739 this is used only by special internal aliases: Tuple and Callable.
740 """
741 def __getitem__(self, params):
742 if self._name != 'Callable' or not self._special:
743 return self.__getitem_inner__(params)
744 if not isinstance(params, tuple) or len(params) != 2:
745 raise TypeError("Callable must be used as "
746 "Callable[[arg, ...], result].")
747 args, result = params
748 if args is Ellipsis:
749 params = (Ellipsis, result)
750 else:
751 if not isinstance(args, list):
752 raise TypeError(f"Callable[args, result]: args must be a list."
753 f" Got {args}")
754 params = (tuple(args), result)
755 return self.__getitem_inner__(params)
756
757 @_tp_cache
758 def __getitem_inner__(self, params):
759 if self.__origin__ is tuple and self._special:
760 if params == ():
761 return self.copy_with((_TypingEmpty,))
762 if not isinstance(params, tuple):
763 params = (params,)
764 if len(params) == 2 and params[1] is ...:
765 msg = "Tuple[t, ...]: t must be a type."
766 p = _type_check(params[0], msg)
767 return self.copy_with((p, _TypingEllipsis))
768 msg = "Tuple[t0, t1, ...]: each t must be a type."
769 params = tuple(_type_check(p, msg) for p in params)
770 return self.copy_with(params)
771 if self.__origin__ is collections.abc.Callable and self._special:
772 args, result = params
773 msg = "Callable[args, result]: result must be a type."
774 result = _type_check(result, msg)
775 if args is Ellipsis:
776 return self.copy_with((_TypingEllipsis, result))
777 msg = "Callable[[arg, ...], result]: each arg must be a type."
778 args = tuple(_type_check(arg, msg) for arg in args)
779 params = args + (result,)
780 return self.copy_with(params)
781 return super().__getitem__(params)
782
783
784class Generic:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700785 """Abstract base class for generic types.
786
Guido van Rossumb24569a2016-11-20 18:01:29 -0800787 A generic type is typically declared by inheriting from
788 this class parameterized with one or more type variables.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700789 For example, a generic mapping type might be defined as::
790
791 class Mapping(Generic[KT, VT]):
792 def __getitem__(self, key: KT) -> VT:
793 ...
794 # Etc.
795
796 This class can then be used as follows::
797
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700798 def lookup_name(mapping: Mapping[KT, VT], key: KT, default: VT) -> VT:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700799 try:
800 return mapping[key]
801 except KeyError:
802 return default
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700803 """
Guido van Rossumd70fe632015-08-05 12:11:06 +0200804 __slots__ = ()
805
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700806 def __new__(cls, *args, **kwds):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000807 if cls is Generic:
Guido van Rossum62fe1bb2016-10-29 16:05:26 -0700808 raise TypeError("Type Generic cannot be instantiated; "
809 "it can be used only as a base class")
Miss Islington (bot)c5444b32018-05-10 20:30:47 -0700810 if super().__new__ is object.__new__ and cls.__init__ is not object.__init__:
Miss Islington (bot)3c28a632018-05-08 18:44:09 -0700811 obj = super().__new__(cls)
812 else:
813 obj = super().__new__(cls, *args, **kwds)
814 return obj
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000815
816 @_tp_cache
817 def __class_getitem__(cls, params):
818 if not isinstance(params, tuple):
819 params = (params,)
820 if not params and cls is not Tuple:
821 raise TypeError(
822 f"Parameter list to {cls.__qualname__}[...] cannot be empty")
823 msg = "Parameters to generic types must be types."
824 params = tuple(_type_check(p, msg) for p in params)
825 if cls is Generic:
826 # Generic can only be subscripted with unique type variables.
827 if not all(isinstance(p, TypeVar) for p in params):
828 raise TypeError(
829 "Parameters to Generic[...] must all be type variables")
830 if len(set(params)) != len(params):
831 raise TypeError(
832 "Parameters to Generic[...] must all be unique")
833 elif cls is _Protocol:
834 # _Protocol is internal at the moment, just skip the check
835 pass
836 else:
837 # Subscripting a regular Generic subclass.
838 _check_generic(cls, params)
839 return _GenericAlias(cls, params)
840
841 def __init_subclass__(cls, *args, **kwargs):
Miss Islington (bot)bd85c972018-04-04 09:51:34 -0700842 super().__init_subclass__(*args, **kwargs)
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000843 tvars = []
844 if '__orig_bases__' in cls.__dict__:
845 error = Generic in cls.__orig_bases__
846 else:
847 error = Generic in cls.__bases__ and cls.__name__ != '_Protocol'
848 if error:
849 raise TypeError("Cannot inherit from plain Generic")
850 if '__orig_bases__' in cls.__dict__:
851 tvars = _collect_type_vars(cls.__orig_bases__)
852 # Look for Generic[T1, ..., Tn].
853 # If found, tvars must be a subset of it.
854 # If not found, tvars is it.
855 # Also check for and reject plain Generic,
856 # and reject multiple Generic[...].
857 gvars = None
858 for base in cls.__orig_bases__:
859 if (isinstance(base, _GenericAlias) and
860 base.__origin__ is Generic):
861 if gvars is not None:
862 raise TypeError(
863 "Cannot inherit from Generic[...] multiple types.")
864 gvars = base.__parameters__
865 if gvars is None:
866 gvars = tvars
867 else:
868 tvarset = set(tvars)
869 gvarset = set(gvars)
870 if not tvarset <= gvarset:
871 s_vars = ', '.join(str(t) for t in tvars if t not in gvarset)
872 s_args = ', '.join(str(g) for g in gvars)
873 raise TypeError(f"Some type variables ({s_vars}) are"
874 f" not listed in Generic[{s_args}]")
875 tvars = gvars
876 cls.__parameters__ = tuple(tvars)
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700877
878
879class _TypingEmpty:
Guido van Rossumb24569a2016-11-20 18:01:29 -0800880 """Internal placeholder for () or []. Used by TupleMeta and CallableMeta
881 to allow empty list/tuple in specific places, without allowing them
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700882 to sneak in where prohibited.
883 """
884
885
886class _TypingEllipsis:
Guido van Rossumb24569a2016-11-20 18:01:29 -0800887 """Internal placeholder for ... (ellipsis)."""
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700888
889
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700890def cast(typ, val):
891 """Cast a value to a type.
892
893 This returns the value unchanged. To the type checker this
894 signals that the return value has the designated type, but at
895 runtime we intentionally don't check anything (we want this
896 to be as fast as possible).
897 """
898 return val
899
900
901def _get_defaults(func):
902 """Internal helper to extract the default arguments, by name."""
Guido van Rossum991d14f2016-11-09 13:12:51 -0800903 try:
904 code = func.__code__
905 except AttributeError:
906 # Some built-in functions don't have __code__, __defaults__, etc.
907 return {}
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700908 pos_count = code.co_argcount
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700909 arg_names = code.co_varnames
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700910 arg_names = arg_names[:pos_count]
911 defaults = func.__defaults__ or ()
912 kwdefaults = func.__kwdefaults__
913 res = dict(kwdefaults) if kwdefaults else {}
914 pos_offset = pos_count - len(defaults)
915 for name, value in zip(arg_names[pos_offset:], defaults):
916 assert name not in res
917 res[name] = value
918 return res
919
920
Ivan Levkivskyib692dc82017-02-13 22:50:14 +0100921_allowed_types = (types.FunctionType, types.BuiltinFunctionType,
922 types.MethodType, types.ModuleType,
Ivan Levkivskyif06e0212017-05-02 19:14:07 +0200923 WrapperDescriptorType, MethodWrapperType, MethodDescriptorType)
Ivan Levkivskyib692dc82017-02-13 22:50:14 +0100924
925
Guido van Rossum991d14f2016-11-09 13:12:51 -0800926def get_type_hints(obj, globalns=None, localns=None):
927 """Return type hints for an object.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700928
Guido van Rossum991d14f2016-11-09 13:12:51 -0800929 This is often the same as obj.__annotations__, but it handles
930 forward references encoded as string literals, and if necessary
931 adds Optional[t] if a default value equal to None is set.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700932
Guido van Rossum991d14f2016-11-09 13:12:51 -0800933 The argument may be a module, class, method, or function. The annotations
934 are returned as a dictionary. For classes, annotations include also
935 inherited members.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700936
Guido van Rossum991d14f2016-11-09 13:12:51 -0800937 TypeError is raised if the argument is not of a type that can contain
938 annotations, and an empty dictionary is returned if no annotations are
939 present.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700940
Guido van Rossum991d14f2016-11-09 13:12:51 -0800941 BEWARE -- the behavior of globalns and localns is counterintuitive
942 (unless you are familiar with how eval() and exec() work). The
943 search order is locals first, then globals.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700944
Guido van Rossum991d14f2016-11-09 13:12:51 -0800945 - If no dict arguments are passed, an attempt is made to use the
Łukasz Langaf350a262017-09-14 14:33:00 -0400946 globals from obj (or the respective module's globals for classes),
947 and these are also used as the locals. If the object does not appear
948 to have globals, an empty dictionary is used.
Guido van Rossum0a6976d2016-09-11 15:34:56 -0700949
Guido van Rossum991d14f2016-11-09 13:12:51 -0800950 - If one dict argument is passed, it is used for both globals and
951 locals.
Guido van Rossum0a6976d2016-09-11 15:34:56 -0700952
Guido van Rossum991d14f2016-11-09 13:12:51 -0800953 - If two dict arguments are passed, they specify globals and
954 locals, respectively.
955 """
Guido van Rossum0a6976d2016-09-11 15:34:56 -0700956
Guido van Rossum991d14f2016-11-09 13:12:51 -0800957 if getattr(obj, '__no_type_check__', None):
958 return {}
Guido van Rossum991d14f2016-11-09 13:12:51 -0800959 # Classes require a special treatment.
960 if isinstance(obj, type):
961 hints = {}
962 for base in reversed(obj.__mro__):
Łukasz Langaf350a262017-09-14 14:33:00 -0400963 if globalns is None:
964 base_globals = sys.modules[base.__module__].__dict__
965 else:
966 base_globals = globalns
Guido van Rossum991d14f2016-11-09 13:12:51 -0800967 ann = base.__dict__.get('__annotations__', {})
968 for name, value in ann.items():
969 if value is None:
970 value = type(None)
971 if isinstance(value, str):
Miss Islington (bot)0f9b68a2018-05-22 20:51:15 -0700972 value = ForwardRef(value, is_argument=False)
Łukasz Langaf350a262017-09-14 14:33:00 -0400973 value = _eval_type(value, base_globals, localns)
Guido van Rossum991d14f2016-11-09 13:12:51 -0800974 hints[name] = value
975 return hints
Łukasz Langaf350a262017-09-14 14:33:00 -0400976
977 if globalns is None:
978 if isinstance(obj, types.ModuleType):
979 globalns = obj.__dict__
980 else:
981 globalns = getattr(obj, '__globals__', {})
982 if localns is None:
983 localns = globalns
984 elif localns is None:
985 localns = globalns
Guido van Rossum991d14f2016-11-09 13:12:51 -0800986 hints = getattr(obj, '__annotations__', None)
987 if hints is None:
988 # Return empty annotations for something that _could_ have them.
Ivan Levkivskyib692dc82017-02-13 22:50:14 +0100989 if isinstance(obj, _allowed_types):
Guido van Rossum0a6976d2016-09-11 15:34:56 -0700990 return {}
Guido van Rossum991d14f2016-11-09 13:12:51 -0800991 else:
992 raise TypeError('{!r} is not a module, class, method, '
993 'or function.'.format(obj))
994 defaults = _get_defaults(obj)
995 hints = dict(hints)
996 for name, value in hints.items():
997 if value is None:
998 value = type(None)
999 if isinstance(value, str):
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001000 value = ForwardRef(value)
Guido van Rossum991d14f2016-11-09 13:12:51 -08001001 value = _eval_type(value, globalns, localns)
1002 if name in defaults and defaults[name] is None:
1003 value = Optional[value]
1004 hints[name] = value
1005 return hints
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001006
1007
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001008def no_type_check(arg):
1009 """Decorator to indicate that annotations are not type hints.
1010
1011 The argument must be a class or function; if it is a class, it
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001012 applies recursively to all methods and classes defined in that class
1013 (but not to methods defined in its superclasses or subclasses).
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001014
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001015 This mutates the function(s) or class(es) in place.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001016 """
1017 if isinstance(arg, type):
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001018 arg_attrs = arg.__dict__.copy()
1019 for attr, val in arg.__dict__.items():
Ivan Levkivskyi65bc6202017-09-14 01:25:15 +02001020 if val in arg.__bases__ + (arg,):
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001021 arg_attrs.pop(attr)
1022 for obj in arg_attrs.values():
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001023 if isinstance(obj, types.FunctionType):
1024 obj.__no_type_check__ = True
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001025 if isinstance(obj, type):
1026 no_type_check(obj)
1027 try:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001028 arg.__no_type_check__ = True
Guido van Rossumd7adfe12017-01-22 17:43:53 -08001029 except TypeError: # built-in classes
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001030 pass
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001031 return arg
1032
1033
1034def no_type_check_decorator(decorator):
1035 """Decorator to give another decorator the @no_type_check effect.
1036
1037 This wraps the decorator with something that wraps the decorated
1038 function in @no_type_check.
1039 """
1040
1041 @functools.wraps(decorator)
1042 def wrapped_decorator(*args, **kwds):
1043 func = decorator(*args, **kwds)
1044 func = no_type_check(func)
1045 return func
1046
1047 return wrapped_decorator
1048
1049
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001050def _overload_dummy(*args, **kwds):
1051 """Helper for @overload to raise when called."""
1052 raise NotImplementedError(
1053 "You should not call an overloaded function. "
1054 "A series of @overload-decorated functions "
1055 "outside a stub module should always be followed "
1056 "by an implementation that is not @overload-ed.")
1057
1058
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001059def overload(func):
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001060 """Decorator for overloaded functions/methods.
1061
1062 In a stub file, place two or more stub definitions for the same
1063 function in a row, each decorated with @overload. For example:
1064
1065 @overload
1066 def utf8(value: None) -> None: ...
1067 @overload
1068 def utf8(value: bytes) -> bytes: ...
1069 @overload
1070 def utf8(value: str) -> bytes: ...
1071
1072 In a non-stub file (i.e. a regular .py file), do the same but
1073 follow it with an implementation. The implementation should *not*
1074 be decorated with @overload. For example:
1075
1076 @overload
1077 def utf8(value: None) -> None: ...
1078 @overload
1079 def utf8(value: bytes) -> bytes: ...
1080 @overload
1081 def utf8(value: str) -> bytes: ...
1082 def utf8(value):
1083 # implementation goes here
1084 """
1085 return _overload_dummy
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001086
1087
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001088class _ProtocolMeta(type):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001089 """Internal metaclass for _Protocol.
1090
1091 This exists so _Protocol classes can be generic without deriving
1092 from Generic.
1093 """
1094
Guido van Rossumd70fe632015-08-05 12:11:06 +02001095 def __instancecheck__(self, obj):
Guido van Rossumca4b2522016-11-19 10:32:41 -08001096 if _Protocol not in self.__bases__:
1097 return super().__instancecheck__(obj)
Guido van Rossumd70fe632015-08-05 12:11:06 +02001098 raise TypeError("Protocols cannot be used with isinstance().")
1099
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001100 def __subclasscheck__(self, cls):
1101 if not self._is_protocol:
1102 # No structural checks since this isn't a protocol.
1103 return NotImplemented
1104
1105 if self is _Protocol:
1106 # Every class is a subclass of the empty protocol.
1107 return True
1108
1109 # Find all attributes defined in the protocol.
1110 attrs = self._get_protocol_attrs()
1111
1112 for attr in attrs:
1113 if not any(attr in d.__dict__ for d in cls.__mro__):
1114 return False
1115 return True
1116
1117 def _get_protocol_attrs(self):
1118 # Get all Protocol base classes.
1119 protocol_bases = []
1120 for c in self.__mro__:
1121 if getattr(c, '_is_protocol', False) and c.__name__ != '_Protocol':
1122 protocol_bases.append(c)
1123
1124 # Get attributes included in protocol.
1125 attrs = set()
1126 for base in protocol_bases:
1127 for attr in base.__dict__.keys():
1128 # Include attributes not defined in any non-protocol bases.
1129 for c in self.__mro__:
1130 if (c is not base and attr in c.__dict__ and
1131 not getattr(c, '_is_protocol', False)):
1132 break
1133 else:
1134 if (not attr.startswith('_abc_') and
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001135 attr != '__abstractmethods__' and
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001136 attr != '__annotations__' and
1137 attr != '__weakref__' and
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001138 attr != '_is_protocol' and
Ivan Levkivskyi65bc6202017-09-14 01:25:15 +02001139 attr != '_gorg' and
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001140 attr != '__dict__' and
1141 attr != '__args__' and
1142 attr != '__slots__' and
1143 attr != '_get_protocol_attrs' and
1144 attr != '__next_in_mro__' and
1145 attr != '__parameters__' and
1146 attr != '__origin__' and
Guido van Rossum7ef22d62016-10-21 14:27:58 -07001147 attr != '__orig_bases__' and
Guido van Rossum1cea70f2016-05-18 08:35:00 -07001148 attr != '__extra__' and
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001149 attr != '__tree_hash__' and
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001150 attr != '__module__'):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001151 attrs.add(attr)
1152
1153 return attrs
1154
1155
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001156class _Protocol(Generic, metaclass=_ProtocolMeta):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001157 """Internal base class for protocol classes.
1158
Guido van Rossumb24569a2016-11-20 18:01:29 -08001159 This implements a simple-minded structural issubclass check
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001160 (similar but more general than the one-offs in collections.abc
1161 such as Hashable).
1162 """
1163
Guido van Rossumd70fe632015-08-05 12:11:06 +02001164 __slots__ = ()
1165
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001166 _is_protocol = True
1167
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001168 def __class_getitem__(cls, params):
1169 return super().__class_getitem__(params)
1170
1171
1172# Some unconstrained type variables. These are used by the container types.
1173# (These are not for export.)
1174T = TypeVar('T') # Any type.
1175KT = TypeVar('KT') # Key type.
1176VT = TypeVar('VT') # Value type.
1177T_co = TypeVar('T_co', covariant=True) # Any type covariant containers.
1178V_co = TypeVar('V_co', covariant=True) # Any type covariant containers.
1179VT_co = TypeVar('VT_co', covariant=True) # Value type covariant containers.
1180T_contra = TypeVar('T_contra', contravariant=True) # Ditto contravariant.
1181# Internal type variable used for Type[].
1182CT_co = TypeVar('CT_co', covariant=True, bound=type)
1183
1184# A useful type variable with constraints. This represents string types.
1185# (This one *is* for export!)
1186AnyStr = TypeVar('AnyStr', bytes, str)
1187
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001188
1189# Various ABCs mimicking those in collections.abc.
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001190def _alias(origin, params, inst=True):
1191 return _GenericAlias(origin, params, special=True, inst=inst)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001192
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001193Hashable = _alias(collections.abc.Hashable, ()) # Not generic.
1194Awaitable = _alias(collections.abc.Awaitable, T_co)
1195Coroutine = _alias(collections.abc.Coroutine, (T_co, T_contra, V_co))
1196AsyncIterable = _alias(collections.abc.AsyncIterable, T_co)
1197AsyncIterator = _alias(collections.abc.AsyncIterator, T_co)
1198Iterable = _alias(collections.abc.Iterable, T_co)
1199Iterator = _alias(collections.abc.Iterator, T_co)
1200Reversible = _alias(collections.abc.Reversible, T_co)
1201Sized = _alias(collections.abc.Sized, ()) # Not generic.
1202Container = _alias(collections.abc.Container, T_co)
1203Collection = _alias(collections.abc.Collection, T_co)
1204Callable = _VariadicGenericAlias(collections.abc.Callable, (), special=True)
1205Callable.__doc__ = \
1206 """Callable type; Callable[[int], str] is a function of (int) -> str.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001207
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001208 The subscription syntax must always be used with exactly two
1209 values: the argument list and the return type. The argument list
1210 must be a list of types or ellipsis; the return type must be a single type.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001211
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001212 There is no syntax to indicate optional or keyword arguments,
1213 such function types are rarely used as callback types.
1214 """
1215AbstractSet = _alias(collections.abc.Set, T_co)
1216MutableSet = _alias(collections.abc.MutableSet, T)
1217# NOTE: Mapping is only covariant in the value type.
1218Mapping = _alias(collections.abc.Mapping, (KT, VT_co))
1219MutableMapping = _alias(collections.abc.MutableMapping, (KT, VT))
1220Sequence = _alias(collections.abc.Sequence, T_co)
1221MutableSequence = _alias(collections.abc.MutableSequence, T)
1222ByteString = _alias(collections.abc.ByteString, ()) # Not generic
1223Tuple = _VariadicGenericAlias(tuple, (), inst=False, special=True)
1224Tuple.__doc__ = \
1225 """Tuple type; Tuple[X, Y] is the cross-product type of X and Y.
Guido van Rossum62fe1bb2016-10-29 16:05:26 -07001226
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001227 Example: Tuple[T1, T2] is a tuple of two elements corresponding
1228 to type variables T1 and T2. Tuple[int, float, str] is a tuple
1229 of an int, a float and a string.
Guido van Rossum62fe1bb2016-10-29 16:05:26 -07001230
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001231 To specify a variable-length tuple of homogeneous type, use Tuple[T, ...].
1232 """
1233List = _alias(list, T, inst=False)
1234Deque = _alias(collections.deque, T)
1235Set = _alias(set, T, inst=False)
1236FrozenSet = _alias(frozenset, T_co, inst=False)
1237MappingView = _alias(collections.abc.MappingView, T_co)
1238KeysView = _alias(collections.abc.KeysView, KT)
1239ItemsView = _alias(collections.abc.ItemsView, (KT, VT_co))
1240ValuesView = _alias(collections.abc.ValuesView, VT_co)
1241ContextManager = _alias(contextlib.AbstractContextManager, T_co)
1242AsyncContextManager = _alias(contextlib.AbstractAsyncContextManager, T_co)
1243Dict = _alias(dict, (KT, VT), inst=False)
1244DefaultDict = _alias(collections.defaultdict, (KT, VT))
Miss Islington (bot)6cb04862018-12-02 08:14:44 -08001245OrderedDict = _alias(collections.OrderedDict, (KT, VT))
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001246Counter = _alias(collections.Counter, T)
1247ChainMap = _alias(collections.ChainMap, (KT, VT))
1248Generator = _alias(collections.abc.Generator, (T_co, T_contra, V_co))
1249AsyncGenerator = _alias(collections.abc.AsyncGenerator, (T_co, T_contra))
1250Type = _alias(type, CT_co, inst=False)
1251Type.__doc__ = \
1252 """A special construct usable to annotate class objects.
Guido van Rossum62fe1bb2016-10-29 16:05:26 -07001253
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001254 For example, suppose we have the following classes::
Guido van Rossum62fe1bb2016-10-29 16:05:26 -07001255
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001256 class User: ... # Abstract base for User classes
1257 class BasicUser(User): ...
1258 class ProUser(User): ...
1259 class TeamUser(User): ...
Guido van Rossumf17c2002015-12-03 17:31:24 -08001260
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001261 And a function that takes a class argument that's a subclass of
1262 User and returns an instance of the corresponding class::
Guido van Rossumf17c2002015-12-03 17:31:24 -08001263
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001264 U = TypeVar('U', bound=User)
1265 def new_user(user_class: Type[U]) -> U:
1266 user = user_class()
1267 # (Here we could write the user object to a database)
1268 return user
Guido van Rossumf17c2002015-12-03 17:31:24 -08001269
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001270 joe = new_user(BasicUser)
Guido van Rossumf17c2002015-12-03 17:31:24 -08001271
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001272 At this point the type checker knows that joe has type BasicUser.
1273 """
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001274
1275
1276class SupportsInt(_Protocol):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001277 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001278
1279 @abstractmethod
1280 def __int__(self) -> int:
1281 pass
1282
1283
1284class SupportsFloat(_Protocol):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001285 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001286
1287 @abstractmethod
1288 def __float__(self) -> float:
1289 pass
1290
1291
1292class SupportsComplex(_Protocol):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001293 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001294
1295 @abstractmethod
1296 def __complex__(self) -> complex:
1297 pass
1298
1299
1300class SupportsBytes(_Protocol):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001301 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001302
1303 @abstractmethod
1304 def __bytes__(self) -> bytes:
1305 pass
1306
1307
Guido van Rossumd70fe632015-08-05 12:11:06 +02001308class SupportsAbs(_Protocol[T_co]):
1309 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001310
1311 @abstractmethod
Guido van Rossumd70fe632015-08-05 12:11:06 +02001312 def __abs__(self) -> T_co:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001313 pass
1314
1315
Guido van Rossumd70fe632015-08-05 12:11:06 +02001316class SupportsRound(_Protocol[T_co]):
1317 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001318
1319 @abstractmethod
Guido van Rossumd70fe632015-08-05 12:11:06 +02001320 def __round__(self, ndigits: int = 0) -> T_co:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001321 pass
1322
1323
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001324def _make_nmtuple(name, types):
Guido van Rossum2f841442016-11-15 09:48:06 -08001325 msg = "NamedTuple('Name', [(f0, t0), (f1, t1), ...]); each t must be a type"
1326 types = [(n, _type_check(t, msg)) for n, t in types]
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001327 nm_tpl = collections.namedtuple(name, [n for n, t in types])
Guido van Rossum83ec3022017-01-17 20:43:28 -08001328 # Prior to PEP 526, only _field_types attribute was assigned.
1329 # Now, both __annotations__ and _field_types are used to maintain compatibility.
1330 nm_tpl.__annotations__ = nm_tpl._field_types = collections.OrderedDict(types)
Guido van Rossum557d1eb2015-11-19 08:16:31 -08001331 try:
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001332 nm_tpl.__module__ = sys._getframe(2).f_globals.get('__name__', '__main__')
Guido van Rossum557d1eb2015-11-19 08:16:31 -08001333 except (AttributeError, ValueError):
1334 pass
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001335 return nm_tpl
1336
1337
Ivan Levkivskyib692dc82017-02-13 22:50:14 +01001338# attributes prohibited to set in NamedTuple class syntax
1339_prohibited = ('__new__', '__init__', '__slots__', '__getnewargs__',
1340 '_fields', '_field_defaults', '_field_types',
Ivan Levkivskyif06e0212017-05-02 19:14:07 +02001341 '_make', '_replace', '_asdict', '_source')
Ivan Levkivskyib692dc82017-02-13 22:50:14 +01001342
1343_special = ('__module__', '__name__', '__qualname__', '__annotations__')
1344
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001345
Guido van Rossum2f841442016-11-15 09:48:06 -08001346class NamedTupleMeta(type):
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001347
Guido van Rossum2f841442016-11-15 09:48:06 -08001348 def __new__(cls, typename, bases, ns):
1349 if ns.get('_root', False):
1350 return super().__new__(cls, typename, bases, ns)
Guido van Rossum2f841442016-11-15 09:48:06 -08001351 types = ns.get('__annotations__', {})
Guido van Rossum3c268be2017-01-18 08:03:50 -08001352 nm_tpl = _make_nmtuple(typename, types.items())
1353 defaults = []
1354 defaults_dict = {}
1355 for field_name in types:
1356 if field_name in ns:
1357 default_value = ns[field_name]
1358 defaults.append(default_value)
1359 defaults_dict[field_name] = default_value
1360 elif defaults:
Guido van Rossumd7adfe12017-01-22 17:43:53 -08001361 raise TypeError("Non-default namedtuple field {field_name} cannot "
1362 "follow default field(s) {default_names}"
Guido van Rossum3c268be2017-01-18 08:03:50 -08001363 .format(field_name=field_name,
1364 default_names=', '.join(defaults_dict.keys())))
Miss Islington (bot)3c28a632018-05-08 18:44:09 -07001365 nm_tpl.__new__.__annotations__ = collections.OrderedDict(types)
Guido van Rossum3c268be2017-01-18 08:03:50 -08001366 nm_tpl.__new__.__defaults__ = tuple(defaults)
1367 nm_tpl._field_defaults = defaults_dict
Guido van Rossum95919c02017-01-22 17:47:20 -08001368 # update from user namespace without overriding special namedtuple attributes
1369 for key in ns:
Ivan Levkivskyib692dc82017-02-13 22:50:14 +01001370 if key in _prohibited:
1371 raise AttributeError("Cannot overwrite NamedTuple attribute " + key)
1372 elif key not in _special and key not in nm_tpl._fields:
Guido van Rossum95919c02017-01-22 17:47:20 -08001373 setattr(nm_tpl, key, ns[key])
Guido van Rossum3c268be2017-01-18 08:03:50 -08001374 return nm_tpl
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001375
Guido van Rossumd7adfe12017-01-22 17:43:53 -08001376
Guido van Rossum2f841442016-11-15 09:48:06 -08001377class NamedTuple(metaclass=NamedTupleMeta):
1378 """Typed version of namedtuple.
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001379
Guido van Rossum2f841442016-11-15 09:48:06 -08001380 Usage in Python versions >= 3.6::
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001381
Guido van Rossum2f841442016-11-15 09:48:06 -08001382 class Employee(NamedTuple):
1383 name: str
1384 id: int
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001385
Guido van Rossum2f841442016-11-15 09:48:06 -08001386 This is equivalent to::
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001387
Guido van Rossum2f841442016-11-15 09:48:06 -08001388 Employee = collections.namedtuple('Employee', ['name', 'id'])
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001389
Guido van Rossum83ec3022017-01-17 20:43:28 -08001390 The resulting class has extra __annotations__ and _field_types
1391 attributes, giving an ordered dict mapping field names to types.
1392 __annotations__ should be preferred, while _field_types
1393 is kept to maintain pre PEP 526 compatibility. (The field names
Guido van Rossum2f841442016-11-15 09:48:06 -08001394 are in the _fields attribute, which is part of the namedtuple
1395 API.) Alternative equivalent keyword syntax is also accepted::
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001396
Guido van Rossum2f841442016-11-15 09:48:06 -08001397 Employee = NamedTuple('Employee', name=str, id=int)
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001398
Guido van Rossum2f841442016-11-15 09:48:06 -08001399 In Python versions <= 3.5 use::
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001400
Guido van Rossum2f841442016-11-15 09:48:06 -08001401 Employee = NamedTuple('Employee', [('name', str), ('id', int)])
1402 """
1403 _root = True
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001404
Guido van Rossum2f841442016-11-15 09:48:06 -08001405 def __new__(self, typename, fields=None, **kwargs):
Guido van Rossum2f841442016-11-15 09:48:06 -08001406 if fields is None:
1407 fields = kwargs.items()
1408 elif kwargs:
1409 raise TypeError("Either list of fields or keywords"
1410 " can be provided to NamedTuple, not both")
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001411 return _make_nmtuple(typename, fields)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001412
1413
Guido van Rossum91185fe2016-06-08 11:19:11 -07001414def NewType(name, tp):
1415 """NewType creates simple unique types with almost zero
1416 runtime overhead. NewType(name, tp) is considered a subtype of tp
1417 by static type checkers. At runtime, NewType(name, tp) returns
1418 a dummy function that simply returns its argument. Usage::
1419
1420 UserId = NewType('UserId', int)
1421
1422 def name_by_id(user_id: UserId) -> str:
1423 ...
1424
1425 UserId('user') # Fails type check
1426
1427 name_by_id(42) # Fails type check
1428 name_by_id(UserId(42)) # OK
1429
1430 num = UserId(5) + 1 # type: int
1431 """
1432
1433 def new_type(x):
1434 return x
1435
1436 new_type.__name__ = name
1437 new_type.__supertype__ = tp
1438 return new_type
1439
1440
Guido van Rossum0e0563c2016-04-05 14:54:25 -07001441# Python-version-specific alias (Python 2: unicode; Python 3: str)
1442Text = str
1443
1444
Guido van Rossum91185fe2016-06-08 11:19:11 -07001445# Constant that's True when type checking, but False here.
1446TYPE_CHECKING = False
1447
1448
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001449class IO(Generic[AnyStr]):
1450 """Generic base class for TextIO and BinaryIO.
1451
1452 This is an abstract, generic version of the return of open().
1453
1454 NOTE: This does not distinguish between the different possible
1455 classes (text vs. binary, read vs. write vs. read/write,
1456 append-only, unbuffered). The TextIO and BinaryIO subclasses
1457 below capture the distinctions between text vs. binary, which is
1458 pervasive in the interface; however we currently do not offer a
1459 way to track the other distinctions in the type system.
1460 """
1461
Guido van Rossumd70fe632015-08-05 12:11:06 +02001462 __slots__ = ()
1463
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001464 @abstractproperty
1465 def mode(self) -> str:
1466 pass
1467
1468 @abstractproperty
1469 def name(self) -> str:
1470 pass
1471
1472 @abstractmethod
1473 def close(self) -> None:
1474 pass
1475
1476 @abstractmethod
1477 def closed(self) -> bool:
1478 pass
1479
1480 @abstractmethod
1481 def fileno(self) -> int:
1482 pass
1483
1484 @abstractmethod
1485 def flush(self) -> None:
1486 pass
1487
1488 @abstractmethod
1489 def isatty(self) -> bool:
1490 pass
1491
1492 @abstractmethod
1493 def read(self, n: int = -1) -> AnyStr:
1494 pass
1495
1496 @abstractmethod
1497 def readable(self) -> bool:
1498 pass
1499
1500 @abstractmethod
1501 def readline(self, limit: int = -1) -> AnyStr:
1502 pass
1503
1504 @abstractmethod
1505 def readlines(self, hint: int = -1) -> List[AnyStr]:
1506 pass
1507
1508 @abstractmethod
1509 def seek(self, offset: int, whence: int = 0) -> int:
1510 pass
1511
1512 @abstractmethod
1513 def seekable(self) -> bool:
1514 pass
1515
1516 @abstractmethod
1517 def tell(self) -> int:
1518 pass
1519
1520 @abstractmethod
1521 def truncate(self, size: int = None) -> int:
1522 pass
1523
1524 @abstractmethod
1525 def writable(self) -> bool:
1526 pass
1527
1528 @abstractmethod
1529 def write(self, s: AnyStr) -> int:
1530 pass
1531
1532 @abstractmethod
1533 def writelines(self, lines: List[AnyStr]) -> None:
1534 pass
1535
1536 @abstractmethod
1537 def __enter__(self) -> 'IO[AnyStr]':
1538 pass
1539
1540 @abstractmethod
1541 def __exit__(self, type, value, traceback) -> None:
1542 pass
1543
1544
1545class BinaryIO(IO[bytes]):
1546 """Typed version of the return of open() in binary mode."""
1547
Guido van Rossumd70fe632015-08-05 12:11:06 +02001548 __slots__ = ()
1549
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001550 @abstractmethod
1551 def write(self, s: Union[bytes, bytearray]) -> int:
1552 pass
1553
1554 @abstractmethod
1555 def __enter__(self) -> 'BinaryIO':
1556 pass
1557
1558
1559class TextIO(IO[str]):
1560 """Typed version of the return of open() in text mode."""
1561
Guido van Rossumd70fe632015-08-05 12:11:06 +02001562 __slots__ = ()
1563
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001564 @abstractproperty
1565 def buffer(self) -> BinaryIO:
1566 pass
1567
1568 @abstractproperty
1569 def encoding(self) -> str:
1570 pass
1571
1572 @abstractproperty
Guido van Rossum991d14f2016-11-09 13:12:51 -08001573 def errors(self) -> Optional[str]:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001574 pass
1575
1576 @abstractproperty
1577 def line_buffering(self) -> bool:
1578 pass
1579
1580 @abstractproperty
1581 def newlines(self) -> Any:
1582 pass
1583
1584 @abstractmethod
1585 def __enter__(self) -> 'TextIO':
1586 pass
1587
1588
1589class io:
1590 """Wrapper namespace for IO generic classes."""
1591
1592 __all__ = ['IO', 'TextIO', 'BinaryIO']
1593 IO = IO
1594 TextIO = TextIO
1595 BinaryIO = BinaryIO
1596
Guido van Rossumd7adfe12017-01-22 17:43:53 -08001597
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001598io.__name__ = __name__ + '.io'
1599sys.modules[io.__name__] = io
1600
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001601Pattern = _alias(stdlib_re.Pattern, AnyStr)
1602Match = _alias(stdlib_re.Match, AnyStr)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001603
1604class re:
1605 """Wrapper namespace for re type aliases."""
1606
1607 __all__ = ['Pattern', 'Match']
1608 Pattern = Pattern
1609 Match = Match
1610
Guido van Rossumd7adfe12017-01-22 17:43:53 -08001611
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001612re.__name__ = __name__ + '.re'
1613sys.modules[re.__name__] = re