blob: 89b73db158379ecfe0ad68ba4fa891f947c142e5 [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
27import re as stdlib_re # Avoid confusion with the re we export.
28import sys
29import types
Ivan Levkivskyid911e402018-01-20 11:23:59 +000030from types import WrapperDescriptorType, MethodWrapperType, MethodDescriptorType
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070031
32# Please keep __all__ alphabetized within each category.
33__all__ = [
34 # Super-special typing primitives.
35 'Any',
36 'Callable',
Guido van Rossum0a6976d2016-09-11 15:34:56 -070037 'ClassVar',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070038 'Generic',
39 'Optional',
Guido van Rossumeb9aca32016-05-24 16:38:22 -070040 'Tuple',
41 'Type',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070042 'TypeVar',
43 'Union',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070044
45 # ABCs (from collections.abc).
46 'AbstractSet', # collections.abc.Set.
47 'ByteString',
48 'Container',
Ivan Levkivskyi29fda8d2017-06-10 21:57:56 +020049 'ContextManager',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070050 'Hashable',
51 'ItemsView',
52 'Iterable',
53 'Iterator',
54 'KeysView',
55 'Mapping',
56 'MappingView',
57 'MutableMapping',
58 'MutableSequence',
59 'MutableSet',
60 'Sequence',
61 'Sized',
62 'ValuesView',
Ivan Levkivskyid911e402018-01-20 11:23:59 +000063 'Awaitable',
64 'AsyncIterator',
65 'AsyncIterable',
66 'Coroutine',
67 'Collection',
68 'AsyncGenerator',
69 'AsyncContextManager',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070070
71 # Structural checks, a.k.a. protocols.
72 'Reversible',
73 'SupportsAbs',
Ivan Levkivskyif06e0212017-05-02 19:14:07 +020074 'SupportsBytes',
75 'SupportsComplex',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070076 'SupportsFloat',
77 'SupportsInt',
78 'SupportsRound',
79
80 # Concrete collection types.
Ivan Levkivskyib692dc82017-02-13 22:50:14 +010081 'Counter',
Raymond Hettinger80490522017-01-16 22:42:37 -080082 'Deque',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070083 'Dict',
Guido van Rossumbd5b9a02016-04-05 08:28:52 -070084 'DefaultDict',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070085 'List',
86 'Set',
Guido van Rossumefa798d2016-08-23 11:01:50 -070087 'FrozenSet',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070088 'NamedTuple', # Not really a type.
89 'Generator',
90
91 # One-off things.
92 'AnyStr',
93 'cast',
94 'get_type_hints',
Guido van Rossum91185fe2016-06-08 11:19:11 -070095 'NewType',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070096 'no_type_check',
97 'no_type_check_decorator',
Ivan Levkivskyiac560272018-03-23 21:44:54 +000098 'NoReturn',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -070099 'overload',
Guido van Rossum0e0563c2016-04-05 14:54:25 -0700100 'Text',
Guido van Rossum91185fe2016-06-08 11:19:11 -0700101 'TYPE_CHECKING',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700102]
103
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700104# The pseudo-submodules 're' and 'io' are part of the public
105# namespace, but excluded from __all__ because they might stomp on
106# legitimate imports of those modules.
107
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700108
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000109def _type_check(arg, msg):
110 """Check that the argument is a type, and return it (internal helper).
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700111
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000112 As a special case, accept None and return type(None) instead. Also wrap strings
113 into ForwardRef instances. Consider several corner cases, for example plain
114 special forms like Union are not valid, while Union[int, str] is OK, etc.
115 The msg argument is a human-readable error message, e.g::
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700116
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000117 "Union[arg, ...]: arg should be a type."
Guido van Rossum4cefe742016-09-27 15:20:12 -0700118
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000119 We append the repr() of the actual value (truncated to 100 chars).
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700120 """
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000121 if arg is None:
122 return type(None)
123 if isinstance(arg, str):
124 return ForwardRef(arg)
125 if (isinstance(arg, _GenericAlias) and
126 arg.__origin__ in (Generic, _Protocol, ClassVar)):
127 raise TypeError(f"{arg} is not valid as type argument")
128 if (isinstance(arg, _SpecialForm) and arg is not Any or
129 arg in (Generic, _Protocol)):
130 raise TypeError(f"Plain {arg} is not valid as type argument")
131 if isinstance(arg, (type, TypeVar, ForwardRef)):
132 return arg
133 if not callable(arg):
134 raise TypeError(f"{msg} Got {arg!r:.100}.")
135 return arg
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700136
137
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000138def _type_repr(obj):
139 """Return the repr() of an object, special-casing types (internal helper).
140
141 If obj is a type, we return a shorter version than the default
142 type.__repr__, based on the module and qualified name, which is
143 typically enough to uniquely identify a type. For everything
144 else, we fall back on repr(obj).
145 """
146 if isinstance(obj, type):
147 if obj.__module__ == 'builtins':
148 return obj.__qualname__
149 return f'{obj.__module__}.{obj.__qualname__}'
150 if obj is ...:
151 return('...')
152 if isinstance(obj, types.FunctionType):
153 return obj.__name__
154 return repr(obj)
155
156
157def _collect_type_vars(types):
158 """Collect all type variable contained in types in order of
159 first appearance (lexicographic order). For example::
160
161 _collect_type_vars((T, List[S, T])) == (T, S)
162 """
163 tvars = []
164 for t in types:
165 if isinstance(t, TypeVar) and t not in tvars:
166 tvars.append(t)
167 if isinstance(t, _GenericAlias) and not t._special:
168 tvars.extend([t for t in t.__parameters__ if t not in tvars])
169 return tuple(tvars)
170
171
172def _subs_tvars(tp, tvars, subs):
173 """Substitute type variables 'tvars' with substitutions 'subs'.
174 These two must have the same length.
175 """
176 if not isinstance(tp, _GenericAlias):
177 return tp
178 new_args = list(tp.__args__)
179 for a, arg in enumerate(tp.__args__):
180 if isinstance(arg, TypeVar):
181 for i, tvar in enumerate(tvars):
182 if arg == tvar:
183 new_args[a] = subs[i]
184 else:
185 new_args[a] = _subs_tvars(arg, tvars, subs)
186 if tp.__origin__ is Union:
187 return Union[tuple(new_args)]
188 return tp.copy_with(tuple(new_args))
189
190
191def _check_generic(cls, parameters):
192 """Check correct count for parameters of a generic cls (internal helper).
193 This gives a nice error message in case of count mismatch.
194 """
195 if not cls.__parameters__:
196 raise TypeError(f"{cls} is not a generic class")
197 alen = len(parameters)
198 elen = len(cls.__parameters__)
199 if alen != elen:
200 raise TypeError(f"Too {'many' if alen > elen else 'few'} parameters for {cls};"
201 f" actual {alen}, expected {elen}")
202
203
204def _remove_dups_flatten(parameters):
205 """An internal helper for Union creation and substitution: flatten Union's
206 among parameters, then remove duplicates and strict subclasses.
207 """
208 # Flatten out Union[Union[...], ...].
209 params = []
210 for p in parameters:
211 if isinstance(p, _GenericAlias) and p.__origin__ is Union:
212 params.extend(p.__args__)
213 elif isinstance(p, tuple) and len(p) > 0 and p[0] is Union:
214 params.extend(p[1:])
215 else:
216 params.append(p)
217 # Weed out strict duplicates, preserving the first of each occurrence.
218 all_params = set(params)
219 if len(all_params) < len(params):
220 new_params = []
221 for t in params:
222 if t in all_params:
223 new_params.append(t)
224 all_params.remove(t)
225 params = new_params
226 assert not all_params, all_params
227 # Weed out subclasses.
228 # E.g. Union[int, Employee, Manager] == Union[int, Employee].
229 # If object is present it will be sole survivor among proper classes.
230 # Never discard type variables.
231 # (In particular, Union[str, AnyStr] != AnyStr.)
232 all_params = set(params)
233 for t1 in params:
234 if not isinstance(t1, type):
235 continue
236 if any((isinstance(t2, type) or
237 isinstance(t2, _GenericAlias) and t2._special) and issubclass(t1, t2)
238 for t2 in all_params - {t1}):
239 all_params.remove(t1)
240 return tuple(t for t in params if t in all_params)
241
242
243_cleanups = []
244
245
246def _tp_cache(func):
247 """Internal wrapper caching __getitem__ of generic types with a fallback to
248 original function for non-hashable arguments.
249 """
250 cached = functools.lru_cache()(func)
251 _cleanups.append(cached.cache_clear)
252
253 @functools.wraps(func)
254 def inner(*args, **kwds):
255 try:
256 return cached(*args, **kwds)
257 except TypeError:
258 pass # All real errors (not unhashable args) are raised below.
259 return func(*args, **kwds)
260 return inner
261
262
263def _eval_type(t, globalns, localns):
264 """Evaluate all forward reverences in the given type t.
265 For use of globalns and localns see the docstring for get_type_hints().
266 """
267 if isinstance(t, ForwardRef):
268 return t._evaluate(globalns, localns)
269 if isinstance(t, _GenericAlias):
270 ev_args = tuple(_eval_type(a, globalns, localns) for a in t.__args__)
271 if ev_args == t.__args__:
272 return t
273 res = t.copy_with(ev_args)
274 res._special = t._special
275 return res
276 return t
277
278
279class _Final:
280 """Mixin to prohibit subclassing"""
Guido van Rossum4cefe742016-09-27 15:20:12 -0700281
Guido van Rossum83ec3022017-01-17 20:43:28 -0800282 __slots__ = ('__weakref__',)
Guido van Rossum4cefe742016-09-27 15:20:12 -0700283
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000284 def __init_subclass__(self, *args, **kwds):
285 if '_root' not in kwds:
286 raise TypeError("Cannot subclass special typing classes")
287
Miss Islington (bot)d0e04c82018-03-26 15:29:06 -0700288class _Immutable:
289 """Mixin to indicate that object should not be copied."""
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000290
Miss Islington (bot)d0e04c82018-03-26 15:29:06 -0700291 def __copy__(self):
292 return self
293
294 def __deepcopy__(self, memo):
295 return self
296
297
298class _SpecialForm(_Final, _Immutable, _root=True):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000299 """Internal indicator of special typing constructs.
300 See _doc instance attribute for specific docs.
301 """
302
303 __slots__ = ('_name', '_doc')
304
305 def __getstate__(self):
306 return {'name': self._name, 'doc': self._doc}
307
308 def __setstate__(self, state):
309 self._name = state['name']
310 self._doc = state['doc']
Guido van Rossum4cefe742016-09-27 15:20:12 -0700311
312 def __new__(cls, *args, **kwds):
313 """Constructor.
314
315 This only exists to give a better error message in case
316 someone tries to subclass a special typing object (not a good idea).
317 """
318 if (len(args) == 3 and
319 isinstance(args[0], str) and
320 isinstance(args[1], tuple)):
321 # Close enough.
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000322 raise TypeError(f"Cannot subclass {cls!r}")
Guido van Rossumb47c9d22016-10-03 08:40:50 -0700323 return super().__new__(cls)
Guido van Rossum4cefe742016-09-27 15:20:12 -0700324
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000325 def __init__(self, name, doc):
326 self._name = name
327 self._doc = doc
Guido van Rossum4cefe742016-09-27 15:20:12 -0700328
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000329 def __eq__(self, other):
330 if not isinstance(other, _SpecialForm):
331 return NotImplemented
332 return self._name == other._name
333
334 def __hash__(self):
335 return hash((self._name,))
Guido van Rossum4cefe742016-09-27 15:20:12 -0700336
337 def __repr__(self):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000338 return 'typing.' + self._name
339
Miss Islington (bot)d0e04c82018-03-26 15:29:06 -0700340 def __reduce__(self):
341 return self._name
Guido van Rossum4cefe742016-09-27 15:20:12 -0700342
343 def __call__(self, *args, **kwds):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000344 raise TypeError(f"Cannot instantiate {self!r}")
345
346 def __instancecheck__(self, obj):
347 raise TypeError(f"{self} cannot be used with isinstance()")
348
349 def __subclasscheck__(self, cls):
350 raise TypeError(f"{self} cannot be used with issubclass()")
351
352 @_tp_cache
353 def __getitem__(self, parameters):
354 if self._name == 'ClassVar':
355 item = _type_check(parameters, 'ClassVar accepts only single type.')
356 return _GenericAlias(self, (item,))
357 if self._name == 'Union':
358 if parameters == ():
359 raise TypeError("Cannot take a Union of no types.")
360 if not isinstance(parameters, tuple):
361 parameters = (parameters,)
362 msg = "Union[arg, ...]: each arg must be a type."
363 parameters = tuple(_type_check(p, msg) for p in parameters)
364 parameters = _remove_dups_flatten(parameters)
365 if len(parameters) == 1:
366 return parameters[0]
367 return _GenericAlias(self, parameters)
368 if self._name == 'Optional':
369 arg = _type_check(parameters, "Optional[t] requires a single type.")
370 return Union[arg, type(None)]
371 raise TypeError(f"{self} is not subscriptable")
Guido van Rossum4cefe742016-09-27 15:20:12 -0700372
373
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000374Any = _SpecialForm('Any', doc=
375 """Special type indicating an unconstrained type.
Guido van Rossumb47c9d22016-10-03 08:40:50 -0700376
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000377 - Any is compatible with every type.
378 - Any assumed to have all methods.
379 - All values assumed to be instances of Any.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700380
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000381 Note that all the above statements are true from the point of view of
382 static type checkers. At runtime, Any should not be used with instance
383 or class checks.
384 """)
Guido van Rossumd70fe632015-08-05 12:11:06 +0200385
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000386NoReturn = _SpecialForm('NoReturn', doc=
387 """Special type indicating functions that never return.
388 Example::
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700389
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000390 from typing import NoReturn
391
392 def stop() -> NoReturn:
393 raise Exception('no way')
394
395 This type is invalid in other positions, e.g., ``List[NoReturn]``
396 will fail in static type checkers.
397 """)
398
399ClassVar = _SpecialForm('ClassVar', doc=
400 """Special type construct to mark class variables.
401
402 An annotation wrapped in ClassVar indicates that a given
403 attribute is intended to be used as a class variable and
404 should not be set on instances of that class. Usage::
405
406 class Starship:
407 stats: ClassVar[Dict[str, int]] = {} # class variable
408 damage: int = 10 # instance variable
409
410 ClassVar accepts only types and cannot be further subscribed.
411
412 Note that ClassVar is not a class itself, and should not
413 be used with isinstance() or issubclass().
414 """)
415
416Union = _SpecialForm('Union', doc=
417 """Union type; Union[X, Y] means either X or Y.
418
419 To define a union, use e.g. Union[int, str]. Details:
420 - The arguments must be types and there must be at least one.
421 - None as an argument is a special case and is replaced by
422 type(None).
423 - Unions of unions are flattened, e.g.::
424
425 Union[Union[int, str], float] == Union[int, str, float]
426
427 - Unions of a single argument vanish, e.g.::
428
429 Union[int] == int # The constructor actually returns int
430
431 - Redundant arguments are skipped, e.g.::
432
433 Union[int, str, int] == Union[int, str]
434
435 - When comparing unions, the argument order is ignored, e.g.::
436
437 Union[int, str] == Union[str, int]
438
439 - When two arguments have a subclass relationship, the least
440 derived argument is kept, e.g.::
441
442 class Employee: pass
443 class Manager(Employee): pass
444 Union[int, Employee, Manager] == Union[int, Employee]
445 Union[Manager, int, Employee] == Union[int, Employee]
446 Union[Employee, Manager] == Employee
447
448 - Similar for object::
449
450 Union[int, object] == object
451
452 - You cannot subclass or instantiate a union.
453 - You can use Optional[X] as a shorthand for Union[X, None].
454 """)
455
456Optional = _SpecialForm('Optional', doc=
457 """Optional type.
458
459 Optional[X] is equivalent to Union[X, None].
460 """)
Guido van Rossumb7dedc82016-10-29 12:44:29 -0700461
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700462
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000463class ForwardRef(_Final, _root=True):
Guido van Rossumb24569a2016-11-20 18:01:29 -0800464 """Internal wrapper to hold a forward reference."""
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700465
Guido van Rossum4cefe742016-09-27 15:20:12 -0700466 __slots__ = ('__forward_arg__', '__forward_code__',
Guido van Rossumc7b92952016-11-10 08:24:06 -0800467 '__forward_evaluated__', '__forward_value__')
Guido van Rossum4cefe742016-09-27 15:20:12 -0700468
469 def __init__(self, arg):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700470 if not isinstance(arg, str):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000471 raise TypeError(f"Forward reference must be a string -- got {arg!r}")
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700472 try:
473 code = compile(arg, '<string>', 'eval')
474 except SyntaxError:
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000475 raise SyntaxError(f"Forward reference must be an expression -- got {arg!r}")
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700476 self.__forward_arg__ = arg
477 self.__forward_code__ = code
478 self.__forward_evaluated__ = False
479 self.__forward_value__ = None
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700480
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000481 def _evaluate(self, globalns, localns):
Guido van Rossumdad17902016-11-10 08:29:18 -0800482 if not self.__forward_evaluated__ or localns is not globalns:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700483 if globalns is None and localns is None:
484 globalns = localns = {}
485 elif globalns is None:
486 globalns = localns
487 elif localns is None:
488 localns = globalns
489 self.__forward_value__ = _type_check(
490 eval(self.__forward_code__, globalns, localns),
491 "Forward references must evaluate to types.")
492 self.__forward_evaluated__ = True
493 return self.__forward_value__
494
Guido van Rossum4cefe742016-09-27 15:20:12 -0700495 def __eq__(self, other):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000496 if not isinstance(other, ForwardRef):
Guido van Rossum4cefe742016-09-27 15:20:12 -0700497 return NotImplemented
498 return (self.__forward_arg__ == other.__forward_arg__ and
Guido van Rossumc7b92952016-11-10 08:24:06 -0800499 self.__forward_value__ == other.__forward_value__)
Guido van Rossum4cefe742016-09-27 15:20:12 -0700500
501 def __hash__(self):
Guido van Rossumc7b92952016-11-10 08:24:06 -0800502 return hash((self.__forward_arg__, self.__forward_value__))
Guido van Rossum4cefe742016-09-27 15:20:12 -0700503
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700504 def __repr__(self):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000505 return f'ForwardRef({self.__forward_arg__!r})'
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700506
507
Miss Islington (bot)d0e04c82018-03-26 15:29:06 -0700508def _find_name(mod, name):
509 return getattr(sys.modules[mod], name)
510
511
512class TypeVar(_Final, _Immutable, _root=True):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700513 """Type variable.
514
515 Usage::
516
517 T = TypeVar('T') # Can be anything
518 A = TypeVar('A', str, bytes) # Must be str or bytes
519
520 Type variables exist primarily for the benefit of static type
521 checkers. They serve as the parameters for generic types as well
522 as for generic function definitions. See class Generic for more
523 information on generic types. Generic functions work as follows:
524
Guido van Rossumb24569a2016-11-20 18:01:29 -0800525 def repeat(x: T, n: int) -> List[T]:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700526 '''Return a list containing n references to x.'''
527 return [x]*n
528
529 def longest(x: A, y: A) -> A:
530 '''Return the longest of two strings.'''
531 return x if len(x) >= len(y) else y
532
533 The latter example's signature is essentially the overloading
534 of (str, str) -> str and (bytes, bytes) -> bytes. Also note
535 that if the arguments are instances of some subclass of str,
536 the return type is still plain str.
537
Guido van Rossumb24569a2016-11-20 18:01:29 -0800538 At runtime, isinstance(x, T) and issubclass(C, T) will raise TypeError.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700539
Guido van Rossumefa798d2016-08-23 11:01:50 -0700540 Type variables defined with covariant=True or contravariant=True
541 can be used do declare covariant or contravariant generic types.
542 See PEP 484 for more details. By default generic types are invariant
543 in all type variables.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700544
545 Type variables can be introspected. e.g.:
546
547 T.__name__ == 'T'
548 T.__constraints__ == ()
549 T.__covariant__ == False
550 T.__contravariant__ = False
551 A.__constraints__ == (str, bytes)
Miss Islington (bot)d0e04c82018-03-26 15:29:06 -0700552
553 Note that only type variables defined in global scope can be pickled.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700554 """
555
Guido van Rossum4cefe742016-09-27 15:20:12 -0700556 __slots__ = ('__name__', '__bound__', '__constraints__',
Miss Islington (bot)d0e04c82018-03-26 15:29:06 -0700557 '__covariant__', '__contravariant__', '_def_mod')
Guido van Rossum4cefe742016-09-27 15:20:12 -0700558
559 def __init__(self, name, *constraints, bound=None,
Guido van Rossumd7adfe12017-01-22 17:43:53 -0800560 covariant=False, contravariant=False):
Guido van Rossum4cefe742016-09-27 15:20:12 -0700561 self.__name__ = name
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700562 if covariant and contravariant:
Guido van Rossumefa798d2016-08-23 11:01:50 -0700563 raise ValueError("Bivariant types are not supported.")
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700564 self.__covariant__ = bool(covariant)
565 self.__contravariant__ = bool(contravariant)
566 if constraints and bound is not None:
567 raise TypeError("Constraints cannot be combined with bound=...")
568 if constraints and len(constraints) == 1:
569 raise TypeError("A single constraint is not allowed")
570 msg = "TypeVar(name, constraint, ...): constraints must be types."
571 self.__constraints__ = tuple(_type_check(t, msg) for t in constraints)
572 if bound:
573 self.__bound__ = _type_check(bound, "Bound must be a type.")
574 else:
575 self.__bound__ = None
Miss Islington (bot)d0e04c82018-03-26 15:29:06 -0700576 self._def_mod = sys._getframe(1).f_globals['__name__'] # for pickling
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700577
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000578 def __getstate__(self):
579 return {'name': self.__name__,
580 'bound': self.__bound__,
581 'constraints': self.__constraints__,
582 'co': self.__covariant__,
583 'contra': self.__contravariant__}
584
585 def __setstate__(self, state):
586 self.__name__ = state['name']
587 self.__bound__ = state['bound']
588 self.__constraints__ = state['constraints']
589 self.__covariant__ = state['co']
590 self.__contravariant__ = state['contra']
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700591
592 def __repr__(self):
593 if self.__covariant__:
594 prefix = '+'
595 elif self.__contravariant__:
596 prefix = '-'
597 else:
598 prefix = '~'
599 return prefix + self.__name__
600
Miss Islington (bot)d0e04c82018-03-26 15:29:06 -0700601 def __reduce__(self):
602 return (_find_name, (self._def_mod, self.__name__))
603
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700604
Guido van Rossum83ec3022017-01-17 20:43:28 -0800605# Special typing constructs Union, Optional, Generic, Callable and Tuple
606# use three special attributes for internal bookkeeping of generic types:
607# * __parameters__ is a tuple of unique free type parameters of a generic
608# type, for example, Dict[T, T].__parameters__ == (T,);
609# * __origin__ keeps a reference to a type that was subscripted,
Miss Islington (bot)3c28a632018-05-08 18:44:09 -0700610# e.g., Union[T, int].__origin__ == Union, or the non-generic version of
611# the type.
Guido van Rossum83ec3022017-01-17 20:43:28 -0800612# * __args__ is a tuple of all arguments used in subscripting,
613# e.g., Dict[T, int].__args__ == (T, int).
614
Miss Islington (bot)04eac022018-04-04 17:46:40 -0700615
616# Mapping from non-generic type names that have a generic alias in typing
617# but with a different name.
618_normalize_alias = {'list': 'List',
619 'tuple': 'Tuple',
620 'dict': 'Dict',
621 'set': 'Set',
622 'frozenset': 'FrozenSet',
623 'deque': 'Deque',
624 'defaultdict': 'DefaultDict',
625 'type': 'Type',
626 'Set': 'AbstractSet'}
627
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000628def _is_dunder(attr):
629 return attr.startswith('__') and attr.endswith('__')
Guido van Rossum83ec3022017-01-17 20:43:28 -0800630
Guido van Rossumb24569a2016-11-20 18:01:29 -0800631
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000632class _GenericAlias(_Final, _root=True):
633 """The central part of internal API.
634
635 This represents a generic version of type 'origin' with type arguments 'params'.
636 There are two kind of these aliases: user defined and special. The special ones
637 are wrappers around builtin collections and ABCs in collections.abc. These must
638 have 'name' always set. If 'inst' is False, then the alias can't be instantiated,
639 this is used by e.g. typing.List and typing.Dict.
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700640 """
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000641 def __init__(self, origin, params, *, inst=True, special=False, name=None):
642 self._inst = inst
643 self._special = special
644 if special and name is None:
645 orig_name = origin.__name__
Miss Islington (bot)04eac022018-04-04 17:46:40 -0700646 name = _normalize_alias.get(orig_name, orig_name)
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000647 self._name = name
648 if not isinstance(params, tuple):
649 params = (params,)
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700650 self.__origin__ = origin
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700651 self.__args__ = tuple(... if a is _TypingEllipsis else
652 () if a is _TypingEmpty else
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000653 a for a in params)
654 self.__parameters__ = _collect_type_vars(params)
655 self.__slots__ = None # This is not documented.
656 if not name:
657 self.__module__ = origin.__module__
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700658
Guido van Rossum4cefe742016-09-27 15:20:12 -0700659 @_tp_cache
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700660 def __getitem__(self, params):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000661 if self.__origin__ in (Generic, _Protocol):
662 # Can't subscript Generic[...] or _Protocol[...].
663 raise TypeError(f"Cannot subscript already-subscripted {self}")
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700664 if not isinstance(params, tuple):
665 params = (params,)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700666 msg = "Parameters to generic types must be types."
667 params = tuple(_type_check(p, msg) for p in params)
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000668 _check_generic(self, params)
669 return _subs_tvars(self, self.__parameters__, params)
Ivan Levkivskyib692dc82017-02-13 22:50:14 +0100670
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000671 def copy_with(self, params):
672 # We don't copy self._special.
673 return _GenericAlias(self.__origin__, params, name=self._name, inst=self._inst)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700674
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000675 def __repr__(self):
676 if (self._name != 'Callable' or
677 len(self.__args__) == 2 and self.__args__[0] is Ellipsis):
678 if self._name:
679 name = 'typing.' + self._name
680 else:
681 name = _type_repr(self.__origin__)
682 if not self._special:
683 args = f'[{", ".join([_type_repr(a) for a in self.__args__])}]'
684 else:
685 args = ''
686 return (f'{name}{args}')
687 if self._special:
688 return 'typing.Callable'
689 return (f'typing.Callable'
690 f'[[{", ".join([_type_repr(a) for a in self.__args__[:-1]])}], '
691 f'{_type_repr(self.__args__[-1])}]')
692
693 def __eq__(self, other):
694 if not isinstance(other, _GenericAlias):
695 return NotImplemented
696 if self.__origin__ != other.__origin__:
Ivan Levkivskyib692dc82017-02-13 22:50:14 +0100697 return False
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000698 if self.__origin__ is Union and other.__origin__ is Union:
699 return frozenset(self.__args__) == frozenset(other.__args__)
700 return self.__args__ == other.__args__
Ivan Levkivskyib692dc82017-02-13 22:50:14 +0100701
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000702 def __hash__(self):
703 if self.__origin__ is Union:
704 return hash((Union, frozenset(self.__args__)))
705 return hash((self.__origin__, self.__args__))
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700706
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000707 def __call__(self, *args, **kwargs):
708 if not self._inst:
709 raise TypeError(f"Type {self._name} cannot be instantiated; "
710 f"use {self._name.lower()}() instead")
711 result = self.__origin__(*args, **kwargs)
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700712 try:
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000713 result.__orig_class__ = self
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700714 except AttributeError:
715 pass
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000716 return result
717
718 def __mro_entries__(self, bases):
719 if self._name: # generic version of an ABC or built-in class
720 res = []
721 if self.__origin__ not in bases:
722 res.append(self.__origin__)
723 i = bases.index(self)
724 if not any(isinstance(b, _GenericAlias) or issubclass(b, Generic)
725 for b in bases[i+1:]):
726 res.append(Generic)
727 return tuple(res)
728 if self.__origin__ is Generic:
729 i = bases.index(self)
730 for b in bases[i+1:]:
731 if isinstance(b, _GenericAlias) and b is not self:
732 return ()
733 return (self.__origin__,)
734
735 def __getattr__(self, attr):
Miss Islington (bot)32955292018-04-20 14:00:41 -0700736 # We are careful for copy and pickle.
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000737 # Also for simplicity we just don't relay all dunder names
738 if '__origin__' in self.__dict__ and not _is_dunder(attr):
739 return getattr(self.__origin__, attr)
740 raise AttributeError(attr)
741
742 def __setattr__(self, attr, val):
743 if _is_dunder(attr) or attr in ('_name', '_inst', '_special'):
744 super().__setattr__(attr, val)
745 else:
746 setattr(self.__origin__, attr, val)
747
748 def __instancecheck__(self, obj):
749 return self.__subclasscheck__(type(obj))
750
751 def __subclasscheck__(self, cls):
752 if self._special:
753 if not isinstance(cls, _GenericAlias):
754 return issubclass(cls, self.__origin__)
755 if cls._special:
756 return issubclass(cls.__origin__, self.__origin__)
757 raise TypeError("Subscripted generics cannot be used with"
758 " class and instance checks")
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700759
Miss Islington (bot)d0e04c82018-03-26 15:29:06 -0700760 def __reduce__(self):
761 if self._special:
762 return self._name
763 return super().__reduce__()
764
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700765
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000766class _VariadicGenericAlias(_GenericAlias, _root=True):
767 """Same as _GenericAlias above but for variadic aliases. Currently,
768 this is used only by special internal aliases: Tuple and Callable.
769 """
770 def __getitem__(self, params):
771 if self._name != 'Callable' or not self._special:
772 return self.__getitem_inner__(params)
773 if not isinstance(params, tuple) or len(params) != 2:
774 raise TypeError("Callable must be used as "
775 "Callable[[arg, ...], result].")
776 args, result = params
777 if args is Ellipsis:
778 params = (Ellipsis, result)
779 else:
780 if not isinstance(args, list):
781 raise TypeError(f"Callable[args, result]: args must be a list."
782 f" Got {args}")
783 params = (tuple(args), result)
784 return self.__getitem_inner__(params)
785
786 @_tp_cache
787 def __getitem_inner__(self, params):
788 if self.__origin__ is tuple and self._special:
789 if params == ():
790 return self.copy_with((_TypingEmpty,))
791 if not isinstance(params, tuple):
792 params = (params,)
793 if len(params) == 2 and params[1] is ...:
794 msg = "Tuple[t, ...]: t must be a type."
795 p = _type_check(params[0], msg)
796 return self.copy_with((p, _TypingEllipsis))
797 msg = "Tuple[t0, t1, ...]: each t must be a type."
798 params = tuple(_type_check(p, msg) for p in params)
799 return self.copy_with(params)
800 if self.__origin__ is collections.abc.Callable and self._special:
801 args, result = params
802 msg = "Callable[args, result]: result must be a type."
803 result = _type_check(result, msg)
804 if args is Ellipsis:
805 return self.copy_with((_TypingEllipsis, result))
806 msg = "Callable[[arg, ...], result]: each arg must be a type."
807 args = tuple(_type_check(arg, msg) for arg in args)
808 params = args + (result,)
809 return self.copy_with(params)
810 return super().__getitem__(params)
811
812
813class Generic:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700814 """Abstract base class for generic types.
815
Guido van Rossumb24569a2016-11-20 18:01:29 -0800816 A generic type is typically declared by inheriting from
817 this class parameterized with one or more type variables.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700818 For example, a generic mapping type might be defined as::
819
820 class Mapping(Generic[KT, VT]):
821 def __getitem__(self, key: KT) -> VT:
822 ...
823 # Etc.
824
825 This class can then be used as follows::
826
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700827 def lookup_name(mapping: Mapping[KT, VT], key: KT, default: VT) -> VT:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700828 try:
829 return mapping[key]
830 except KeyError:
831 return default
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700832 """
Guido van Rossumd70fe632015-08-05 12:11:06 +0200833 __slots__ = ()
834
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700835 def __new__(cls, *args, **kwds):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000836 if cls is Generic:
Guido van Rossum62fe1bb2016-10-29 16:05:26 -0700837 raise TypeError("Type Generic cannot be instantiated; "
838 "it can be used only as a base class")
Miss Islington (bot)3c28a632018-05-08 18:44:09 -0700839 if super().__new__ is object.__new__:
840 obj = super().__new__(cls)
841 else:
842 obj = super().__new__(cls, *args, **kwds)
843 return obj
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000844
845 @_tp_cache
846 def __class_getitem__(cls, params):
847 if not isinstance(params, tuple):
848 params = (params,)
849 if not params and cls is not Tuple:
850 raise TypeError(
851 f"Parameter list to {cls.__qualname__}[...] cannot be empty")
852 msg = "Parameters to generic types must be types."
853 params = tuple(_type_check(p, msg) for p in params)
854 if cls is Generic:
855 # Generic can only be subscripted with unique type variables.
856 if not all(isinstance(p, TypeVar) for p in params):
857 raise TypeError(
858 "Parameters to Generic[...] must all be type variables")
859 if len(set(params)) != len(params):
860 raise TypeError(
861 "Parameters to Generic[...] must all be unique")
862 elif cls is _Protocol:
863 # _Protocol is internal at the moment, just skip the check
864 pass
865 else:
866 # Subscripting a regular Generic subclass.
867 _check_generic(cls, params)
868 return _GenericAlias(cls, params)
869
870 def __init_subclass__(cls, *args, **kwargs):
Miss Islington (bot)bd85c972018-04-04 09:51:34 -0700871 super().__init_subclass__(*args, **kwargs)
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000872 tvars = []
873 if '__orig_bases__' in cls.__dict__:
874 error = Generic in cls.__orig_bases__
875 else:
876 error = Generic in cls.__bases__ and cls.__name__ != '_Protocol'
877 if error:
878 raise TypeError("Cannot inherit from plain Generic")
879 if '__orig_bases__' in cls.__dict__:
880 tvars = _collect_type_vars(cls.__orig_bases__)
881 # Look for Generic[T1, ..., Tn].
882 # If found, tvars must be a subset of it.
883 # If not found, tvars is it.
884 # Also check for and reject plain Generic,
885 # and reject multiple Generic[...].
886 gvars = None
887 for base in cls.__orig_bases__:
888 if (isinstance(base, _GenericAlias) and
889 base.__origin__ is Generic):
890 if gvars is not None:
891 raise TypeError(
892 "Cannot inherit from Generic[...] multiple types.")
893 gvars = base.__parameters__
894 if gvars is None:
895 gvars = tvars
896 else:
897 tvarset = set(tvars)
898 gvarset = set(gvars)
899 if not tvarset <= gvarset:
900 s_vars = ', '.join(str(t) for t in tvars if t not in gvarset)
901 s_args = ', '.join(str(g) for g in gvars)
902 raise TypeError(f"Some type variables ({s_vars}) are"
903 f" not listed in Generic[{s_args}]")
904 tvars = gvars
905 cls.__parameters__ = tuple(tvars)
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700906
907
908class _TypingEmpty:
Guido van Rossumb24569a2016-11-20 18:01:29 -0800909 """Internal placeholder for () or []. Used by TupleMeta and CallableMeta
910 to allow empty list/tuple in specific places, without allowing them
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700911 to sneak in where prohibited.
912 """
913
914
915class _TypingEllipsis:
Guido van Rossumb24569a2016-11-20 18:01:29 -0800916 """Internal placeholder for ... (ellipsis)."""
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700917
918
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700919def cast(typ, val):
920 """Cast a value to a type.
921
922 This returns the value unchanged. To the type checker this
923 signals that the return value has the designated type, but at
924 runtime we intentionally don't check anything (we want this
925 to be as fast as possible).
926 """
927 return val
928
929
930def _get_defaults(func):
931 """Internal helper to extract the default arguments, by name."""
Guido van Rossum991d14f2016-11-09 13:12:51 -0800932 try:
933 code = func.__code__
934 except AttributeError:
935 # Some built-in functions don't have __code__, __defaults__, etc.
936 return {}
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700937 pos_count = code.co_argcount
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700938 arg_names = code.co_varnames
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700939 arg_names = arg_names[:pos_count]
940 defaults = func.__defaults__ or ()
941 kwdefaults = func.__kwdefaults__
942 res = dict(kwdefaults) if kwdefaults else {}
943 pos_offset = pos_count - len(defaults)
944 for name, value in zip(arg_names[pos_offset:], defaults):
945 assert name not in res
946 res[name] = value
947 return res
948
949
Ivan Levkivskyib692dc82017-02-13 22:50:14 +0100950_allowed_types = (types.FunctionType, types.BuiltinFunctionType,
951 types.MethodType, types.ModuleType,
Ivan Levkivskyif06e0212017-05-02 19:14:07 +0200952 WrapperDescriptorType, MethodWrapperType, MethodDescriptorType)
Ivan Levkivskyib692dc82017-02-13 22:50:14 +0100953
954
Guido van Rossum991d14f2016-11-09 13:12:51 -0800955def get_type_hints(obj, globalns=None, localns=None):
956 """Return type hints for an object.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700957
Guido van Rossum991d14f2016-11-09 13:12:51 -0800958 This is often the same as obj.__annotations__, but it handles
959 forward references encoded as string literals, and if necessary
960 adds Optional[t] if a default value equal to None is set.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700961
Guido van Rossum991d14f2016-11-09 13:12:51 -0800962 The argument may be a module, class, method, or function. The annotations
963 are returned as a dictionary. For classes, annotations include also
964 inherited members.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700965
Guido van Rossum991d14f2016-11-09 13:12:51 -0800966 TypeError is raised if the argument is not of a type that can contain
967 annotations, and an empty dictionary is returned if no annotations are
968 present.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700969
Guido van Rossum991d14f2016-11-09 13:12:51 -0800970 BEWARE -- the behavior of globalns and localns is counterintuitive
971 (unless you are familiar with how eval() and exec() work). The
972 search order is locals first, then globals.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700973
Guido van Rossum991d14f2016-11-09 13:12:51 -0800974 - If no dict arguments are passed, an attempt is made to use the
Łukasz Langaf350a262017-09-14 14:33:00 -0400975 globals from obj (or the respective module's globals for classes),
976 and these are also used as the locals. If the object does not appear
977 to have globals, an empty dictionary is used.
Guido van Rossum0a6976d2016-09-11 15:34:56 -0700978
Guido van Rossum991d14f2016-11-09 13:12:51 -0800979 - If one dict argument is passed, it is used for both globals and
980 locals.
Guido van Rossum0a6976d2016-09-11 15:34:56 -0700981
Guido van Rossum991d14f2016-11-09 13:12:51 -0800982 - If two dict arguments are passed, they specify globals and
983 locals, respectively.
984 """
Guido van Rossum0a6976d2016-09-11 15:34:56 -0700985
Guido van Rossum991d14f2016-11-09 13:12:51 -0800986 if getattr(obj, '__no_type_check__', None):
987 return {}
Guido van Rossum991d14f2016-11-09 13:12:51 -0800988 # Classes require a special treatment.
989 if isinstance(obj, type):
990 hints = {}
991 for base in reversed(obj.__mro__):
Łukasz Langaf350a262017-09-14 14:33:00 -0400992 if globalns is None:
993 base_globals = sys.modules[base.__module__].__dict__
994 else:
995 base_globals = globalns
Guido van Rossum991d14f2016-11-09 13:12:51 -0800996 ann = base.__dict__.get('__annotations__', {})
997 for name, value in ann.items():
998 if value is None:
999 value = type(None)
1000 if isinstance(value, str):
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001001 value = ForwardRef(value)
Łukasz Langaf350a262017-09-14 14:33:00 -04001002 value = _eval_type(value, base_globals, localns)
Guido van Rossum991d14f2016-11-09 13:12:51 -08001003 hints[name] = value
1004 return hints
Łukasz Langaf350a262017-09-14 14:33:00 -04001005
1006 if globalns is None:
1007 if isinstance(obj, types.ModuleType):
1008 globalns = obj.__dict__
1009 else:
1010 globalns = getattr(obj, '__globals__', {})
1011 if localns is None:
1012 localns = globalns
1013 elif localns is None:
1014 localns = globalns
Guido van Rossum991d14f2016-11-09 13:12:51 -08001015 hints = getattr(obj, '__annotations__', None)
1016 if hints is None:
1017 # Return empty annotations for something that _could_ have them.
Ivan Levkivskyib692dc82017-02-13 22:50:14 +01001018 if isinstance(obj, _allowed_types):
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001019 return {}
Guido van Rossum991d14f2016-11-09 13:12:51 -08001020 else:
1021 raise TypeError('{!r} is not a module, class, method, '
1022 'or function.'.format(obj))
1023 defaults = _get_defaults(obj)
1024 hints = dict(hints)
1025 for name, value in hints.items():
1026 if value is None:
1027 value = type(None)
1028 if isinstance(value, str):
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001029 value = ForwardRef(value)
Guido van Rossum991d14f2016-11-09 13:12:51 -08001030 value = _eval_type(value, globalns, localns)
1031 if name in defaults and defaults[name] is None:
1032 value = Optional[value]
1033 hints[name] = value
1034 return hints
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001035
1036
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001037def no_type_check(arg):
1038 """Decorator to indicate that annotations are not type hints.
1039
1040 The argument must be a class or function; if it is a class, it
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001041 applies recursively to all methods and classes defined in that class
1042 (but not to methods defined in its superclasses or subclasses).
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001043
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001044 This mutates the function(s) or class(es) in place.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001045 """
1046 if isinstance(arg, type):
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001047 arg_attrs = arg.__dict__.copy()
1048 for attr, val in arg.__dict__.items():
Ivan Levkivskyi65bc6202017-09-14 01:25:15 +02001049 if val in arg.__bases__ + (arg,):
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001050 arg_attrs.pop(attr)
1051 for obj in arg_attrs.values():
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001052 if isinstance(obj, types.FunctionType):
1053 obj.__no_type_check__ = True
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001054 if isinstance(obj, type):
1055 no_type_check(obj)
1056 try:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001057 arg.__no_type_check__ = True
Guido van Rossumd7adfe12017-01-22 17:43:53 -08001058 except TypeError: # built-in classes
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001059 pass
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001060 return arg
1061
1062
1063def no_type_check_decorator(decorator):
1064 """Decorator to give another decorator the @no_type_check effect.
1065
1066 This wraps the decorator with something that wraps the decorated
1067 function in @no_type_check.
1068 """
1069
1070 @functools.wraps(decorator)
1071 def wrapped_decorator(*args, **kwds):
1072 func = decorator(*args, **kwds)
1073 func = no_type_check(func)
1074 return func
1075
1076 return wrapped_decorator
1077
1078
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001079def _overload_dummy(*args, **kwds):
1080 """Helper for @overload to raise when called."""
1081 raise NotImplementedError(
1082 "You should not call an overloaded function. "
1083 "A series of @overload-decorated functions "
1084 "outside a stub module should always be followed "
1085 "by an implementation that is not @overload-ed.")
1086
1087
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001088def overload(func):
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001089 """Decorator for overloaded functions/methods.
1090
1091 In a stub file, place two or more stub definitions for the same
1092 function in a row, each decorated with @overload. For example:
1093
1094 @overload
1095 def utf8(value: None) -> None: ...
1096 @overload
1097 def utf8(value: bytes) -> bytes: ...
1098 @overload
1099 def utf8(value: str) -> bytes: ...
1100
1101 In a non-stub file (i.e. a regular .py file), do the same but
1102 follow it with an implementation. The implementation should *not*
1103 be decorated with @overload. For example:
1104
1105 @overload
1106 def utf8(value: None) -> None: ...
1107 @overload
1108 def utf8(value: bytes) -> bytes: ...
1109 @overload
1110 def utf8(value: str) -> bytes: ...
1111 def utf8(value):
1112 # implementation goes here
1113 """
1114 return _overload_dummy
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001115
1116
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001117class _ProtocolMeta(type):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001118 """Internal metaclass for _Protocol.
1119
1120 This exists so _Protocol classes can be generic without deriving
1121 from Generic.
1122 """
1123
Guido van Rossumd70fe632015-08-05 12:11:06 +02001124 def __instancecheck__(self, obj):
Guido van Rossumca4b2522016-11-19 10:32:41 -08001125 if _Protocol not in self.__bases__:
1126 return super().__instancecheck__(obj)
Guido van Rossumd70fe632015-08-05 12:11:06 +02001127 raise TypeError("Protocols cannot be used with isinstance().")
1128
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001129 def __subclasscheck__(self, cls):
1130 if not self._is_protocol:
1131 # No structural checks since this isn't a protocol.
1132 return NotImplemented
1133
1134 if self is _Protocol:
1135 # Every class is a subclass of the empty protocol.
1136 return True
1137
1138 # Find all attributes defined in the protocol.
1139 attrs = self._get_protocol_attrs()
1140
1141 for attr in attrs:
1142 if not any(attr in d.__dict__ for d in cls.__mro__):
1143 return False
1144 return True
1145
1146 def _get_protocol_attrs(self):
1147 # Get all Protocol base classes.
1148 protocol_bases = []
1149 for c in self.__mro__:
1150 if getattr(c, '_is_protocol', False) and c.__name__ != '_Protocol':
1151 protocol_bases.append(c)
1152
1153 # Get attributes included in protocol.
1154 attrs = set()
1155 for base in protocol_bases:
1156 for attr in base.__dict__.keys():
1157 # Include attributes not defined in any non-protocol bases.
1158 for c in self.__mro__:
1159 if (c is not base and attr in c.__dict__ and
1160 not getattr(c, '_is_protocol', False)):
1161 break
1162 else:
1163 if (not attr.startswith('_abc_') and
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001164 attr != '__abstractmethods__' and
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001165 attr != '__annotations__' and
1166 attr != '__weakref__' and
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001167 attr != '_is_protocol' and
Ivan Levkivskyi65bc6202017-09-14 01:25:15 +02001168 attr != '_gorg' and
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001169 attr != '__dict__' and
1170 attr != '__args__' and
1171 attr != '__slots__' and
1172 attr != '_get_protocol_attrs' and
1173 attr != '__next_in_mro__' and
1174 attr != '__parameters__' and
1175 attr != '__origin__' and
Guido van Rossum7ef22d62016-10-21 14:27:58 -07001176 attr != '__orig_bases__' and
Guido van Rossum1cea70f2016-05-18 08:35:00 -07001177 attr != '__extra__' and
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001178 attr != '__tree_hash__' and
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001179 attr != '__module__'):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001180 attrs.add(attr)
1181
1182 return attrs
1183
1184
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001185class _Protocol(Generic, metaclass=_ProtocolMeta):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001186 """Internal base class for protocol classes.
1187
Guido van Rossumb24569a2016-11-20 18:01:29 -08001188 This implements a simple-minded structural issubclass check
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001189 (similar but more general than the one-offs in collections.abc
1190 such as Hashable).
1191 """
1192
Guido van Rossumd70fe632015-08-05 12:11:06 +02001193 __slots__ = ()
1194
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001195 _is_protocol = True
1196
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001197 def __class_getitem__(cls, params):
1198 return super().__class_getitem__(params)
1199
1200
1201# Some unconstrained type variables. These are used by the container types.
1202# (These are not for export.)
1203T = TypeVar('T') # Any type.
1204KT = TypeVar('KT') # Key type.
1205VT = TypeVar('VT') # Value type.
1206T_co = TypeVar('T_co', covariant=True) # Any type covariant containers.
1207V_co = TypeVar('V_co', covariant=True) # Any type covariant containers.
1208VT_co = TypeVar('VT_co', covariant=True) # Value type covariant containers.
1209T_contra = TypeVar('T_contra', contravariant=True) # Ditto contravariant.
1210# Internal type variable used for Type[].
1211CT_co = TypeVar('CT_co', covariant=True, bound=type)
1212
1213# A useful type variable with constraints. This represents string types.
1214# (This one *is* for export!)
1215AnyStr = TypeVar('AnyStr', bytes, str)
1216
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001217
1218# Various ABCs mimicking those in collections.abc.
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001219def _alias(origin, params, inst=True):
1220 return _GenericAlias(origin, params, special=True, inst=inst)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001221
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001222Hashable = _alias(collections.abc.Hashable, ()) # Not generic.
1223Awaitable = _alias(collections.abc.Awaitable, T_co)
1224Coroutine = _alias(collections.abc.Coroutine, (T_co, T_contra, V_co))
1225AsyncIterable = _alias(collections.abc.AsyncIterable, T_co)
1226AsyncIterator = _alias(collections.abc.AsyncIterator, T_co)
1227Iterable = _alias(collections.abc.Iterable, T_co)
1228Iterator = _alias(collections.abc.Iterator, T_co)
1229Reversible = _alias(collections.abc.Reversible, T_co)
1230Sized = _alias(collections.abc.Sized, ()) # Not generic.
1231Container = _alias(collections.abc.Container, T_co)
1232Collection = _alias(collections.abc.Collection, T_co)
1233Callable = _VariadicGenericAlias(collections.abc.Callable, (), special=True)
1234Callable.__doc__ = \
1235 """Callable type; Callable[[int], str] is a function of (int) -> str.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001236
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001237 The subscription syntax must always be used with exactly two
1238 values: the argument list and the return type. The argument list
1239 must be a list of types or ellipsis; the return type must be a single type.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001240
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001241 There is no syntax to indicate optional or keyword arguments,
1242 such function types are rarely used as callback types.
1243 """
1244AbstractSet = _alias(collections.abc.Set, T_co)
1245MutableSet = _alias(collections.abc.MutableSet, T)
1246# NOTE: Mapping is only covariant in the value type.
1247Mapping = _alias(collections.abc.Mapping, (KT, VT_co))
1248MutableMapping = _alias(collections.abc.MutableMapping, (KT, VT))
1249Sequence = _alias(collections.abc.Sequence, T_co)
1250MutableSequence = _alias(collections.abc.MutableSequence, T)
1251ByteString = _alias(collections.abc.ByteString, ()) # Not generic
1252Tuple = _VariadicGenericAlias(tuple, (), inst=False, special=True)
1253Tuple.__doc__ = \
1254 """Tuple type; Tuple[X, Y] is the cross-product type of X and Y.
Guido van Rossum62fe1bb2016-10-29 16:05:26 -07001255
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001256 Example: Tuple[T1, T2] is a tuple of two elements corresponding
1257 to type variables T1 and T2. Tuple[int, float, str] is a tuple
1258 of an int, a float and a string.
Guido van Rossum62fe1bb2016-10-29 16:05:26 -07001259
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001260 To specify a variable-length tuple of homogeneous type, use Tuple[T, ...].
1261 """
1262List = _alias(list, T, inst=False)
1263Deque = _alias(collections.deque, T)
1264Set = _alias(set, T, inst=False)
1265FrozenSet = _alias(frozenset, T_co, inst=False)
1266MappingView = _alias(collections.abc.MappingView, T_co)
1267KeysView = _alias(collections.abc.KeysView, KT)
1268ItemsView = _alias(collections.abc.ItemsView, (KT, VT_co))
1269ValuesView = _alias(collections.abc.ValuesView, VT_co)
1270ContextManager = _alias(contextlib.AbstractContextManager, T_co)
1271AsyncContextManager = _alias(contextlib.AbstractAsyncContextManager, T_co)
1272Dict = _alias(dict, (KT, VT), inst=False)
1273DefaultDict = _alias(collections.defaultdict, (KT, VT))
1274Counter = _alias(collections.Counter, T)
1275ChainMap = _alias(collections.ChainMap, (KT, VT))
1276Generator = _alias(collections.abc.Generator, (T_co, T_contra, V_co))
1277AsyncGenerator = _alias(collections.abc.AsyncGenerator, (T_co, T_contra))
1278Type = _alias(type, CT_co, inst=False)
1279Type.__doc__ = \
1280 """A special construct usable to annotate class objects.
Guido van Rossum62fe1bb2016-10-29 16:05:26 -07001281
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001282 For example, suppose we have the following classes::
Guido van Rossum62fe1bb2016-10-29 16:05:26 -07001283
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001284 class User: ... # Abstract base for User classes
1285 class BasicUser(User): ...
1286 class ProUser(User): ...
1287 class TeamUser(User): ...
Guido van Rossumf17c2002015-12-03 17:31:24 -08001288
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001289 And a function that takes a class argument that's a subclass of
1290 User and returns an instance of the corresponding class::
Guido van Rossumf17c2002015-12-03 17:31:24 -08001291
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001292 U = TypeVar('U', bound=User)
1293 def new_user(user_class: Type[U]) -> U:
1294 user = user_class()
1295 # (Here we could write the user object to a database)
1296 return user
Guido van Rossumf17c2002015-12-03 17:31:24 -08001297
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001298 joe = new_user(BasicUser)
Guido van Rossumf17c2002015-12-03 17:31:24 -08001299
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001300 At this point the type checker knows that joe has type BasicUser.
1301 """
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001302
1303
1304class SupportsInt(_Protocol):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001305 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001306
1307 @abstractmethod
1308 def __int__(self) -> int:
1309 pass
1310
1311
1312class SupportsFloat(_Protocol):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001313 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001314
1315 @abstractmethod
1316 def __float__(self) -> float:
1317 pass
1318
1319
1320class SupportsComplex(_Protocol):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001321 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001322
1323 @abstractmethod
1324 def __complex__(self) -> complex:
1325 pass
1326
1327
1328class SupportsBytes(_Protocol):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001329 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001330
1331 @abstractmethod
1332 def __bytes__(self) -> bytes:
1333 pass
1334
1335
Guido van Rossumd70fe632015-08-05 12:11:06 +02001336class SupportsAbs(_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 __abs__(self) -> T_co:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001341 pass
1342
1343
Guido van Rossumd70fe632015-08-05 12:11:06 +02001344class SupportsRound(_Protocol[T_co]):
1345 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001346
1347 @abstractmethod
Guido van Rossumd70fe632015-08-05 12:11:06 +02001348 def __round__(self, ndigits: int = 0) -> T_co:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001349 pass
1350
1351
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001352def _make_nmtuple(name, types):
Guido van Rossum2f841442016-11-15 09:48:06 -08001353 msg = "NamedTuple('Name', [(f0, t0), (f1, t1), ...]); each t must be a type"
1354 types = [(n, _type_check(t, msg)) for n, t in types]
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001355 nm_tpl = collections.namedtuple(name, [n for n, t in types])
Guido van Rossum83ec3022017-01-17 20:43:28 -08001356 # Prior to PEP 526, only _field_types attribute was assigned.
1357 # Now, both __annotations__ and _field_types are used to maintain compatibility.
1358 nm_tpl.__annotations__ = nm_tpl._field_types = collections.OrderedDict(types)
Guido van Rossum557d1eb2015-11-19 08:16:31 -08001359 try:
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001360 nm_tpl.__module__ = sys._getframe(2).f_globals.get('__name__', '__main__')
Guido van Rossum557d1eb2015-11-19 08:16:31 -08001361 except (AttributeError, ValueError):
1362 pass
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001363 return nm_tpl
1364
1365
Ivan Levkivskyib692dc82017-02-13 22:50:14 +01001366# attributes prohibited to set in NamedTuple class syntax
1367_prohibited = ('__new__', '__init__', '__slots__', '__getnewargs__',
1368 '_fields', '_field_defaults', '_field_types',
Ivan Levkivskyif06e0212017-05-02 19:14:07 +02001369 '_make', '_replace', '_asdict', '_source')
Ivan Levkivskyib692dc82017-02-13 22:50:14 +01001370
1371_special = ('__module__', '__name__', '__qualname__', '__annotations__')
1372
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001373
Guido van Rossum2f841442016-11-15 09:48:06 -08001374class NamedTupleMeta(type):
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001375
Guido van Rossum2f841442016-11-15 09:48:06 -08001376 def __new__(cls, typename, bases, ns):
1377 if ns.get('_root', False):
1378 return super().__new__(cls, typename, bases, ns)
Guido van Rossum2f841442016-11-15 09:48:06 -08001379 types = ns.get('__annotations__', {})
Guido van Rossum3c268be2017-01-18 08:03:50 -08001380 nm_tpl = _make_nmtuple(typename, types.items())
1381 defaults = []
1382 defaults_dict = {}
1383 for field_name in types:
1384 if field_name in ns:
1385 default_value = ns[field_name]
1386 defaults.append(default_value)
1387 defaults_dict[field_name] = default_value
1388 elif defaults:
Guido van Rossumd7adfe12017-01-22 17:43:53 -08001389 raise TypeError("Non-default namedtuple field {field_name} cannot "
1390 "follow default field(s) {default_names}"
Guido van Rossum3c268be2017-01-18 08:03:50 -08001391 .format(field_name=field_name,
1392 default_names=', '.join(defaults_dict.keys())))
Miss Islington (bot)3c28a632018-05-08 18:44:09 -07001393 nm_tpl.__new__.__annotations__ = collections.OrderedDict(types)
Guido van Rossum3c268be2017-01-18 08:03:50 -08001394 nm_tpl.__new__.__defaults__ = tuple(defaults)
1395 nm_tpl._field_defaults = defaults_dict
Guido van Rossum95919c02017-01-22 17:47:20 -08001396 # update from user namespace without overriding special namedtuple attributes
1397 for key in ns:
Ivan Levkivskyib692dc82017-02-13 22:50:14 +01001398 if key in _prohibited:
1399 raise AttributeError("Cannot overwrite NamedTuple attribute " + key)
1400 elif key not in _special and key not in nm_tpl._fields:
Guido van Rossum95919c02017-01-22 17:47:20 -08001401 setattr(nm_tpl, key, ns[key])
Guido van Rossum3c268be2017-01-18 08:03:50 -08001402 return nm_tpl
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001403
Guido van Rossumd7adfe12017-01-22 17:43:53 -08001404
Guido van Rossum2f841442016-11-15 09:48:06 -08001405class NamedTuple(metaclass=NamedTupleMeta):
1406 """Typed version of namedtuple.
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001407
Guido van Rossum2f841442016-11-15 09:48:06 -08001408 Usage in Python versions >= 3.6::
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001409
Guido van Rossum2f841442016-11-15 09:48:06 -08001410 class Employee(NamedTuple):
1411 name: str
1412 id: int
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001413
Guido van Rossum2f841442016-11-15 09:48:06 -08001414 This is equivalent to::
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001415
Guido van Rossum2f841442016-11-15 09:48:06 -08001416 Employee = collections.namedtuple('Employee', ['name', 'id'])
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001417
Guido van Rossum83ec3022017-01-17 20:43:28 -08001418 The resulting class has extra __annotations__ and _field_types
1419 attributes, giving an ordered dict mapping field names to types.
1420 __annotations__ should be preferred, while _field_types
1421 is kept to maintain pre PEP 526 compatibility. (The field names
Guido van Rossum2f841442016-11-15 09:48:06 -08001422 are in the _fields attribute, which is part of the namedtuple
1423 API.) Alternative equivalent keyword syntax is also accepted::
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001424
Guido van Rossum2f841442016-11-15 09:48:06 -08001425 Employee = NamedTuple('Employee', name=str, id=int)
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001426
Guido van Rossum2f841442016-11-15 09:48:06 -08001427 In Python versions <= 3.5 use::
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001428
Guido van Rossum2f841442016-11-15 09:48:06 -08001429 Employee = NamedTuple('Employee', [('name', str), ('id', int)])
1430 """
1431 _root = True
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001432
Guido van Rossum2f841442016-11-15 09:48:06 -08001433 def __new__(self, typename, fields=None, **kwargs):
Guido van Rossum2f841442016-11-15 09:48:06 -08001434 if fields is None:
1435 fields = kwargs.items()
1436 elif kwargs:
1437 raise TypeError("Either list of fields or keywords"
1438 " can be provided to NamedTuple, not both")
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001439 return _make_nmtuple(typename, fields)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001440
1441
Guido van Rossum91185fe2016-06-08 11:19:11 -07001442def NewType(name, tp):
1443 """NewType creates simple unique types with almost zero
1444 runtime overhead. NewType(name, tp) is considered a subtype of tp
1445 by static type checkers. At runtime, NewType(name, tp) returns
1446 a dummy function that simply returns its argument. Usage::
1447
1448 UserId = NewType('UserId', int)
1449
1450 def name_by_id(user_id: UserId) -> str:
1451 ...
1452
1453 UserId('user') # Fails type check
1454
1455 name_by_id(42) # Fails type check
1456 name_by_id(UserId(42)) # OK
1457
1458 num = UserId(5) + 1 # type: int
1459 """
1460
1461 def new_type(x):
1462 return x
1463
1464 new_type.__name__ = name
1465 new_type.__supertype__ = tp
1466 return new_type
1467
1468
Guido van Rossum0e0563c2016-04-05 14:54:25 -07001469# Python-version-specific alias (Python 2: unicode; Python 3: str)
1470Text = str
1471
1472
Guido van Rossum91185fe2016-06-08 11:19:11 -07001473# Constant that's True when type checking, but False here.
1474TYPE_CHECKING = False
1475
1476
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001477class IO(Generic[AnyStr]):
1478 """Generic base class for TextIO and BinaryIO.
1479
1480 This is an abstract, generic version of the return of open().
1481
1482 NOTE: This does not distinguish between the different possible
1483 classes (text vs. binary, read vs. write vs. read/write,
1484 append-only, unbuffered). The TextIO and BinaryIO subclasses
1485 below capture the distinctions between text vs. binary, which is
1486 pervasive in the interface; however we currently do not offer a
1487 way to track the other distinctions in the type system.
1488 """
1489
Guido van Rossumd70fe632015-08-05 12:11:06 +02001490 __slots__ = ()
1491
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001492 @abstractproperty
1493 def mode(self) -> str:
1494 pass
1495
1496 @abstractproperty
1497 def name(self) -> str:
1498 pass
1499
1500 @abstractmethod
1501 def close(self) -> None:
1502 pass
1503
1504 @abstractmethod
1505 def closed(self) -> bool:
1506 pass
1507
1508 @abstractmethod
1509 def fileno(self) -> int:
1510 pass
1511
1512 @abstractmethod
1513 def flush(self) -> None:
1514 pass
1515
1516 @abstractmethod
1517 def isatty(self) -> bool:
1518 pass
1519
1520 @abstractmethod
1521 def read(self, n: int = -1) -> AnyStr:
1522 pass
1523
1524 @abstractmethod
1525 def readable(self) -> bool:
1526 pass
1527
1528 @abstractmethod
1529 def readline(self, limit: int = -1) -> AnyStr:
1530 pass
1531
1532 @abstractmethod
1533 def readlines(self, hint: int = -1) -> List[AnyStr]:
1534 pass
1535
1536 @abstractmethod
1537 def seek(self, offset: int, whence: int = 0) -> int:
1538 pass
1539
1540 @abstractmethod
1541 def seekable(self) -> bool:
1542 pass
1543
1544 @abstractmethod
1545 def tell(self) -> int:
1546 pass
1547
1548 @abstractmethod
1549 def truncate(self, size: int = None) -> int:
1550 pass
1551
1552 @abstractmethod
1553 def writable(self) -> bool:
1554 pass
1555
1556 @abstractmethod
1557 def write(self, s: AnyStr) -> int:
1558 pass
1559
1560 @abstractmethod
1561 def writelines(self, lines: List[AnyStr]) -> None:
1562 pass
1563
1564 @abstractmethod
1565 def __enter__(self) -> 'IO[AnyStr]':
1566 pass
1567
1568 @abstractmethod
1569 def __exit__(self, type, value, traceback) -> None:
1570 pass
1571
1572
1573class BinaryIO(IO[bytes]):
1574 """Typed version of the return of open() in binary mode."""
1575
Guido van Rossumd70fe632015-08-05 12:11:06 +02001576 __slots__ = ()
1577
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001578 @abstractmethod
1579 def write(self, s: Union[bytes, bytearray]) -> int:
1580 pass
1581
1582 @abstractmethod
1583 def __enter__(self) -> 'BinaryIO':
1584 pass
1585
1586
1587class TextIO(IO[str]):
1588 """Typed version of the return of open() in text mode."""
1589
Guido van Rossumd70fe632015-08-05 12:11:06 +02001590 __slots__ = ()
1591
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001592 @abstractproperty
1593 def buffer(self) -> BinaryIO:
1594 pass
1595
1596 @abstractproperty
1597 def encoding(self) -> str:
1598 pass
1599
1600 @abstractproperty
Guido van Rossum991d14f2016-11-09 13:12:51 -08001601 def errors(self) -> Optional[str]:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001602 pass
1603
1604 @abstractproperty
1605 def line_buffering(self) -> bool:
1606 pass
1607
1608 @abstractproperty
1609 def newlines(self) -> Any:
1610 pass
1611
1612 @abstractmethod
1613 def __enter__(self) -> 'TextIO':
1614 pass
1615
1616
1617class io:
1618 """Wrapper namespace for IO generic classes."""
1619
1620 __all__ = ['IO', 'TextIO', 'BinaryIO']
1621 IO = IO
1622 TextIO = TextIO
1623 BinaryIO = BinaryIO
1624
Guido van Rossumd7adfe12017-01-22 17:43:53 -08001625
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001626io.__name__ = __name__ + '.io'
1627sys.modules[io.__name__] = io
1628
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001629Pattern = _alias(stdlib_re.Pattern, AnyStr)
1630Match = _alias(stdlib_re.Match, AnyStr)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001631
1632class re:
1633 """Wrapper namespace for re type aliases."""
1634
1635 __all__ = ['Pattern', 'Match']
1636 Pattern = Pattern
1637 Match = Match
1638
Guido van Rossumd7adfe12017-01-22 17:43:53 -08001639
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001640re.__name__ = __name__ + '.re'
1641sys.modules[re.__name__] = re