blob: e9265afce491655075123a5aecc8d10838f235ec [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:
5* Imports and exports, all public names should be explicitelly added to __all__.
6* 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")
133 if (isinstance(arg, _SpecialForm) and arg is not Any or
134 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
297 def __getstate__(self):
298 return {'name': self._name, 'doc': self._doc}
299
300 def __setstate__(self, state):
301 self._name = state['name']
302 self._doc = state['doc']
Guido van Rossum4cefe742016-09-27 15:20:12 -0700303
304 def __new__(cls, *args, **kwds):
305 """Constructor.
306
307 This only exists to give a better error message in case
308 someone tries to subclass a special typing object (not a good idea).
309 """
310 if (len(args) == 3 and
311 isinstance(args[0], str) and
312 isinstance(args[1], tuple)):
313 # Close enough.
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000314 raise TypeError(f"Cannot subclass {cls!r}")
Guido van Rossumb47c9d22016-10-03 08:40:50 -0700315 return super().__new__(cls)
Guido van Rossum4cefe742016-09-27 15:20:12 -0700316
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000317 def __init__(self, name, doc):
318 self._name = name
319 self._doc = doc
Guido van Rossum4cefe742016-09-27 15:20:12 -0700320
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000321 def __eq__(self, other):
322 if not isinstance(other, _SpecialForm):
323 return NotImplemented
324 return self._name == other._name
325
326 def __hash__(self):
327 return hash((self._name,))
Guido van Rossum4cefe742016-09-27 15:20:12 -0700328
329 def __repr__(self):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000330 return 'typing.' + self._name
331
Miss Islington (bot)d0e04c82018-03-26 15:29:06 -0700332 def __reduce__(self):
333 return self._name
Guido van Rossum4cefe742016-09-27 15:20:12 -0700334
335 def __call__(self, *args, **kwds):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000336 raise TypeError(f"Cannot instantiate {self!r}")
337
338 def __instancecheck__(self, obj):
339 raise TypeError(f"{self} cannot be used with isinstance()")
340
341 def __subclasscheck__(self, cls):
342 raise TypeError(f"{self} cannot be used with issubclass()")
343
344 @_tp_cache
345 def __getitem__(self, parameters):
346 if self._name == 'ClassVar':
347 item = _type_check(parameters, 'ClassVar accepts only single type.')
348 return _GenericAlias(self, (item,))
349 if self._name == 'Union':
350 if parameters == ():
351 raise TypeError("Cannot take a Union of no types.")
352 if not isinstance(parameters, tuple):
353 parameters = (parameters,)
354 msg = "Union[arg, ...]: each arg must be a type."
355 parameters = tuple(_type_check(p, msg) for p in parameters)
356 parameters = _remove_dups_flatten(parameters)
357 if len(parameters) == 1:
358 return parameters[0]
359 return _GenericAlias(self, parameters)
360 if self._name == 'Optional':
361 arg = _type_check(parameters, "Optional[t] requires a single type.")
362 return Union[arg, type(None)]
363 raise TypeError(f"{self} is not subscriptable")
Guido van Rossum4cefe742016-09-27 15:20:12 -0700364
365
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000366Any = _SpecialForm('Any', doc=
367 """Special type indicating an unconstrained type.
Guido van Rossumb47c9d22016-10-03 08:40:50 -0700368
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000369 - Any is compatible with every type.
370 - Any assumed to have all methods.
371 - All values assumed to be instances of Any.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700372
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000373 Note that all the above statements are true from the point of view of
374 static type checkers. At runtime, Any should not be used with instance
375 or class checks.
376 """)
Guido van Rossumd70fe632015-08-05 12:11:06 +0200377
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000378NoReturn = _SpecialForm('NoReturn', doc=
379 """Special type indicating functions that never return.
380 Example::
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700381
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000382 from typing import NoReturn
383
384 def stop() -> NoReturn:
385 raise Exception('no way')
386
387 This type is invalid in other positions, e.g., ``List[NoReturn]``
388 will fail in static type checkers.
389 """)
390
391ClassVar = _SpecialForm('ClassVar', doc=
392 """Special type construct to mark class variables.
393
394 An annotation wrapped in ClassVar indicates that a given
395 attribute is intended to be used as a class variable and
396 should not be set on instances of that class. Usage::
397
398 class Starship:
399 stats: ClassVar[Dict[str, int]] = {} # class variable
400 damage: int = 10 # instance variable
401
402 ClassVar accepts only types and cannot be further subscribed.
403
404 Note that ClassVar is not a class itself, and should not
405 be used with isinstance() or issubclass().
406 """)
407
408Union = _SpecialForm('Union', doc=
409 """Union type; Union[X, Y] means either X or Y.
410
411 To define a union, use e.g. Union[int, str]. Details:
412 - The arguments must be types and there must be at least one.
413 - None as an argument is a special case and is replaced by
414 type(None).
415 - Unions of unions are flattened, e.g.::
416
417 Union[Union[int, str], float] == Union[int, str, float]
418
419 - Unions of a single argument vanish, e.g.::
420
421 Union[int] == int # The constructor actually returns int
422
423 - Redundant arguments are skipped, e.g.::
424
425 Union[int, str, int] == Union[int, str]
426
427 - When comparing unions, the argument order is ignored, e.g.::
428
429 Union[int, str] == Union[str, int]
430
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000431 - You cannot subclass or instantiate a union.
432 - You can use Optional[X] as a shorthand for Union[X, None].
433 """)
434
435Optional = _SpecialForm('Optional', doc=
436 """Optional type.
437
438 Optional[X] is equivalent to Union[X, None].
439 """)
Guido van Rossumb7dedc82016-10-29 12:44:29 -0700440
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700441
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000442class ForwardRef(_Final, _root=True):
Guido van Rossumb24569a2016-11-20 18:01:29 -0800443 """Internal wrapper to hold a forward reference."""
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700444
Guido van Rossum4cefe742016-09-27 15:20:12 -0700445 __slots__ = ('__forward_arg__', '__forward_code__',
Miss Islington (bot)9c17cd32018-05-16 15:04:39 -0700446 '__forward_evaluated__', '__forward_value__',
447 '__forward_is_argument__')
Guido van Rossum4cefe742016-09-27 15:20:12 -0700448
Miss Islington (bot)0f9b68a2018-05-22 20:51:15 -0700449 def __init__(self, arg, is_argument=True):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700450 if not isinstance(arg, str):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000451 raise TypeError(f"Forward reference must be a string -- got {arg!r}")
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700452 try:
453 code = compile(arg, '<string>', 'eval')
454 except SyntaxError:
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000455 raise SyntaxError(f"Forward reference must be an expression -- got {arg!r}")
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700456 self.__forward_arg__ = arg
457 self.__forward_code__ = code
458 self.__forward_evaluated__ = False
459 self.__forward_value__ = None
Miss Islington (bot)9c17cd32018-05-16 15:04:39 -0700460 self.__forward_is_argument__ = is_argument
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700461
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000462 def _evaluate(self, globalns, localns):
Guido van Rossumdad17902016-11-10 08:29:18 -0800463 if not self.__forward_evaluated__ or localns is not globalns:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700464 if globalns is None and localns is None:
465 globalns = localns = {}
466 elif globalns is None:
467 globalns = localns
468 elif localns is None:
469 localns = globalns
470 self.__forward_value__ = _type_check(
471 eval(self.__forward_code__, globalns, localns),
Miss Islington (bot)9c17cd32018-05-16 15:04:39 -0700472 "Forward references must evaluate to types.",
473 is_argument=self.__forward_is_argument__)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700474 self.__forward_evaluated__ = True
475 return self.__forward_value__
476
Guido van Rossum4cefe742016-09-27 15:20:12 -0700477 def __eq__(self, other):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000478 if not isinstance(other, ForwardRef):
Guido van Rossum4cefe742016-09-27 15:20:12 -0700479 return NotImplemented
480 return (self.__forward_arg__ == other.__forward_arg__ and
Guido van Rossumc7b92952016-11-10 08:24:06 -0800481 self.__forward_value__ == other.__forward_value__)
Guido van Rossum4cefe742016-09-27 15:20:12 -0700482
483 def __hash__(self):
Guido van Rossumc7b92952016-11-10 08:24:06 -0800484 return hash((self.__forward_arg__, self.__forward_value__))
Guido van Rossum4cefe742016-09-27 15:20:12 -0700485
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700486 def __repr__(self):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000487 return f'ForwardRef({self.__forward_arg__!r})'
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700488
489
Miss Islington (bot)d0e04c82018-03-26 15:29:06 -0700490class TypeVar(_Final, _Immutable, _root=True):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700491 """Type variable.
492
493 Usage::
494
495 T = TypeVar('T') # Can be anything
496 A = TypeVar('A', str, bytes) # Must be str or bytes
497
498 Type variables exist primarily for the benefit of static type
499 checkers. They serve as the parameters for generic types as well
500 as for generic function definitions. See class Generic for more
501 information on generic types. Generic functions work as follows:
502
Guido van Rossumb24569a2016-11-20 18:01:29 -0800503 def repeat(x: T, n: int) -> List[T]:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700504 '''Return a list containing n references to x.'''
505 return [x]*n
506
507 def longest(x: A, y: A) -> A:
508 '''Return the longest of two strings.'''
509 return x if len(x) >= len(y) else y
510
511 The latter example's signature is essentially the overloading
512 of (str, str) -> str and (bytes, bytes) -> bytes. Also note
513 that if the arguments are instances of some subclass of str,
514 the return type is still plain str.
515
Guido van Rossumb24569a2016-11-20 18:01:29 -0800516 At runtime, isinstance(x, T) and issubclass(C, T) will raise TypeError.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700517
Guido van Rossumefa798d2016-08-23 11:01:50 -0700518 Type variables defined with covariant=True or contravariant=True
519 can be used do declare covariant or contravariant generic types.
520 See PEP 484 for more details. By default generic types are invariant
521 in all type variables.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700522
523 Type variables can be introspected. e.g.:
524
525 T.__name__ == 'T'
526 T.__constraints__ == ()
527 T.__covariant__ == False
528 T.__contravariant__ = False
529 A.__constraints__ == (str, bytes)
Miss Islington (bot)d0e04c82018-03-26 15:29:06 -0700530
531 Note that only type variables defined in global scope can be pickled.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700532 """
533
Guido van Rossum4cefe742016-09-27 15:20:12 -0700534 __slots__ = ('__name__', '__bound__', '__constraints__',
Miss Islington (bot)d4986252018-05-26 11:38:00 -0700535 '__covariant__', '__contravariant__')
Guido van Rossum4cefe742016-09-27 15:20:12 -0700536
537 def __init__(self, name, *constraints, bound=None,
Guido van Rossumd7adfe12017-01-22 17:43:53 -0800538 covariant=False, contravariant=False):
Guido van Rossum4cefe742016-09-27 15:20:12 -0700539 self.__name__ = name
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700540 if covariant and contravariant:
Guido van Rossumefa798d2016-08-23 11:01:50 -0700541 raise ValueError("Bivariant types are not supported.")
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700542 self.__covariant__ = bool(covariant)
543 self.__contravariant__ = bool(contravariant)
544 if constraints and bound is not None:
545 raise TypeError("Constraints cannot be combined with bound=...")
546 if constraints and len(constraints) == 1:
547 raise TypeError("A single constraint is not allowed")
548 msg = "TypeVar(name, constraint, ...): constraints must be types."
549 self.__constraints__ = tuple(_type_check(t, msg) for t in constraints)
550 if bound:
551 self.__bound__ = _type_check(bound, "Bound must be a type.")
552 else:
553 self.__bound__ = None
Miss Islington (bot)d4986252018-05-26 11:38:00 -0700554 def_mod = sys._getframe(1).f_globals['__name__'] # for pickling
555 if def_mod != 'typing':
556 self.__module__ = def_mod
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700557
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000558 def __getstate__(self):
559 return {'name': self.__name__,
560 'bound': self.__bound__,
561 'constraints': self.__constraints__,
562 'co': self.__covariant__,
563 'contra': self.__contravariant__}
564
565 def __setstate__(self, state):
566 self.__name__ = state['name']
567 self.__bound__ = state['bound']
568 self.__constraints__ = state['constraints']
569 self.__covariant__ = state['co']
570 self.__contravariant__ = state['contra']
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700571
572 def __repr__(self):
573 if self.__covariant__:
574 prefix = '+'
575 elif self.__contravariant__:
576 prefix = '-'
577 else:
578 prefix = '~'
579 return prefix + self.__name__
580
Miss Islington (bot)d0e04c82018-03-26 15:29:06 -0700581 def __reduce__(self):
Miss Islington (bot)d4986252018-05-26 11:38:00 -0700582 return self.__name__
Miss Islington (bot)d0e04c82018-03-26 15:29:06 -0700583
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700584
Guido van Rossum83ec3022017-01-17 20:43:28 -0800585# Special typing constructs Union, Optional, Generic, Callable and Tuple
586# use three special attributes for internal bookkeeping of generic types:
587# * __parameters__ is a tuple of unique free type parameters of a generic
588# type, for example, Dict[T, T].__parameters__ == (T,);
589# * __origin__ keeps a reference to a type that was subscripted,
Miss Islington (bot)3c28a632018-05-08 18:44:09 -0700590# e.g., Union[T, int].__origin__ == Union, or the non-generic version of
591# the type.
Guido van Rossum83ec3022017-01-17 20:43:28 -0800592# * __args__ is a tuple of all arguments used in subscripting,
593# e.g., Dict[T, int].__args__ == (T, int).
594
Miss Islington (bot)04eac022018-04-04 17:46:40 -0700595
596# Mapping from non-generic type names that have a generic alias in typing
597# but with a different name.
598_normalize_alias = {'list': 'List',
599 'tuple': 'Tuple',
600 'dict': 'Dict',
601 'set': 'Set',
602 'frozenset': 'FrozenSet',
603 'deque': 'Deque',
604 'defaultdict': 'DefaultDict',
605 'type': 'Type',
606 'Set': 'AbstractSet'}
607
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000608def _is_dunder(attr):
609 return attr.startswith('__') and attr.endswith('__')
Guido van Rossum83ec3022017-01-17 20:43:28 -0800610
Guido van Rossumb24569a2016-11-20 18:01:29 -0800611
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000612class _GenericAlias(_Final, _root=True):
613 """The central part of internal API.
614
615 This represents a generic version of type 'origin' with type arguments 'params'.
616 There are two kind of these aliases: user defined and special. The special ones
617 are wrappers around builtin collections and ABCs in collections.abc. These must
618 have 'name' always set. If 'inst' is False, then the alias can't be instantiated,
619 this is used by e.g. typing.List and typing.Dict.
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700620 """
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000621 def __init__(self, origin, params, *, inst=True, special=False, name=None):
622 self._inst = inst
623 self._special = special
624 if special and name is None:
625 orig_name = origin.__name__
Miss Islington (bot)04eac022018-04-04 17:46:40 -0700626 name = _normalize_alias.get(orig_name, orig_name)
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000627 self._name = name
628 if not isinstance(params, tuple):
629 params = (params,)
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700630 self.__origin__ = origin
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700631 self.__args__ = tuple(... if a is _TypingEllipsis else
632 () if a is _TypingEmpty else
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000633 a for a in params)
634 self.__parameters__ = _collect_type_vars(params)
635 self.__slots__ = None # This is not documented.
636 if not name:
637 self.__module__ = origin.__module__
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700638
Guido van Rossum4cefe742016-09-27 15:20:12 -0700639 @_tp_cache
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700640 def __getitem__(self, params):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000641 if self.__origin__ in (Generic, _Protocol):
642 # Can't subscript Generic[...] or _Protocol[...].
643 raise TypeError(f"Cannot subscript already-subscripted {self}")
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700644 if not isinstance(params, tuple):
645 params = (params,)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700646 msg = "Parameters to generic types must be types."
647 params = tuple(_type_check(p, msg) for p in params)
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000648 _check_generic(self, params)
649 return _subs_tvars(self, self.__parameters__, params)
Ivan Levkivskyib692dc82017-02-13 22:50:14 +0100650
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000651 def copy_with(self, params):
652 # We don't copy self._special.
653 return _GenericAlias(self.__origin__, params, name=self._name, inst=self._inst)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700654
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000655 def __repr__(self):
656 if (self._name != 'Callable' or
657 len(self.__args__) == 2 and self.__args__[0] is Ellipsis):
658 if self._name:
659 name = 'typing.' + self._name
660 else:
661 name = _type_repr(self.__origin__)
662 if not self._special:
663 args = f'[{", ".join([_type_repr(a) for a in self.__args__])}]'
664 else:
665 args = ''
666 return (f'{name}{args}')
667 if self._special:
668 return 'typing.Callable'
669 return (f'typing.Callable'
670 f'[[{", ".join([_type_repr(a) for a in self.__args__[:-1]])}], '
671 f'{_type_repr(self.__args__[-1])}]')
672
673 def __eq__(self, other):
674 if not isinstance(other, _GenericAlias):
675 return NotImplemented
676 if self.__origin__ != other.__origin__:
Ivan Levkivskyib692dc82017-02-13 22:50:14 +0100677 return False
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000678 if self.__origin__ is Union and other.__origin__ is Union:
679 return frozenset(self.__args__) == frozenset(other.__args__)
680 return self.__args__ == other.__args__
Ivan Levkivskyib692dc82017-02-13 22:50:14 +0100681
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000682 def __hash__(self):
683 if self.__origin__ is Union:
684 return hash((Union, frozenset(self.__args__)))
685 return hash((self.__origin__, self.__args__))
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700686
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000687 def __call__(self, *args, **kwargs):
688 if not self._inst:
689 raise TypeError(f"Type {self._name} cannot be instantiated; "
690 f"use {self._name.lower()}() instead")
691 result = self.__origin__(*args, **kwargs)
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700692 try:
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000693 result.__orig_class__ = self
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700694 except AttributeError:
695 pass
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000696 return result
697
698 def __mro_entries__(self, bases):
699 if self._name: # generic version of an ABC or built-in class
700 res = []
701 if self.__origin__ not in bases:
702 res.append(self.__origin__)
703 i = bases.index(self)
704 if not any(isinstance(b, _GenericAlias) or issubclass(b, Generic)
705 for b in bases[i+1:]):
706 res.append(Generic)
707 return tuple(res)
708 if self.__origin__ is Generic:
709 i = bases.index(self)
710 for b in bases[i+1:]:
711 if isinstance(b, _GenericAlias) and b is not self:
712 return ()
713 return (self.__origin__,)
714
715 def __getattr__(self, attr):
Miss Islington (bot)32955292018-04-20 14:00:41 -0700716 # We are careful for copy and pickle.
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000717 # Also for simplicity we just don't relay all dunder names
718 if '__origin__' in self.__dict__ and not _is_dunder(attr):
719 return getattr(self.__origin__, attr)
720 raise AttributeError(attr)
721
722 def __setattr__(self, attr, val):
723 if _is_dunder(attr) or attr in ('_name', '_inst', '_special'):
724 super().__setattr__(attr, val)
725 else:
726 setattr(self.__origin__, attr, val)
727
728 def __instancecheck__(self, obj):
729 return self.__subclasscheck__(type(obj))
730
731 def __subclasscheck__(self, cls):
732 if self._special:
733 if not isinstance(cls, _GenericAlias):
734 return issubclass(cls, self.__origin__)
735 if cls._special:
736 return issubclass(cls.__origin__, self.__origin__)
737 raise TypeError("Subscripted generics cannot be used with"
738 " class and instance checks")
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700739
Miss Islington (bot)d0e04c82018-03-26 15:29:06 -0700740 def __reduce__(self):
741 if self._special:
742 return self._name
Miss Islington (bot)d4986252018-05-26 11:38:00 -0700743
744 if self._name:
745 origin = globals()[self._name]
746 else:
747 origin = self.__origin__
748 if (origin is Callable and
749 not (len(self.__args__) == 2 and self.__args__[0] is Ellipsis)):
750 args = list(self.__args__[:-1]), self.__args__[-1]
751 else:
752 args = tuple(self.__args__)
753 if len(args) == 1 and not isinstance(args[0], tuple):
754 args, = args
755 return operator.getitem, (origin, args)
Miss Islington (bot)d0e04c82018-03-26 15:29:06 -0700756
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700757
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000758class _VariadicGenericAlias(_GenericAlias, _root=True):
759 """Same as _GenericAlias above but for variadic aliases. Currently,
760 this is used only by special internal aliases: Tuple and Callable.
761 """
762 def __getitem__(self, params):
763 if self._name != 'Callable' or not self._special:
764 return self.__getitem_inner__(params)
765 if not isinstance(params, tuple) or len(params) != 2:
766 raise TypeError("Callable must be used as "
767 "Callable[[arg, ...], result].")
768 args, result = params
769 if args is Ellipsis:
770 params = (Ellipsis, result)
771 else:
772 if not isinstance(args, list):
773 raise TypeError(f"Callable[args, result]: args must be a list."
774 f" Got {args}")
775 params = (tuple(args), result)
776 return self.__getitem_inner__(params)
777
778 @_tp_cache
779 def __getitem_inner__(self, params):
780 if self.__origin__ is tuple and self._special:
781 if params == ():
782 return self.copy_with((_TypingEmpty,))
783 if not isinstance(params, tuple):
784 params = (params,)
785 if len(params) == 2 and params[1] is ...:
786 msg = "Tuple[t, ...]: t must be a type."
787 p = _type_check(params[0], msg)
788 return self.copy_with((p, _TypingEllipsis))
789 msg = "Tuple[t0, t1, ...]: each t must be a type."
790 params = tuple(_type_check(p, msg) for p in params)
791 return self.copy_with(params)
792 if self.__origin__ is collections.abc.Callable and self._special:
793 args, result = params
794 msg = "Callable[args, result]: result must be a type."
795 result = _type_check(result, msg)
796 if args is Ellipsis:
797 return self.copy_with((_TypingEllipsis, result))
798 msg = "Callable[[arg, ...], result]: each arg must be a type."
799 args = tuple(_type_check(arg, msg) for arg in args)
800 params = args + (result,)
801 return self.copy_with(params)
802 return super().__getitem__(params)
803
804
805class Generic:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700806 """Abstract base class for generic types.
807
Guido van Rossumb24569a2016-11-20 18:01:29 -0800808 A generic type is typically declared by inheriting from
809 this class parameterized with one or more type variables.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700810 For example, a generic mapping type might be defined as::
811
812 class Mapping(Generic[KT, VT]):
813 def __getitem__(self, key: KT) -> VT:
814 ...
815 # Etc.
816
817 This class can then be used as follows::
818
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700819 def lookup_name(mapping: Mapping[KT, VT], key: KT, default: VT) -> VT:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700820 try:
821 return mapping[key]
822 except KeyError:
823 return default
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700824 """
Guido van Rossumd70fe632015-08-05 12:11:06 +0200825 __slots__ = ()
826
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700827 def __new__(cls, *args, **kwds):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000828 if cls is Generic:
Guido van Rossum62fe1bb2016-10-29 16:05:26 -0700829 raise TypeError("Type Generic cannot be instantiated; "
830 "it can be used only as a base class")
Miss Islington (bot)c5444b32018-05-10 20:30:47 -0700831 if super().__new__ is object.__new__ and cls.__init__ is not object.__init__:
Miss Islington (bot)3c28a632018-05-08 18:44:09 -0700832 obj = super().__new__(cls)
833 else:
834 obj = super().__new__(cls, *args, **kwds)
835 return obj
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000836
837 @_tp_cache
838 def __class_getitem__(cls, params):
839 if not isinstance(params, tuple):
840 params = (params,)
841 if not params and cls is not Tuple:
842 raise TypeError(
843 f"Parameter list to {cls.__qualname__}[...] cannot be empty")
844 msg = "Parameters to generic types must be types."
845 params = tuple(_type_check(p, msg) for p in params)
846 if cls is Generic:
847 # Generic can only be subscripted with unique type variables.
848 if not all(isinstance(p, TypeVar) for p in params):
849 raise TypeError(
850 "Parameters to Generic[...] must all be type variables")
851 if len(set(params)) != len(params):
852 raise TypeError(
853 "Parameters to Generic[...] must all be unique")
854 elif cls is _Protocol:
855 # _Protocol is internal at the moment, just skip the check
856 pass
857 else:
858 # Subscripting a regular Generic subclass.
859 _check_generic(cls, params)
860 return _GenericAlias(cls, params)
861
862 def __init_subclass__(cls, *args, **kwargs):
Miss Islington (bot)bd85c972018-04-04 09:51:34 -0700863 super().__init_subclass__(*args, **kwargs)
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000864 tvars = []
865 if '__orig_bases__' in cls.__dict__:
866 error = Generic in cls.__orig_bases__
867 else:
868 error = Generic in cls.__bases__ and cls.__name__ != '_Protocol'
869 if error:
870 raise TypeError("Cannot inherit from plain Generic")
871 if '__orig_bases__' in cls.__dict__:
872 tvars = _collect_type_vars(cls.__orig_bases__)
873 # Look for Generic[T1, ..., Tn].
874 # If found, tvars must be a subset of it.
875 # If not found, tvars is it.
876 # Also check for and reject plain Generic,
877 # and reject multiple Generic[...].
878 gvars = None
879 for base in cls.__orig_bases__:
880 if (isinstance(base, _GenericAlias) and
881 base.__origin__ is Generic):
882 if gvars is not None:
883 raise TypeError(
884 "Cannot inherit from Generic[...] multiple types.")
885 gvars = base.__parameters__
886 if gvars is None:
887 gvars = tvars
888 else:
889 tvarset = set(tvars)
890 gvarset = set(gvars)
891 if not tvarset <= gvarset:
892 s_vars = ', '.join(str(t) for t in tvars if t not in gvarset)
893 s_args = ', '.join(str(g) for g in gvars)
894 raise TypeError(f"Some type variables ({s_vars}) are"
895 f" not listed in Generic[{s_args}]")
896 tvars = gvars
897 cls.__parameters__ = tuple(tvars)
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700898
899
900class _TypingEmpty:
Guido van Rossumb24569a2016-11-20 18:01:29 -0800901 """Internal placeholder for () or []. Used by TupleMeta and CallableMeta
902 to allow empty list/tuple in specific places, without allowing them
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700903 to sneak in where prohibited.
904 """
905
906
907class _TypingEllipsis:
Guido van Rossumb24569a2016-11-20 18:01:29 -0800908 """Internal placeholder for ... (ellipsis)."""
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700909
910
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700911def cast(typ, val):
912 """Cast a value to a type.
913
914 This returns the value unchanged. To the type checker this
915 signals that the return value has the designated type, but at
916 runtime we intentionally don't check anything (we want this
917 to be as fast as possible).
918 """
919 return val
920
921
922def _get_defaults(func):
923 """Internal helper to extract the default arguments, by name."""
Guido van Rossum991d14f2016-11-09 13:12:51 -0800924 try:
925 code = func.__code__
926 except AttributeError:
927 # Some built-in functions don't have __code__, __defaults__, etc.
928 return {}
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700929 pos_count = code.co_argcount
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700930 arg_names = code.co_varnames
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700931 arg_names = arg_names[:pos_count]
932 defaults = func.__defaults__ or ()
933 kwdefaults = func.__kwdefaults__
934 res = dict(kwdefaults) if kwdefaults else {}
935 pos_offset = pos_count - len(defaults)
936 for name, value in zip(arg_names[pos_offset:], defaults):
937 assert name not in res
938 res[name] = value
939 return res
940
941
Ivan Levkivskyib692dc82017-02-13 22:50:14 +0100942_allowed_types = (types.FunctionType, types.BuiltinFunctionType,
943 types.MethodType, types.ModuleType,
Ivan Levkivskyif06e0212017-05-02 19:14:07 +0200944 WrapperDescriptorType, MethodWrapperType, MethodDescriptorType)
Ivan Levkivskyib692dc82017-02-13 22:50:14 +0100945
946
Guido van Rossum991d14f2016-11-09 13:12:51 -0800947def get_type_hints(obj, globalns=None, localns=None):
948 """Return type hints for an object.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700949
Guido van Rossum991d14f2016-11-09 13:12:51 -0800950 This is often the same as obj.__annotations__, but it handles
951 forward references encoded as string literals, and if necessary
952 adds Optional[t] if a default value equal to None is set.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700953
Guido van Rossum991d14f2016-11-09 13:12:51 -0800954 The argument may be a module, class, method, or function. The annotations
955 are returned as a dictionary. For classes, annotations include also
956 inherited members.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700957
Guido van Rossum991d14f2016-11-09 13:12:51 -0800958 TypeError is raised if the argument is not of a type that can contain
959 annotations, and an empty dictionary is returned if no annotations are
960 present.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700961
Guido van Rossum991d14f2016-11-09 13:12:51 -0800962 BEWARE -- the behavior of globalns and localns is counterintuitive
963 (unless you are familiar with how eval() and exec() work). The
964 search order is locals first, then globals.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700965
Guido van Rossum991d14f2016-11-09 13:12:51 -0800966 - If no dict arguments are passed, an attempt is made to use the
Łukasz Langaf350a262017-09-14 14:33:00 -0400967 globals from obj (or the respective module's globals for classes),
968 and these are also used as the locals. If the object does not appear
969 to have globals, an empty dictionary is used.
Guido van Rossum0a6976d2016-09-11 15:34:56 -0700970
Guido van Rossum991d14f2016-11-09 13:12:51 -0800971 - If one dict argument is passed, it is used for both globals and
972 locals.
Guido van Rossum0a6976d2016-09-11 15:34:56 -0700973
Guido van Rossum991d14f2016-11-09 13:12:51 -0800974 - If two dict arguments are passed, they specify globals and
975 locals, respectively.
976 """
Guido van Rossum0a6976d2016-09-11 15:34:56 -0700977
Guido van Rossum991d14f2016-11-09 13:12:51 -0800978 if getattr(obj, '__no_type_check__', None):
979 return {}
Guido van Rossum991d14f2016-11-09 13:12:51 -0800980 # Classes require a special treatment.
981 if isinstance(obj, type):
982 hints = {}
983 for base in reversed(obj.__mro__):
Łukasz Langaf350a262017-09-14 14:33:00 -0400984 if globalns is None:
985 base_globals = sys.modules[base.__module__].__dict__
986 else:
987 base_globals = globalns
Guido van Rossum991d14f2016-11-09 13:12:51 -0800988 ann = base.__dict__.get('__annotations__', {})
989 for name, value in ann.items():
990 if value is None:
991 value = type(None)
992 if isinstance(value, str):
Miss Islington (bot)0f9b68a2018-05-22 20:51:15 -0700993 value = ForwardRef(value, is_argument=False)
Łukasz Langaf350a262017-09-14 14:33:00 -0400994 value = _eval_type(value, base_globals, localns)
Guido van Rossum991d14f2016-11-09 13:12:51 -0800995 hints[name] = value
996 return hints
Łukasz Langaf350a262017-09-14 14:33:00 -0400997
998 if globalns is None:
999 if isinstance(obj, types.ModuleType):
1000 globalns = obj.__dict__
1001 else:
1002 globalns = getattr(obj, '__globals__', {})
1003 if localns is None:
1004 localns = globalns
1005 elif localns is None:
1006 localns = globalns
Guido van Rossum991d14f2016-11-09 13:12:51 -08001007 hints = getattr(obj, '__annotations__', None)
1008 if hints is None:
1009 # Return empty annotations for something that _could_ have them.
Ivan Levkivskyib692dc82017-02-13 22:50:14 +01001010 if isinstance(obj, _allowed_types):
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001011 return {}
Guido van Rossum991d14f2016-11-09 13:12:51 -08001012 else:
1013 raise TypeError('{!r} is not a module, class, method, '
1014 'or function.'.format(obj))
1015 defaults = _get_defaults(obj)
1016 hints = dict(hints)
1017 for name, value in hints.items():
1018 if value is None:
1019 value = type(None)
1020 if isinstance(value, str):
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001021 value = ForwardRef(value)
Guido van Rossum991d14f2016-11-09 13:12:51 -08001022 value = _eval_type(value, globalns, localns)
1023 if name in defaults and defaults[name] is None:
1024 value = Optional[value]
1025 hints[name] = value
1026 return hints
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001027
1028
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001029def no_type_check(arg):
1030 """Decorator to indicate that annotations are not type hints.
1031
1032 The argument must be a class or function; if it is a class, it
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001033 applies recursively to all methods and classes defined in that class
1034 (but not to methods defined in its superclasses or subclasses).
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001035
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001036 This mutates the function(s) or class(es) in place.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001037 """
1038 if isinstance(arg, type):
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001039 arg_attrs = arg.__dict__.copy()
1040 for attr, val in arg.__dict__.items():
Ivan Levkivskyi65bc6202017-09-14 01:25:15 +02001041 if val in arg.__bases__ + (arg,):
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001042 arg_attrs.pop(attr)
1043 for obj in arg_attrs.values():
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001044 if isinstance(obj, types.FunctionType):
1045 obj.__no_type_check__ = True
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001046 if isinstance(obj, type):
1047 no_type_check(obj)
1048 try:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001049 arg.__no_type_check__ = True
Guido van Rossumd7adfe12017-01-22 17:43:53 -08001050 except TypeError: # built-in classes
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001051 pass
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001052 return arg
1053
1054
1055def no_type_check_decorator(decorator):
1056 """Decorator to give another decorator the @no_type_check effect.
1057
1058 This wraps the decorator with something that wraps the decorated
1059 function in @no_type_check.
1060 """
1061
1062 @functools.wraps(decorator)
1063 def wrapped_decorator(*args, **kwds):
1064 func = decorator(*args, **kwds)
1065 func = no_type_check(func)
1066 return func
1067
1068 return wrapped_decorator
1069
1070
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001071def _overload_dummy(*args, **kwds):
1072 """Helper for @overload to raise when called."""
1073 raise NotImplementedError(
1074 "You should not call an overloaded function. "
1075 "A series of @overload-decorated functions "
1076 "outside a stub module should always be followed "
1077 "by an implementation that is not @overload-ed.")
1078
1079
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001080def overload(func):
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001081 """Decorator for overloaded functions/methods.
1082
1083 In a stub file, place two or more stub definitions for the same
1084 function in a row, each decorated with @overload. For example:
1085
1086 @overload
1087 def utf8(value: None) -> None: ...
1088 @overload
1089 def utf8(value: bytes) -> bytes: ...
1090 @overload
1091 def utf8(value: str) -> bytes: ...
1092
1093 In a non-stub file (i.e. a regular .py file), do the same but
1094 follow it with an implementation. The implementation should *not*
1095 be decorated with @overload. For example:
1096
1097 @overload
1098 def utf8(value: None) -> None: ...
1099 @overload
1100 def utf8(value: bytes) -> bytes: ...
1101 @overload
1102 def utf8(value: str) -> bytes: ...
1103 def utf8(value):
1104 # implementation goes here
1105 """
1106 return _overload_dummy
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001107
1108
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001109class _ProtocolMeta(type):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001110 """Internal metaclass for _Protocol.
1111
1112 This exists so _Protocol classes can be generic without deriving
1113 from Generic.
1114 """
1115
Guido van Rossumd70fe632015-08-05 12:11:06 +02001116 def __instancecheck__(self, obj):
Guido van Rossumca4b2522016-11-19 10:32:41 -08001117 if _Protocol not in self.__bases__:
1118 return super().__instancecheck__(obj)
Guido van Rossumd70fe632015-08-05 12:11:06 +02001119 raise TypeError("Protocols cannot be used with isinstance().")
1120
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001121 def __subclasscheck__(self, cls):
1122 if not self._is_protocol:
1123 # No structural checks since this isn't a protocol.
1124 return NotImplemented
1125
1126 if self is _Protocol:
1127 # Every class is a subclass of the empty protocol.
1128 return True
1129
1130 # Find all attributes defined in the protocol.
1131 attrs = self._get_protocol_attrs()
1132
1133 for attr in attrs:
1134 if not any(attr in d.__dict__ for d in cls.__mro__):
1135 return False
1136 return True
1137
1138 def _get_protocol_attrs(self):
1139 # Get all Protocol base classes.
1140 protocol_bases = []
1141 for c in self.__mro__:
1142 if getattr(c, '_is_protocol', False) and c.__name__ != '_Protocol':
1143 protocol_bases.append(c)
1144
1145 # Get attributes included in protocol.
1146 attrs = set()
1147 for base in protocol_bases:
1148 for attr in base.__dict__.keys():
1149 # Include attributes not defined in any non-protocol bases.
1150 for c in self.__mro__:
1151 if (c is not base and attr in c.__dict__ and
1152 not getattr(c, '_is_protocol', False)):
1153 break
1154 else:
1155 if (not attr.startswith('_abc_') and
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001156 attr != '__abstractmethods__' and
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001157 attr != '__annotations__' and
1158 attr != '__weakref__' and
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001159 attr != '_is_protocol' and
Ivan Levkivskyi65bc6202017-09-14 01:25:15 +02001160 attr != '_gorg' and
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001161 attr != '__dict__' and
1162 attr != '__args__' and
1163 attr != '__slots__' and
1164 attr != '_get_protocol_attrs' and
1165 attr != '__next_in_mro__' and
1166 attr != '__parameters__' and
1167 attr != '__origin__' and
Guido van Rossum7ef22d62016-10-21 14:27:58 -07001168 attr != '__orig_bases__' and
Guido van Rossum1cea70f2016-05-18 08:35:00 -07001169 attr != '__extra__' and
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001170 attr != '__tree_hash__' and
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001171 attr != '__module__'):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001172 attrs.add(attr)
1173
1174 return attrs
1175
1176
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001177class _Protocol(Generic, metaclass=_ProtocolMeta):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001178 """Internal base class for protocol classes.
1179
Guido van Rossumb24569a2016-11-20 18:01:29 -08001180 This implements a simple-minded structural issubclass check
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001181 (similar but more general than the one-offs in collections.abc
1182 such as Hashable).
1183 """
1184
Guido van Rossumd70fe632015-08-05 12:11:06 +02001185 __slots__ = ()
1186
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001187 _is_protocol = True
1188
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001189 def __class_getitem__(cls, params):
1190 return super().__class_getitem__(params)
1191
1192
1193# Some unconstrained type variables. These are used by the container types.
1194# (These are not for export.)
1195T = TypeVar('T') # Any type.
1196KT = TypeVar('KT') # Key type.
1197VT = TypeVar('VT') # Value type.
1198T_co = TypeVar('T_co', covariant=True) # Any type covariant containers.
1199V_co = TypeVar('V_co', covariant=True) # Any type covariant containers.
1200VT_co = TypeVar('VT_co', covariant=True) # Value type covariant containers.
1201T_contra = TypeVar('T_contra', contravariant=True) # Ditto contravariant.
1202# Internal type variable used for Type[].
1203CT_co = TypeVar('CT_co', covariant=True, bound=type)
1204
1205# A useful type variable with constraints. This represents string types.
1206# (This one *is* for export!)
1207AnyStr = TypeVar('AnyStr', bytes, str)
1208
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001209
1210# Various ABCs mimicking those in collections.abc.
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001211def _alias(origin, params, inst=True):
1212 return _GenericAlias(origin, params, special=True, inst=inst)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001213
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001214Hashable = _alias(collections.abc.Hashable, ()) # Not generic.
1215Awaitable = _alias(collections.abc.Awaitable, T_co)
1216Coroutine = _alias(collections.abc.Coroutine, (T_co, T_contra, V_co))
1217AsyncIterable = _alias(collections.abc.AsyncIterable, T_co)
1218AsyncIterator = _alias(collections.abc.AsyncIterator, T_co)
1219Iterable = _alias(collections.abc.Iterable, T_co)
1220Iterator = _alias(collections.abc.Iterator, T_co)
1221Reversible = _alias(collections.abc.Reversible, T_co)
1222Sized = _alias(collections.abc.Sized, ()) # Not generic.
1223Container = _alias(collections.abc.Container, T_co)
1224Collection = _alias(collections.abc.Collection, T_co)
1225Callable = _VariadicGenericAlias(collections.abc.Callable, (), special=True)
1226Callable.__doc__ = \
1227 """Callable type; Callable[[int], str] is a function of (int) -> str.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001228
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001229 The subscription syntax must always be used with exactly two
1230 values: the argument list and the return type. The argument list
1231 must be a list of types or ellipsis; the return type must be a single type.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001232
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001233 There is no syntax to indicate optional or keyword arguments,
1234 such function types are rarely used as callback types.
1235 """
1236AbstractSet = _alias(collections.abc.Set, T_co)
1237MutableSet = _alias(collections.abc.MutableSet, T)
1238# NOTE: Mapping is only covariant in the value type.
1239Mapping = _alias(collections.abc.Mapping, (KT, VT_co))
1240MutableMapping = _alias(collections.abc.MutableMapping, (KT, VT))
1241Sequence = _alias(collections.abc.Sequence, T_co)
1242MutableSequence = _alias(collections.abc.MutableSequence, T)
1243ByteString = _alias(collections.abc.ByteString, ()) # Not generic
1244Tuple = _VariadicGenericAlias(tuple, (), inst=False, special=True)
1245Tuple.__doc__ = \
1246 """Tuple type; Tuple[X, Y] is the cross-product type of X and Y.
Guido van Rossum62fe1bb2016-10-29 16:05:26 -07001247
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001248 Example: Tuple[T1, T2] is a tuple of two elements corresponding
1249 to type variables T1 and T2. Tuple[int, float, str] is a tuple
1250 of an int, a float and a string.
Guido van Rossum62fe1bb2016-10-29 16:05:26 -07001251
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001252 To specify a variable-length tuple of homogeneous type, use Tuple[T, ...].
1253 """
1254List = _alias(list, T, inst=False)
1255Deque = _alias(collections.deque, T)
1256Set = _alias(set, T, inst=False)
1257FrozenSet = _alias(frozenset, T_co, inst=False)
1258MappingView = _alias(collections.abc.MappingView, T_co)
1259KeysView = _alias(collections.abc.KeysView, KT)
1260ItemsView = _alias(collections.abc.ItemsView, (KT, VT_co))
1261ValuesView = _alias(collections.abc.ValuesView, VT_co)
1262ContextManager = _alias(contextlib.AbstractContextManager, T_co)
1263AsyncContextManager = _alias(contextlib.AbstractAsyncContextManager, T_co)
1264Dict = _alias(dict, (KT, VT), inst=False)
1265DefaultDict = _alias(collections.defaultdict, (KT, VT))
1266Counter = _alias(collections.Counter, T)
1267ChainMap = _alias(collections.ChainMap, (KT, VT))
1268Generator = _alias(collections.abc.Generator, (T_co, T_contra, V_co))
1269AsyncGenerator = _alias(collections.abc.AsyncGenerator, (T_co, T_contra))
1270Type = _alias(type, CT_co, inst=False)
1271Type.__doc__ = \
1272 """A special construct usable to annotate class objects.
Guido van Rossum62fe1bb2016-10-29 16:05:26 -07001273
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001274 For example, suppose we have the following classes::
Guido van Rossum62fe1bb2016-10-29 16:05:26 -07001275
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001276 class User: ... # Abstract base for User classes
1277 class BasicUser(User): ...
1278 class ProUser(User): ...
1279 class TeamUser(User): ...
Guido van Rossumf17c2002015-12-03 17:31:24 -08001280
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001281 And a function that takes a class argument that's a subclass of
1282 User and returns an instance of the corresponding class::
Guido van Rossumf17c2002015-12-03 17:31:24 -08001283
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001284 U = TypeVar('U', bound=User)
1285 def new_user(user_class: Type[U]) -> U:
1286 user = user_class()
1287 # (Here we could write the user object to a database)
1288 return user
Guido van Rossumf17c2002015-12-03 17:31:24 -08001289
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001290 joe = new_user(BasicUser)
Guido van Rossumf17c2002015-12-03 17:31:24 -08001291
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001292 At this point the type checker knows that joe has type BasicUser.
1293 """
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001294
1295
1296class SupportsInt(_Protocol):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001297 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001298
1299 @abstractmethod
1300 def __int__(self) -> int:
1301 pass
1302
1303
1304class SupportsFloat(_Protocol):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001305 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001306
1307 @abstractmethod
1308 def __float__(self) -> float:
1309 pass
1310
1311
1312class SupportsComplex(_Protocol):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001313 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001314
1315 @abstractmethod
1316 def __complex__(self) -> complex:
1317 pass
1318
1319
1320class SupportsBytes(_Protocol):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001321 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001322
1323 @abstractmethod
1324 def __bytes__(self) -> bytes:
1325 pass
1326
1327
Guido van Rossumd70fe632015-08-05 12:11:06 +02001328class SupportsAbs(_Protocol[T_co]):
1329 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001330
1331 @abstractmethod
Guido van Rossumd70fe632015-08-05 12:11:06 +02001332 def __abs__(self) -> T_co:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001333 pass
1334
1335
Guido van Rossumd70fe632015-08-05 12:11:06 +02001336class SupportsRound(_Protocol[T_co]):
1337 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001338
1339 @abstractmethod
Guido van Rossumd70fe632015-08-05 12:11:06 +02001340 def __round__(self, ndigits: int = 0) -> T_co:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001341 pass
1342
1343
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001344def _make_nmtuple(name, types):
Guido van Rossum2f841442016-11-15 09:48:06 -08001345 msg = "NamedTuple('Name', [(f0, t0), (f1, t1), ...]); each t must be a type"
1346 types = [(n, _type_check(t, msg)) for n, t in types]
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001347 nm_tpl = collections.namedtuple(name, [n for n, t in types])
Guido van Rossum83ec3022017-01-17 20:43:28 -08001348 # Prior to PEP 526, only _field_types attribute was assigned.
1349 # Now, both __annotations__ and _field_types are used to maintain compatibility.
1350 nm_tpl.__annotations__ = nm_tpl._field_types = collections.OrderedDict(types)
Guido van Rossum557d1eb2015-11-19 08:16:31 -08001351 try:
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001352 nm_tpl.__module__ = sys._getframe(2).f_globals.get('__name__', '__main__')
Guido van Rossum557d1eb2015-11-19 08:16:31 -08001353 except (AttributeError, ValueError):
1354 pass
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001355 return nm_tpl
1356
1357
Ivan Levkivskyib692dc82017-02-13 22:50:14 +01001358# attributes prohibited to set in NamedTuple class syntax
1359_prohibited = ('__new__', '__init__', '__slots__', '__getnewargs__',
1360 '_fields', '_field_defaults', '_field_types',
Ivan Levkivskyif06e0212017-05-02 19:14:07 +02001361 '_make', '_replace', '_asdict', '_source')
Ivan Levkivskyib692dc82017-02-13 22:50:14 +01001362
1363_special = ('__module__', '__name__', '__qualname__', '__annotations__')
1364
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001365
Guido van Rossum2f841442016-11-15 09:48:06 -08001366class NamedTupleMeta(type):
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001367
Guido van Rossum2f841442016-11-15 09:48:06 -08001368 def __new__(cls, typename, bases, ns):
1369 if ns.get('_root', False):
1370 return super().__new__(cls, typename, bases, ns)
Guido van Rossum2f841442016-11-15 09:48:06 -08001371 types = ns.get('__annotations__', {})
Guido van Rossum3c268be2017-01-18 08:03:50 -08001372 nm_tpl = _make_nmtuple(typename, types.items())
1373 defaults = []
1374 defaults_dict = {}
1375 for field_name in types:
1376 if field_name in ns:
1377 default_value = ns[field_name]
1378 defaults.append(default_value)
1379 defaults_dict[field_name] = default_value
1380 elif defaults:
Guido van Rossumd7adfe12017-01-22 17:43:53 -08001381 raise TypeError("Non-default namedtuple field {field_name} cannot "
1382 "follow default field(s) {default_names}"
Guido van Rossum3c268be2017-01-18 08:03:50 -08001383 .format(field_name=field_name,
1384 default_names=', '.join(defaults_dict.keys())))
Miss Islington (bot)3c28a632018-05-08 18:44:09 -07001385 nm_tpl.__new__.__annotations__ = collections.OrderedDict(types)
Guido van Rossum3c268be2017-01-18 08:03:50 -08001386 nm_tpl.__new__.__defaults__ = tuple(defaults)
1387 nm_tpl._field_defaults = defaults_dict
Guido van Rossum95919c02017-01-22 17:47:20 -08001388 # update from user namespace without overriding special namedtuple attributes
1389 for key in ns:
Ivan Levkivskyib692dc82017-02-13 22:50:14 +01001390 if key in _prohibited:
1391 raise AttributeError("Cannot overwrite NamedTuple attribute " + key)
1392 elif key not in _special and key not in nm_tpl._fields:
Guido van Rossum95919c02017-01-22 17:47:20 -08001393 setattr(nm_tpl, key, ns[key])
Guido van Rossum3c268be2017-01-18 08:03:50 -08001394 return nm_tpl
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001395
Guido van Rossumd7adfe12017-01-22 17:43:53 -08001396
Guido van Rossum2f841442016-11-15 09:48:06 -08001397class NamedTuple(metaclass=NamedTupleMeta):
1398 """Typed version of namedtuple.
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001399
Guido van Rossum2f841442016-11-15 09:48:06 -08001400 Usage in Python versions >= 3.6::
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001401
Guido van Rossum2f841442016-11-15 09:48:06 -08001402 class Employee(NamedTuple):
1403 name: str
1404 id: int
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001405
Guido van Rossum2f841442016-11-15 09:48:06 -08001406 This is equivalent to::
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001407
Guido van Rossum2f841442016-11-15 09:48:06 -08001408 Employee = collections.namedtuple('Employee', ['name', 'id'])
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001409
Guido van Rossum83ec3022017-01-17 20:43:28 -08001410 The resulting class has extra __annotations__ and _field_types
1411 attributes, giving an ordered dict mapping field names to types.
1412 __annotations__ should be preferred, while _field_types
1413 is kept to maintain pre PEP 526 compatibility. (The field names
Guido van Rossum2f841442016-11-15 09:48:06 -08001414 are in the _fields attribute, which is part of the namedtuple
1415 API.) Alternative equivalent keyword syntax is also accepted::
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001416
Guido van Rossum2f841442016-11-15 09:48:06 -08001417 Employee = NamedTuple('Employee', name=str, id=int)
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001418
Guido van Rossum2f841442016-11-15 09:48:06 -08001419 In Python versions <= 3.5 use::
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001420
Guido van Rossum2f841442016-11-15 09:48:06 -08001421 Employee = NamedTuple('Employee', [('name', str), ('id', int)])
1422 """
1423 _root = True
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001424
Guido van Rossum2f841442016-11-15 09:48:06 -08001425 def __new__(self, typename, fields=None, **kwargs):
Guido van Rossum2f841442016-11-15 09:48:06 -08001426 if fields is None:
1427 fields = kwargs.items()
1428 elif kwargs:
1429 raise TypeError("Either list of fields or keywords"
1430 " can be provided to NamedTuple, not both")
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001431 return _make_nmtuple(typename, fields)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001432
1433
Guido van Rossum91185fe2016-06-08 11:19:11 -07001434def NewType(name, tp):
1435 """NewType creates simple unique types with almost zero
1436 runtime overhead. NewType(name, tp) is considered a subtype of tp
1437 by static type checkers. At runtime, NewType(name, tp) returns
1438 a dummy function that simply returns its argument. Usage::
1439
1440 UserId = NewType('UserId', int)
1441
1442 def name_by_id(user_id: UserId) -> str:
1443 ...
1444
1445 UserId('user') # Fails type check
1446
1447 name_by_id(42) # Fails type check
1448 name_by_id(UserId(42)) # OK
1449
1450 num = UserId(5) + 1 # type: int
1451 """
1452
1453 def new_type(x):
1454 return x
1455
1456 new_type.__name__ = name
1457 new_type.__supertype__ = tp
1458 return new_type
1459
1460
Guido van Rossum0e0563c2016-04-05 14:54:25 -07001461# Python-version-specific alias (Python 2: unicode; Python 3: str)
1462Text = str
1463
1464
Guido van Rossum91185fe2016-06-08 11:19:11 -07001465# Constant that's True when type checking, but False here.
1466TYPE_CHECKING = False
1467
1468
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001469class IO(Generic[AnyStr]):
1470 """Generic base class for TextIO and BinaryIO.
1471
1472 This is an abstract, generic version of the return of open().
1473
1474 NOTE: This does not distinguish between the different possible
1475 classes (text vs. binary, read vs. write vs. read/write,
1476 append-only, unbuffered). The TextIO and BinaryIO subclasses
1477 below capture the distinctions between text vs. binary, which is
1478 pervasive in the interface; however we currently do not offer a
1479 way to track the other distinctions in the type system.
1480 """
1481
Guido van Rossumd70fe632015-08-05 12:11:06 +02001482 __slots__ = ()
1483
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001484 @abstractproperty
1485 def mode(self) -> str:
1486 pass
1487
1488 @abstractproperty
1489 def name(self) -> str:
1490 pass
1491
1492 @abstractmethod
1493 def close(self) -> None:
1494 pass
1495
1496 @abstractmethod
1497 def closed(self) -> bool:
1498 pass
1499
1500 @abstractmethod
1501 def fileno(self) -> int:
1502 pass
1503
1504 @abstractmethod
1505 def flush(self) -> None:
1506 pass
1507
1508 @abstractmethod
1509 def isatty(self) -> bool:
1510 pass
1511
1512 @abstractmethod
1513 def read(self, n: int = -1) -> AnyStr:
1514 pass
1515
1516 @abstractmethod
1517 def readable(self) -> bool:
1518 pass
1519
1520 @abstractmethod
1521 def readline(self, limit: int = -1) -> AnyStr:
1522 pass
1523
1524 @abstractmethod
1525 def readlines(self, hint: int = -1) -> List[AnyStr]:
1526 pass
1527
1528 @abstractmethod
1529 def seek(self, offset: int, whence: int = 0) -> int:
1530 pass
1531
1532 @abstractmethod
1533 def seekable(self) -> bool:
1534 pass
1535
1536 @abstractmethod
1537 def tell(self) -> int:
1538 pass
1539
1540 @abstractmethod
1541 def truncate(self, size: int = None) -> int:
1542 pass
1543
1544 @abstractmethod
1545 def writable(self) -> bool:
1546 pass
1547
1548 @abstractmethod
1549 def write(self, s: AnyStr) -> int:
1550 pass
1551
1552 @abstractmethod
1553 def writelines(self, lines: List[AnyStr]) -> None:
1554 pass
1555
1556 @abstractmethod
1557 def __enter__(self) -> 'IO[AnyStr]':
1558 pass
1559
1560 @abstractmethod
1561 def __exit__(self, type, value, traceback) -> None:
1562 pass
1563
1564
1565class BinaryIO(IO[bytes]):
1566 """Typed version of the return of open() in binary mode."""
1567
Guido van Rossumd70fe632015-08-05 12:11:06 +02001568 __slots__ = ()
1569
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001570 @abstractmethod
1571 def write(self, s: Union[bytes, bytearray]) -> int:
1572 pass
1573
1574 @abstractmethod
1575 def __enter__(self) -> 'BinaryIO':
1576 pass
1577
1578
1579class TextIO(IO[str]):
1580 """Typed version of the return of open() in text mode."""
1581
Guido van Rossumd70fe632015-08-05 12:11:06 +02001582 __slots__ = ()
1583
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001584 @abstractproperty
1585 def buffer(self) -> BinaryIO:
1586 pass
1587
1588 @abstractproperty
1589 def encoding(self) -> str:
1590 pass
1591
1592 @abstractproperty
Guido van Rossum991d14f2016-11-09 13:12:51 -08001593 def errors(self) -> Optional[str]:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001594 pass
1595
1596 @abstractproperty
1597 def line_buffering(self) -> bool:
1598 pass
1599
1600 @abstractproperty
1601 def newlines(self) -> Any:
1602 pass
1603
1604 @abstractmethod
1605 def __enter__(self) -> 'TextIO':
1606 pass
1607
1608
1609class io:
1610 """Wrapper namespace for IO generic classes."""
1611
1612 __all__ = ['IO', 'TextIO', 'BinaryIO']
1613 IO = IO
1614 TextIO = TextIO
1615 BinaryIO = BinaryIO
1616
Guido van Rossumd7adfe12017-01-22 17:43:53 -08001617
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001618io.__name__ = __name__ + '.io'
1619sys.modules[io.__name__] = io
1620
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001621Pattern = _alias(stdlib_re.Pattern, AnyStr)
1622Match = _alias(stdlib_re.Match, AnyStr)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001623
1624class re:
1625 """Wrapper namespace for re type aliases."""
1626
1627 __all__ = ['Pattern', 'Match']
1628 Pattern = Pattern
1629 Match = Match
1630
Guido van Rossumd7adfe12017-01-22 17:43:53 -08001631
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001632re.__name__ = __name__ + '.re'
1633sys.modules[re.__name__] = re