blob: 56126cfc02470e886c2eb9affce3027196c142f1 [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
288
289class _SpecialForm(_Final, _root=True):
290 """Internal indicator of special typing constructs.
291 See _doc instance attribute for specific docs.
292 """
293
294 __slots__ = ('_name', '_doc')
295
296 def __getstate__(self):
297 return {'name': self._name, 'doc': self._doc}
298
299 def __setstate__(self, state):
300 self._name = state['name']
301 self._doc = state['doc']
Guido van Rossum4cefe742016-09-27 15:20:12 -0700302
303 def __new__(cls, *args, **kwds):
304 """Constructor.
305
306 This only exists to give a better error message in case
307 someone tries to subclass a special typing object (not a good idea).
308 """
309 if (len(args) == 3 and
310 isinstance(args[0], str) and
311 isinstance(args[1], tuple)):
312 # Close enough.
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000313 raise TypeError(f"Cannot subclass {cls!r}")
Guido van Rossumb47c9d22016-10-03 08:40:50 -0700314 return super().__new__(cls)
Guido van Rossum4cefe742016-09-27 15:20:12 -0700315
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000316 def __init__(self, name, doc):
317 self._name = name
318 self._doc = doc
Guido van Rossum4cefe742016-09-27 15:20:12 -0700319
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000320 def __eq__(self, other):
321 if not isinstance(other, _SpecialForm):
322 return NotImplemented
323 return self._name == other._name
324
325 def __hash__(self):
326 return hash((self._name,))
Guido van Rossum4cefe742016-09-27 15:20:12 -0700327
328 def __repr__(self):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000329 return 'typing.' + self._name
330
331 def __copy__(self):
332 return self # Special forms are immutable.
Guido van Rossum4cefe742016-09-27 15:20:12 -0700333
334 def __call__(self, *args, **kwds):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000335 raise TypeError(f"Cannot instantiate {self!r}")
336
337 def __instancecheck__(self, obj):
338 raise TypeError(f"{self} cannot be used with isinstance()")
339
340 def __subclasscheck__(self, cls):
341 raise TypeError(f"{self} cannot be used with issubclass()")
342
343 @_tp_cache
344 def __getitem__(self, parameters):
345 if self._name == 'ClassVar':
346 item = _type_check(parameters, 'ClassVar accepts only single type.')
347 return _GenericAlias(self, (item,))
348 if self._name == 'Union':
349 if parameters == ():
350 raise TypeError("Cannot take a Union of no types.")
351 if not isinstance(parameters, tuple):
352 parameters = (parameters,)
353 msg = "Union[arg, ...]: each arg must be a type."
354 parameters = tuple(_type_check(p, msg) for p in parameters)
355 parameters = _remove_dups_flatten(parameters)
356 if len(parameters) == 1:
357 return parameters[0]
358 return _GenericAlias(self, parameters)
359 if self._name == 'Optional':
360 arg = _type_check(parameters, "Optional[t] requires a single type.")
361 return Union[arg, type(None)]
362 raise TypeError(f"{self} is not subscriptable")
Guido van Rossum4cefe742016-09-27 15:20:12 -0700363
364
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000365Any = _SpecialForm('Any', doc=
366 """Special type indicating an unconstrained type.
Guido van Rossumb47c9d22016-10-03 08:40:50 -0700367
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000368 - Any is compatible with every type.
369 - Any assumed to have all methods.
370 - All values assumed to be instances of Any.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700371
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000372 Note that all the above statements are true from the point of view of
373 static type checkers. At runtime, Any should not be used with instance
374 or class checks.
375 """)
Guido van Rossumd70fe632015-08-05 12:11:06 +0200376
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000377NoReturn = _SpecialForm('NoReturn', doc=
378 """Special type indicating functions that never return.
379 Example::
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700380
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000381 from typing import NoReturn
382
383 def stop() -> NoReturn:
384 raise Exception('no way')
385
386 This type is invalid in other positions, e.g., ``List[NoReturn]``
387 will fail in static type checkers.
388 """)
389
390ClassVar = _SpecialForm('ClassVar', doc=
391 """Special type construct to mark class variables.
392
393 An annotation wrapped in ClassVar indicates that a given
394 attribute is intended to be used as a class variable and
395 should not be set on instances of that class. Usage::
396
397 class Starship:
398 stats: ClassVar[Dict[str, int]] = {} # class variable
399 damage: int = 10 # instance variable
400
401 ClassVar accepts only types and cannot be further subscribed.
402
403 Note that ClassVar is not a class itself, and should not
404 be used with isinstance() or issubclass().
405 """)
406
407Union = _SpecialForm('Union', doc=
408 """Union type; Union[X, Y] means either X or Y.
409
410 To define a union, use e.g. Union[int, str]. Details:
411 - The arguments must be types and there must be at least one.
412 - None as an argument is a special case and is replaced by
413 type(None).
414 - Unions of unions are flattened, e.g.::
415
416 Union[Union[int, str], float] == Union[int, str, float]
417
418 - Unions of a single argument vanish, e.g.::
419
420 Union[int] == int # The constructor actually returns int
421
422 - Redundant arguments are skipped, e.g.::
423
424 Union[int, str, int] == Union[int, str]
425
426 - When comparing unions, the argument order is ignored, e.g.::
427
428 Union[int, str] == Union[str, int]
429
430 - When two arguments have a subclass relationship, the least
431 derived argument is kept, e.g.::
432
433 class Employee: pass
434 class Manager(Employee): pass
435 Union[int, Employee, Manager] == Union[int, Employee]
436 Union[Manager, int, Employee] == Union[int, Employee]
437 Union[Employee, Manager] == Employee
438
439 - Similar for object::
440
441 Union[int, object] == object
442
443 - You cannot subclass or instantiate a union.
444 - You can use Optional[X] as a shorthand for Union[X, None].
445 """)
446
447Optional = _SpecialForm('Optional', doc=
448 """Optional type.
449
450 Optional[X] is equivalent to Union[X, None].
451 """)
Guido van Rossumb7dedc82016-10-29 12:44:29 -0700452
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700453
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000454class ForwardRef(_Final, _root=True):
Guido van Rossumb24569a2016-11-20 18:01:29 -0800455 """Internal wrapper to hold a forward reference."""
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700456
Guido van Rossum4cefe742016-09-27 15:20:12 -0700457 __slots__ = ('__forward_arg__', '__forward_code__',
Guido van Rossumc7b92952016-11-10 08:24:06 -0800458 '__forward_evaluated__', '__forward_value__')
Guido van Rossum4cefe742016-09-27 15:20:12 -0700459
460 def __init__(self, arg):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700461 if not isinstance(arg, str):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000462 raise TypeError(f"Forward reference must be a string -- got {arg!r}")
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700463 try:
464 code = compile(arg, '<string>', 'eval')
465 except SyntaxError:
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000466 raise SyntaxError(f"Forward reference must be an expression -- got {arg!r}")
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700467 self.__forward_arg__ = arg
468 self.__forward_code__ = code
469 self.__forward_evaluated__ = False
470 self.__forward_value__ = None
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700471
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000472 def _evaluate(self, globalns, localns):
Guido van Rossumdad17902016-11-10 08:29:18 -0800473 if not self.__forward_evaluated__ or localns is not globalns:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700474 if globalns is None and localns is None:
475 globalns = localns = {}
476 elif globalns is None:
477 globalns = localns
478 elif localns is None:
479 localns = globalns
480 self.__forward_value__ = _type_check(
481 eval(self.__forward_code__, globalns, localns),
482 "Forward references must evaluate to types.")
483 self.__forward_evaluated__ = True
484 return self.__forward_value__
485
Guido van Rossum4cefe742016-09-27 15:20:12 -0700486 def __eq__(self, other):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000487 if not isinstance(other, ForwardRef):
Guido van Rossum4cefe742016-09-27 15:20:12 -0700488 return NotImplemented
489 return (self.__forward_arg__ == other.__forward_arg__ and
Guido van Rossumc7b92952016-11-10 08:24:06 -0800490 self.__forward_value__ == other.__forward_value__)
Guido van Rossum4cefe742016-09-27 15:20:12 -0700491
492 def __hash__(self):
Guido van Rossumc7b92952016-11-10 08:24:06 -0800493 return hash((self.__forward_arg__, self.__forward_value__))
Guido van Rossum4cefe742016-09-27 15:20:12 -0700494
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700495 def __repr__(self):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000496 return f'ForwardRef({self.__forward_arg__!r})'
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700497
498
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000499class TypeVar(_Final, _root=True):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700500 """Type variable.
501
502 Usage::
503
504 T = TypeVar('T') # Can be anything
505 A = TypeVar('A', str, bytes) # Must be str or bytes
506
507 Type variables exist primarily for the benefit of static type
508 checkers. They serve as the parameters for generic types as well
509 as for generic function definitions. See class Generic for more
510 information on generic types. Generic functions work as follows:
511
Guido van Rossumb24569a2016-11-20 18:01:29 -0800512 def repeat(x: T, n: int) -> List[T]:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700513 '''Return a list containing n references to x.'''
514 return [x]*n
515
516 def longest(x: A, y: A) -> A:
517 '''Return the longest of two strings.'''
518 return x if len(x) >= len(y) else y
519
520 The latter example's signature is essentially the overloading
521 of (str, str) -> str and (bytes, bytes) -> bytes. Also note
522 that if the arguments are instances of some subclass of str,
523 the return type is still plain str.
524
Guido van Rossumb24569a2016-11-20 18:01:29 -0800525 At runtime, isinstance(x, T) and issubclass(C, T) will raise TypeError.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700526
Guido van Rossumefa798d2016-08-23 11:01:50 -0700527 Type variables defined with covariant=True or contravariant=True
528 can be used do declare covariant or contravariant generic types.
529 See PEP 484 for more details. By default generic types are invariant
530 in all type variables.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700531
532 Type variables can be introspected. e.g.:
533
534 T.__name__ == 'T'
535 T.__constraints__ == ()
536 T.__covariant__ == False
537 T.__contravariant__ = False
538 A.__constraints__ == (str, bytes)
539 """
540
Guido van Rossum4cefe742016-09-27 15:20:12 -0700541 __slots__ = ('__name__', '__bound__', '__constraints__',
542 '__covariant__', '__contravariant__')
543
544 def __init__(self, name, *constraints, bound=None,
Guido van Rossumd7adfe12017-01-22 17:43:53 -0800545 covariant=False, contravariant=False):
Guido van Rossum4cefe742016-09-27 15:20:12 -0700546 self.__name__ = name
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700547 if covariant and contravariant:
Guido van Rossumefa798d2016-08-23 11:01:50 -0700548 raise ValueError("Bivariant types are not supported.")
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700549 self.__covariant__ = bool(covariant)
550 self.__contravariant__ = bool(contravariant)
551 if constraints and bound is not None:
552 raise TypeError("Constraints cannot be combined with bound=...")
553 if constraints and len(constraints) == 1:
554 raise TypeError("A single constraint is not allowed")
555 msg = "TypeVar(name, constraint, ...): constraints must be types."
556 self.__constraints__ = tuple(_type_check(t, msg) for t in constraints)
557 if bound:
558 self.__bound__ = _type_check(bound, "Bound must be a type.")
559 else:
560 self.__bound__ = None
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700561
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000562 def __getstate__(self):
563 return {'name': self.__name__,
564 'bound': self.__bound__,
565 'constraints': self.__constraints__,
566 'co': self.__covariant__,
567 'contra': self.__contravariant__}
568
569 def __setstate__(self, state):
570 self.__name__ = state['name']
571 self.__bound__ = state['bound']
572 self.__constraints__ = state['constraints']
573 self.__covariant__ = state['co']
574 self.__contravariant__ = state['contra']
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700575
576 def __repr__(self):
577 if self.__covariant__:
578 prefix = '+'
579 elif self.__contravariant__:
580 prefix = '-'
581 else:
582 prefix = '~'
583 return prefix + self.__name__
584
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700585
Guido van Rossum83ec3022017-01-17 20:43:28 -0800586# Special typing constructs Union, Optional, Generic, Callable and Tuple
587# use three special attributes for internal bookkeeping of generic types:
588# * __parameters__ is a tuple of unique free type parameters of a generic
589# type, for example, Dict[T, T].__parameters__ == (T,);
590# * __origin__ keeps a reference to a type that was subscripted,
591# e.g., Union[T, int].__origin__ == Union;
592# * __args__ is a tuple of all arguments used in subscripting,
593# e.g., Dict[T, int].__args__ == (T, int).
594
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000595def _is_dunder(attr):
596 return attr.startswith('__') and attr.endswith('__')
Guido van Rossum83ec3022017-01-17 20:43:28 -0800597
Guido van Rossumb24569a2016-11-20 18:01:29 -0800598
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000599class _GenericAlias(_Final, _root=True):
600 """The central part of internal API.
601
602 This represents a generic version of type 'origin' with type arguments 'params'.
603 There are two kind of these aliases: user defined and special. The special ones
604 are wrappers around builtin collections and ABCs in collections.abc. These must
605 have 'name' always set. If 'inst' is False, then the alias can't be instantiated,
606 this is used by e.g. typing.List and typing.Dict.
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700607 """
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000608 def __init__(self, origin, params, *, inst=True, special=False, name=None):
609 self._inst = inst
610 self._special = special
611 if special and name is None:
612 orig_name = origin.__name__
613 name = orig_name[0].title() + orig_name[1:]
614 self._name = name
615 if not isinstance(params, tuple):
616 params = (params,)
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700617 self.__origin__ = origin
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700618 self.__args__ = tuple(... if a is _TypingEllipsis else
619 () if a is _TypingEmpty else
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000620 a for a in params)
621 self.__parameters__ = _collect_type_vars(params)
622 self.__slots__ = None # This is not documented.
623 if not name:
624 self.__module__ = origin.__module__
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700625
Guido van Rossum4cefe742016-09-27 15:20:12 -0700626 @_tp_cache
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700627 def __getitem__(self, params):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000628 if self.__origin__ in (Generic, _Protocol):
629 # Can't subscript Generic[...] or _Protocol[...].
630 raise TypeError(f"Cannot subscript already-subscripted {self}")
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700631 if not isinstance(params, tuple):
632 params = (params,)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700633 msg = "Parameters to generic types must be types."
634 params = tuple(_type_check(p, msg) for p in params)
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000635 _check_generic(self, params)
636 return _subs_tvars(self, self.__parameters__, params)
Ivan Levkivskyib692dc82017-02-13 22:50:14 +0100637
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000638 def copy_with(self, params):
639 # We don't copy self._special.
640 return _GenericAlias(self.__origin__, params, name=self._name, inst=self._inst)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700641
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000642 def __repr__(self):
643 if (self._name != 'Callable' or
644 len(self.__args__) == 2 and self.__args__[0] is Ellipsis):
645 if self._name:
646 name = 'typing.' + self._name
647 else:
648 name = _type_repr(self.__origin__)
649 if not self._special:
650 args = f'[{", ".join([_type_repr(a) for a in self.__args__])}]'
651 else:
652 args = ''
653 return (f'{name}{args}')
654 if self._special:
655 return 'typing.Callable'
656 return (f'typing.Callable'
657 f'[[{", ".join([_type_repr(a) for a in self.__args__[:-1]])}], '
658 f'{_type_repr(self.__args__[-1])}]')
659
660 def __eq__(self, other):
661 if not isinstance(other, _GenericAlias):
662 return NotImplemented
663 if self.__origin__ != other.__origin__:
Ivan Levkivskyib692dc82017-02-13 22:50:14 +0100664 return False
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000665 if self.__origin__ is Union and other.__origin__ is Union:
666 return frozenset(self.__args__) == frozenset(other.__args__)
667 return self.__args__ == other.__args__
Ivan Levkivskyib692dc82017-02-13 22:50:14 +0100668
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000669 def __hash__(self):
670 if self.__origin__ is Union:
671 return hash((Union, frozenset(self.__args__)))
672 return hash((self.__origin__, self.__args__))
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700673
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000674 def __call__(self, *args, **kwargs):
675 if not self._inst:
676 raise TypeError(f"Type {self._name} cannot be instantiated; "
677 f"use {self._name.lower()}() instead")
678 result = self.__origin__(*args, **kwargs)
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700679 try:
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000680 result.__orig_class__ = self
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700681 except AttributeError:
682 pass
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000683 return result
684
685 def __mro_entries__(self, bases):
686 if self._name: # generic version of an ABC or built-in class
687 res = []
688 if self.__origin__ not in bases:
689 res.append(self.__origin__)
690 i = bases.index(self)
691 if not any(isinstance(b, _GenericAlias) or issubclass(b, Generic)
692 for b in bases[i+1:]):
693 res.append(Generic)
694 return tuple(res)
695 if self.__origin__ is Generic:
696 i = bases.index(self)
697 for b in bases[i+1:]:
698 if isinstance(b, _GenericAlias) and b is not self:
699 return ()
700 return (self.__origin__,)
701
702 def __getattr__(self, attr):
703 # We are carefull for copy and pickle.
704 # Also for simplicity we just don't relay all dunder names
705 if '__origin__' in self.__dict__ and not _is_dunder(attr):
706 return getattr(self.__origin__, attr)
707 raise AttributeError(attr)
708
709 def __setattr__(self, attr, val):
710 if _is_dunder(attr) or attr in ('_name', '_inst', '_special'):
711 super().__setattr__(attr, val)
712 else:
713 setattr(self.__origin__, attr, val)
714
715 def __instancecheck__(self, obj):
716 return self.__subclasscheck__(type(obj))
717
718 def __subclasscheck__(self, cls):
719 if self._special:
720 if not isinstance(cls, _GenericAlias):
721 return issubclass(cls, self.__origin__)
722 if cls._special:
723 return issubclass(cls.__origin__, self.__origin__)
724 raise TypeError("Subscripted generics cannot be used with"
725 " class and instance checks")
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700726
727
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000728class _VariadicGenericAlias(_GenericAlias, _root=True):
729 """Same as _GenericAlias above but for variadic aliases. Currently,
730 this is used only by special internal aliases: Tuple and Callable.
731 """
732 def __getitem__(self, params):
733 if self._name != 'Callable' or not self._special:
734 return self.__getitem_inner__(params)
735 if not isinstance(params, tuple) or len(params) != 2:
736 raise TypeError("Callable must be used as "
737 "Callable[[arg, ...], result].")
738 args, result = params
739 if args is Ellipsis:
740 params = (Ellipsis, result)
741 else:
742 if not isinstance(args, list):
743 raise TypeError(f"Callable[args, result]: args must be a list."
744 f" Got {args}")
745 params = (tuple(args), result)
746 return self.__getitem_inner__(params)
747
748 @_tp_cache
749 def __getitem_inner__(self, params):
750 if self.__origin__ is tuple and self._special:
751 if params == ():
752 return self.copy_with((_TypingEmpty,))
753 if not isinstance(params, tuple):
754 params = (params,)
755 if len(params) == 2 and params[1] is ...:
756 msg = "Tuple[t, ...]: t must be a type."
757 p = _type_check(params[0], msg)
758 return self.copy_with((p, _TypingEllipsis))
759 msg = "Tuple[t0, t1, ...]: each t must be a type."
760 params = tuple(_type_check(p, msg) for p in params)
761 return self.copy_with(params)
762 if self.__origin__ is collections.abc.Callable and self._special:
763 args, result = params
764 msg = "Callable[args, result]: result must be a type."
765 result = _type_check(result, msg)
766 if args is Ellipsis:
767 return self.copy_with((_TypingEllipsis, result))
768 msg = "Callable[[arg, ...], result]: each arg must be a type."
769 args = tuple(_type_check(arg, msg) for arg in args)
770 params = args + (result,)
771 return self.copy_with(params)
772 return super().__getitem__(params)
773
774
775class Generic:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700776 """Abstract base class for generic types.
777
Guido van Rossumb24569a2016-11-20 18:01:29 -0800778 A generic type is typically declared by inheriting from
779 this class parameterized with one or more type variables.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700780 For example, a generic mapping type might be defined as::
781
782 class Mapping(Generic[KT, VT]):
783 def __getitem__(self, key: KT) -> VT:
784 ...
785 # Etc.
786
787 This class can then be used as follows::
788
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700789 def lookup_name(mapping: Mapping[KT, VT], key: KT, default: VT) -> VT:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700790 try:
791 return mapping[key]
792 except KeyError:
793 return default
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700794 """
Guido van Rossumd70fe632015-08-05 12:11:06 +0200795 __slots__ = ()
796
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700797 def __new__(cls, *args, **kwds):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000798 if cls is Generic:
Guido van Rossum62fe1bb2016-10-29 16:05:26 -0700799 raise TypeError("Type Generic cannot be instantiated; "
800 "it can be used only as a base class")
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000801 return super().__new__(cls)
802
803 @_tp_cache
804 def __class_getitem__(cls, params):
805 if not isinstance(params, tuple):
806 params = (params,)
807 if not params and cls is not Tuple:
808 raise TypeError(
809 f"Parameter list to {cls.__qualname__}[...] cannot be empty")
810 msg = "Parameters to generic types must be types."
811 params = tuple(_type_check(p, msg) for p in params)
812 if cls is Generic:
813 # Generic can only be subscripted with unique type variables.
814 if not all(isinstance(p, TypeVar) for p in params):
815 raise TypeError(
816 "Parameters to Generic[...] must all be type variables")
817 if len(set(params)) != len(params):
818 raise TypeError(
819 "Parameters to Generic[...] must all be unique")
820 elif cls is _Protocol:
821 # _Protocol is internal at the moment, just skip the check
822 pass
823 else:
824 # Subscripting a regular Generic subclass.
825 _check_generic(cls, params)
826 return _GenericAlias(cls, params)
827
828 def __init_subclass__(cls, *args, **kwargs):
829 tvars = []
830 if '__orig_bases__' in cls.__dict__:
831 error = Generic in cls.__orig_bases__
832 else:
833 error = Generic in cls.__bases__ and cls.__name__ != '_Protocol'
834 if error:
835 raise TypeError("Cannot inherit from plain Generic")
836 if '__orig_bases__' in cls.__dict__:
837 tvars = _collect_type_vars(cls.__orig_bases__)
838 # Look for Generic[T1, ..., Tn].
839 # If found, tvars must be a subset of it.
840 # If not found, tvars is it.
841 # Also check for and reject plain Generic,
842 # and reject multiple Generic[...].
843 gvars = None
844 for base in cls.__orig_bases__:
845 if (isinstance(base, _GenericAlias) and
846 base.__origin__ is Generic):
847 if gvars is not None:
848 raise TypeError(
849 "Cannot inherit from Generic[...] multiple types.")
850 gvars = base.__parameters__
851 if gvars is None:
852 gvars = tvars
853 else:
854 tvarset = set(tvars)
855 gvarset = set(gvars)
856 if not tvarset <= gvarset:
857 s_vars = ', '.join(str(t) for t in tvars if t not in gvarset)
858 s_args = ', '.join(str(g) for g in gvars)
859 raise TypeError(f"Some type variables ({s_vars}) are"
860 f" not listed in Generic[{s_args}]")
861 tvars = gvars
862 cls.__parameters__ = tuple(tvars)
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700863
864
865class _TypingEmpty:
Guido van Rossumb24569a2016-11-20 18:01:29 -0800866 """Internal placeholder for () or []. Used by TupleMeta and CallableMeta
867 to allow empty list/tuple in specific places, without allowing them
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700868 to sneak in where prohibited.
869 """
870
871
872class _TypingEllipsis:
Guido van Rossumb24569a2016-11-20 18:01:29 -0800873 """Internal placeholder for ... (ellipsis)."""
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700874
875
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700876def cast(typ, val):
877 """Cast a value to a type.
878
879 This returns the value unchanged. To the type checker this
880 signals that the return value has the designated type, but at
881 runtime we intentionally don't check anything (we want this
882 to be as fast as possible).
883 """
884 return val
885
886
887def _get_defaults(func):
888 """Internal helper to extract the default arguments, by name."""
Guido van Rossum991d14f2016-11-09 13:12:51 -0800889 try:
890 code = func.__code__
891 except AttributeError:
892 # Some built-in functions don't have __code__, __defaults__, etc.
893 return {}
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700894 pos_count = code.co_argcount
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700895 arg_names = code.co_varnames
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700896 arg_names = arg_names[:pos_count]
897 defaults = func.__defaults__ or ()
898 kwdefaults = func.__kwdefaults__
899 res = dict(kwdefaults) if kwdefaults else {}
900 pos_offset = pos_count - len(defaults)
901 for name, value in zip(arg_names[pos_offset:], defaults):
902 assert name not in res
903 res[name] = value
904 return res
905
906
Ivan Levkivskyib692dc82017-02-13 22:50:14 +0100907_allowed_types = (types.FunctionType, types.BuiltinFunctionType,
908 types.MethodType, types.ModuleType,
Ivan Levkivskyif06e0212017-05-02 19:14:07 +0200909 WrapperDescriptorType, MethodWrapperType, MethodDescriptorType)
Ivan Levkivskyib692dc82017-02-13 22:50:14 +0100910
911
Guido van Rossum991d14f2016-11-09 13:12:51 -0800912def get_type_hints(obj, globalns=None, localns=None):
913 """Return type hints for an object.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700914
Guido van Rossum991d14f2016-11-09 13:12:51 -0800915 This is often the same as obj.__annotations__, but it handles
916 forward references encoded as string literals, and if necessary
917 adds Optional[t] if a default value equal to None is set.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700918
Guido van Rossum991d14f2016-11-09 13:12:51 -0800919 The argument may be a module, class, method, or function. The annotations
920 are returned as a dictionary. For classes, annotations include also
921 inherited members.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700922
Guido van Rossum991d14f2016-11-09 13:12:51 -0800923 TypeError is raised if the argument is not of a type that can contain
924 annotations, and an empty dictionary is returned if no annotations are
925 present.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700926
Guido van Rossum991d14f2016-11-09 13:12:51 -0800927 BEWARE -- the behavior of globalns and localns is counterintuitive
928 (unless you are familiar with how eval() and exec() work). The
929 search order is locals first, then globals.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700930
Guido van Rossum991d14f2016-11-09 13:12:51 -0800931 - If no dict arguments are passed, an attempt is made to use the
Łukasz Langaf350a262017-09-14 14:33:00 -0400932 globals from obj (or the respective module's globals for classes),
933 and these are also used as the locals. If the object does not appear
934 to have globals, an empty dictionary is used.
Guido van Rossum0a6976d2016-09-11 15:34:56 -0700935
Guido van Rossum991d14f2016-11-09 13:12:51 -0800936 - If one dict argument is passed, it is used for both globals and
937 locals.
Guido van Rossum0a6976d2016-09-11 15:34:56 -0700938
Guido van Rossum991d14f2016-11-09 13:12:51 -0800939 - If two dict arguments are passed, they specify globals and
940 locals, respectively.
941 """
Guido van Rossum0a6976d2016-09-11 15:34:56 -0700942
Guido van Rossum991d14f2016-11-09 13:12:51 -0800943 if getattr(obj, '__no_type_check__', None):
944 return {}
Guido van Rossum991d14f2016-11-09 13:12:51 -0800945 # Classes require a special treatment.
946 if isinstance(obj, type):
947 hints = {}
948 for base in reversed(obj.__mro__):
Łukasz Langaf350a262017-09-14 14:33:00 -0400949 if globalns is None:
950 base_globals = sys.modules[base.__module__].__dict__
951 else:
952 base_globals = globalns
Guido van Rossum991d14f2016-11-09 13:12:51 -0800953 ann = base.__dict__.get('__annotations__', {})
954 for name, value in ann.items():
955 if value is None:
956 value = type(None)
957 if isinstance(value, str):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000958 value = ForwardRef(value)
Łukasz Langaf350a262017-09-14 14:33:00 -0400959 value = _eval_type(value, base_globals, localns)
Guido van Rossum991d14f2016-11-09 13:12:51 -0800960 hints[name] = value
961 return hints
Łukasz Langaf350a262017-09-14 14:33:00 -0400962
963 if globalns is None:
964 if isinstance(obj, types.ModuleType):
965 globalns = obj.__dict__
966 else:
967 globalns = getattr(obj, '__globals__', {})
968 if localns is None:
969 localns = globalns
970 elif localns is None:
971 localns = globalns
Guido van Rossum991d14f2016-11-09 13:12:51 -0800972 hints = getattr(obj, '__annotations__', None)
973 if hints is None:
974 # Return empty annotations for something that _could_ have them.
Ivan Levkivskyib692dc82017-02-13 22:50:14 +0100975 if isinstance(obj, _allowed_types):
Guido van Rossum0a6976d2016-09-11 15:34:56 -0700976 return {}
Guido van Rossum991d14f2016-11-09 13:12:51 -0800977 else:
978 raise TypeError('{!r} is not a module, class, method, '
979 'or function.'.format(obj))
980 defaults = _get_defaults(obj)
981 hints = dict(hints)
982 for name, value in hints.items():
983 if value is None:
984 value = type(None)
985 if isinstance(value, str):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000986 value = ForwardRef(value)
Guido van Rossum991d14f2016-11-09 13:12:51 -0800987 value = _eval_type(value, globalns, localns)
988 if name in defaults and defaults[name] is None:
989 value = Optional[value]
990 hints[name] = value
991 return hints
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700992
993
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700994def no_type_check(arg):
995 """Decorator to indicate that annotations are not type hints.
996
997 The argument must be a class or function; if it is a class, it
Guido van Rossum0a6976d2016-09-11 15:34:56 -0700998 applies recursively to all methods and classes defined in that class
999 (but not to methods defined in its superclasses or subclasses).
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001000
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001001 This mutates the function(s) or class(es) in place.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001002 """
1003 if isinstance(arg, type):
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001004 arg_attrs = arg.__dict__.copy()
1005 for attr, val in arg.__dict__.items():
Ivan Levkivskyi65bc6202017-09-14 01:25:15 +02001006 if val in arg.__bases__ + (arg,):
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001007 arg_attrs.pop(attr)
1008 for obj in arg_attrs.values():
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001009 if isinstance(obj, types.FunctionType):
1010 obj.__no_type_check__ = True
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001011 if isinstance(obj, type):
1012 no_type_check(obj)
1013 try:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001014 arg.__no_type_check__ = True
Guido van Rossumd7adfe12017-01-22 17:43:53 -08001015 except TypeError: # built-in classes
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001016 pass
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001017 return arg
1018
1019
1020def no_type_check_decorator(decorator):
1021 """Decorator to give another decorator the @no_type_check effect.
1022
1023 This wraps the decorator with something that wraps the decorated
1024 function in @no_type_check.
1025 """
1026
1027 @functools.wraps(decorator)
1028 def wrapped_decorator(*args, **kwds):
1029 func = decorator(*args, **kwds)
1030 func = no_type_check(func)
1031 return func
1032
1033 return wrapped_decorator
1034
1035
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001036def _overload_dummy(*args, **kwds):
1037 """Helper for @overload to raise when called."""
1038 raise NotImplementedError(
1039 "You should not call an overloaded function. "
1040 "A series of @overload-decorated functions "
1041 "outside a stub module should always be followed "
1042 "by an implementation that is not @overload-ed.")
1043
1044
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001045def overload(func):
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001046 """Decorator for overloaded functions/methods.
1047
1048 In a stub file, place two or more stub definitions for the same
1049 function in a row, each decorated with @overload. For example:
1050
1051 @overload
1052 def utf8(value: None) -> None: ...
1053 @overload
1054 def utf8(value: bytes) -> bytes: ...
1055 @overload
1056 def utf8(value: str) -> bytes: ...
1057
1058 In a non-stub file (i.e. a regular .py file), do the same but
1059 follow it with an implementation. The implementation should *not*
1060 be decorated with @overload. For example:
1061
1062 @overload
1063 def utf8(value: None) -> None: ...
1064 @overload
1065 def utf8(value: bytes) -> bytes: ...
1066 @overload
1067 def utf8(value: str) -> bytes: ...
1068 def utf8(value):
1069 # implementation goes here
1070 """
1071 return _overload_dummy
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001072
1073
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001074class _ProtocolMeta(type):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001075 """Internal metaclass for _Protocol.
1076
1077 This exists so _Protocol classes can be generic without deriving
1078 from Generic.
1079 """
1080
Guido van Rossumd70fe632015-08-05 12:11:06 +02001081 def __instancecheck__(self, obj):
Guido van Rossumca4b2522016-11-19 10:32:41 -08001082 if _Protocol not in self.__bases__:
1083 return super().__instancecheck__(obj)
Guido van Rossumd70fe632015-08-05 12:11:06 +02001084 raise TypeError("Protocols cannot be used with isinstance().")
1085
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001086 def __subclasscheck__(self, cls):
1087 if not self._is_protocol:
1088 # No structural checks since this isn't a protocol.
1089 return NotImplemented
1090
1091 if self is _Protocol:
1092 # Every class is a subclass of the empty protocol.
1093 return True
1094
1095 # Find all attributes defined in the protocol.
1096 attrs = self._get_protocol_attrs()
1097
1098 for attr in attrs:
1099 if not any(attr in d.__dict__ for d in cls.__mro__):
1100 return False
1101 return True
1102
1103 def _get_protocol_attrs(self):
1104 # Get all Protocol base classes.
1105 protocol_bases = []
1106 for c in self.__mro__:
1107 if getattr(c, '_is_protocol', False) and c.__name__ != '_Protocol':
1108 protocol_bases.append(c)
1109
1110 # Get attributes included in protocol.
1111 attrs = set()
1112 for base in protocol_bases:
1113 for attr in base.__dict__.keys():
1114 # Include attributes not defined in any non-protocol bases.
1115 for c in self.__mro__:
1116 if (c is not base and attr in c.__dict__ and
1117 not getattr(c, '_is_protocol', False)):
1118 break
1119 else:
1120 if (not attr.startswith('_abc_') and
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001121 attr != '__abstractmethods__' and
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001122 attr != '__annotations__' and
1123 attr != '__weakref__' and
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001124 attr != '_is_protocol' and
Ivan Levkivskyi65bc6202017-09-14 01:25:15 +02001125 attr != '_gorg' and
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001126 attr != '__dict__' and
1127 attr != '__args__' and
1128 attr != '__slots__' and
1129 attr != '_get_protocol_attrs' and
1130 attr != '__next_in_mro__' and
1131 attr != '__parameters__' and
1132 attr != '__origin__' and
Guido van Rossum7ef22d62016-10-21 14:27:58 -07001133 attr != '__orig_bases__' and
Guido van Rossum1cea70f2016-05-18 08:35:00 -07001134 attr != '__extra__' and
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001135 attr != '__tree_hash__' and
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001136 attr != '__module__'):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001137 attrs.add(attr)
1138
1139 return attrs
1140
1141
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001142class _Protocol(Generic, metaclass=_ProtocolMeta):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001143 """Internal base class for protocol classes.
1144
Guido van Rossumb24569a2016-11-20 18:01:29 -08001145 This implements a simple-minded structural issubclass check
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001146 (similar but more general than the one-offs in collections.abc
1147 such as Hashable).
1148 """
1149
Guido van Rossumd70fe632015-08-05 12:11:06 +02001150 __slots__ = ()
1151
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001152 _is_protocol = True
1153
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001154 def __class_getitem__(cls, params):
1155 return super().__class_getitem__(params)
1156
1157
1158# Some unconstrained type variables. These are used by the container types.
1159# (These are not for export.)
1160T = TypeVar('T') # Any type.
1161KT = TypeVar('KT') # Key type.
1162VT = TypeVar('VT') # Value type.
1163T_co = TypeVar('T_co', covariant=True) # Any type covariant containers.
1164V_co = TypeVar('V_co', covariant=True) # Any type covariant containers.
1165VT_co = TypeVar('VT_co', covariant=True) # Value type covariant containers.
1166T_contra = TypeVar('T_contra', contravariant=True) # Ditto contravariant.
1167# Internal type variable used for Type[].
1168CT_co = TypeVar('CT_co', covariant=True, bound=type)
1169
1170# A useful type variable with constraints. This represents string types.
1171# (This one *is* for export!)
1172AnyStr = TypeVar('AnyStr', bytes, str)
1173
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001174
1175# Various ABCs mimicking those in collections.abc.
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001176def _alias(origin, params, inst=True):
1177 return _GenericAlias(origin, params, special=True, inst=inst)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001178
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001179Hashable = _alias(collections.abc.Hashable, ()) # Not generic.
1180Awaitable = _alias(collections.abc.Awaitable, T_co)
1181Coroutine = _alias(collections.abc.Coroutine, (T_co, T_contra, V_co))
1182AsyncIterable = _alias(collections.abc.AsyncIterable, T_co)
1183AsyncIterator = _alias(collections.abc.AsyncIterator, T_co)
1184Iterable = _alias(collections.abc.Iterable, T_co)
1185Iterator = _alias(collections.abc.Iterator, T_co)
1186Reversible = _alias(collections.abc.Reversible, T_co)
1187Sized = _alias(collections.abc.Sized, ()) # Not generic.
1188Container = _alias(collections.abc.Container, T_co)
1189Collection = _alias(collections.abc.Collection, T_co)
1190Callable = _VariadicGenericAlias(collections.abc.Callable, (), special=True)
1191Callable.__doc__ = \
1192 """Callable type; Callable[[int], str] is a function of (int) -> str.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001193
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001194 The subscription syntax must always be used with exactly two
1195 values: the argument list and the return type. The argument list
1196 must be a list of types or ellipsis; the return type must be a single type.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001197
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001198 There is no syntax to indicate optional or keyword arguments,
1199 such function types are rarely used as callback types.
1200 """
1201AbstractSet = _alias(collections.abc.Set, T_co)
1202MutableSet = _alias(collections.abc.MutableSet, T)
1203# NOTE: Mapping is only covariant in the value type.
1204Mapping = _alias(collections.abc.Mapping, (KT, VT_co))
1205MutableMapping = _alias(collections.abc.MutableMapping, (KT, VT))
1206Sequence = _alias(collections.abc.Sequence, T_co)
1207MutableSequence = _alias(collections.abc.MutableSequence, T)
1208ByteString = _alias(collections.abc.ByteString, ()) # Not generic
1209Tuple = _VariadicGenericAlias(tuple, (), inst=False, special=True)
1210Tuple.__doc__ = \
1211 """Tuple type; Tuple[X, Y] is the cross-product type of X and Y.
Guido van Rossum62fe1bb2016-10-29 16:05:26 -07001212
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001213 Example: Tuple[T1, T2] is a tuple of two elements corresponding
1214 to type variables T1 and T2. Tuple[int, float, str] is a tuple
1215 of an int, a float and a string.
Guido van Rossum62fe1bb2016-10-29 16:05:26 -07001216
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001217 To specify a variable-length tuple of homogeneous type, use Tuple[T, ...].
1218 """
1219List = _alias(list, T, inst=False)
1220Deque = _alias(collections.deque, T)
1221Set = _alias(set, T, inst=False)
1222FrozenSet = _alias(frozenset, T_co, inst=False)
1223MappingView = _alias(collections.abc.MappingView, T_co)
1224KeysView = _alias(collections.abc.KeysView, KT)
1225ItemsView = _alias(collections.abc.ItemsView, (KT, VT_co))
1226ValuesView = _alias(collections.abc.ValuesView, VT_co)
1227ContextManager = _alias(contextlib.AbstractContextManager, T_co)
1228AsyncContextManager = _alias(contextlib.AbstractAsyncContextManager, T_co)
1229Dict = _alias(dict, (KT, VT), inst=False)
1230DefaultDict = _alias(collections.defaultdict, (KT, VT))
1231Counter = _alias(collections.Counter, T)
1232ChainMap = _alias(collections.ChainMap, (KT, VT))
1233Generator = _alias(collections.abc.Generator, (T_co, T_contra, V_co))
1234AsyncGenerator = _alias(collections.abc.AsyncGenerator, (T_co, T_contra))
1235Type = _alias(type, CT_co, inst=False)
1236Type.__doc__ = \
1237 """A special construct usable to annotate class objects.
Guido van Rossum62fe1bb2016-10-29 16:05:26 -07001238
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001239 For example, suppose we have the following classes::
Guido van Rossum62fe1bb2016-10-29 16:05:26 -07001240
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001241 class User: ... # Abstract base for User classes
1242 class BasicUser(User): ...
1243 class ProUser(User): ...
1244 class TeamUser(User): ...
Guido van Rossumf17c2002015-12-03 17:31:24 -08001245
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001246 And a function that takes a class argument that's a subclass of
1247 User and returns an instance of the corresponding class::
Guido van Rossumf17c2002015-12-03 17:31:24 -08001248
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001249 U = TypeVar('U', bound=User)
1250 def new_user(user_class: Type[U]) -> U:
1251 user = user_class()
1252 # (Here we could write the user object to a database)
1253 return user
Guido van Rossumf17c2002015-12-03 17:31:24 -08001254
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001255 joe = new_user(BasicUser)
Guido van Rossumf17c2002015-12-03 17:31:24 -08001256
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001257 At this point the type checker knows that joe has type BasicUser.
1258 """
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001259
1260
1261class SupportsInt(_Protocol):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001262 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001263
1264 @abstractmethod
1265 def __int__(self) -> int:
1266 pass
1267
1268
1269class SupportsFloat(_Protocol):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001270 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001271
1272 @abstractmethod
1273 def __float__(self) -> float:
1274 pass
1275
1276
1277class SupportsComplex(_Protocol):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001278 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001279
1280 @abstractmethod
1281 def __complex__(self) -> complex:
1282 pass
1283
1284
1285class SupportsBytes(_Protocol):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001286 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001287
1288 @abstractmethod
1289 def __bytes__(self) -> bytes:
1290 pass
1291
1292
Guido van Rossumd70fe632015-08-05 12:11:06 +02001293class SupportsAbs(_Protocol[T_co]):
1294 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001295
1296 @abstractmethod
Guido van Rossumd70fe632015-08-05 12:11:06 +02001297 def __abs__(self) -> T_co:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001298 pass
1299
1300
Guido van Rossumd70fe632015-08-05 12:11:06 +02001301class SupportsRound(_Protocol[T_co]):
1302 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001303
1304 @abstractmethod
Guido van Rossumd70fe632015-08-05 12:11:06 +02001305 def __round__(self, ndigits: int = 0) -> T_co:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001306 pass
1307
1308
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001309def _make_nmtuple(name, types):
Guido van Rossum2f841442016-11-15 09:48:06 -08001310 msg = "NamedTuple('Name', [(f0, t0), (f1, t1), ...]); each t must be a type"
1311 types = [(n, _type_check(t, msg)) for n, t in types]
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001312 nm_tpl = collections.namedtuple(name, [n for n, t in types])
Guido van Rossum83ec3022017-01-17 20:43:28 -08001313 # Prior to PEP 526, only _field_types attribute was assigned.
1314 # Now, both __annotations__ and _field_types are used to maintain compatibility.
1315 nm_tpl.__annotations__ = nm_tpl._field_types = collections.OrderedDict(types)
Guido van Rossum557d1eb2015-11-19 08:16:31 -08001316 try:
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001317 nm_tpl.__module__ = sys._getframe(2).f_globals.get('__name__', '__main__')
Guido van Rossum557d1eb2015-11-19 08:16:31 -08001318 except (AttributeError, ValueError):
1319 pass
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001320 return nm_tpl
1321
1322
Ivan Levkivskyib692dc82017-02-13 22:50:14 +01001323# attributes prohibited to set in NamedTuple class syntax
1324_prohibited = ('__new__', '__init__', '__slots__', '__getnewargs__',
1325 '_fields', '_field_defaults', '_field_types',
Ivan Levkivskyif06e0212017-05-02 19:14:07 +02001326 '_make', '_replace', '_asdict', '_source')
Ivan Levkivskyib692dc82017-02-13 22:50:14 +01001327
1328_special = ('__module__', '__name__', '__qualname__', '__annotations__')
1329
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001330
Guido van Rossum2f841442016-11-15 09:48:06 -08001331class NamedTupleMeta(type):
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001332
Guido van Rossum2f841442016-11-15 09:48:06 -08001333 def __new__(cls, typename, bases, ns):
1334 if ns.get('_root', False):
1335 return super().__new__(cls, typename, bases, ns)
Guido van Rossum2f841442016-11-15 09:48:06 -08001336 types = ns.get('__annotations__', {})
Guido van Rossum3c268be2017-01-18 08:03:50 -08001337 nm_tpl = _make_nmtuple(typename, types.items())
1338 defaults = []
1339 defaults_dict = {}
1340 for field_name in types:
1341 if field_name in ns:
1342 default_value = ns[field_name]
1343 defaults.append(default_value)
1344 defaults_dict[field_name] = default_value
1345 elif defaults:
Guido van Rossumd7adfe12017-01-22 17:43:53 -08001346 raise TypeError("Non-default namedtuple field {field_name} cannot "
1347 "follow default field(s) {default_names}"
Guido van Rossum3c268be2017-01-18 08:03:50 -08001348 .format(field_name=field_name,
1349 default_names=', '.join(defaults_dict.keys())))
1350 nm_tpl.__new__.__defaults__ = tuple(defaults)
1351 nm_tpl._field_defaults = defaults_dict
Guido van Rossum95919c02017-01-22 17:47:20 -08001352 # update from user namespace without overriding special namedtuple attributes
1353 for key in ns:
Ivan Levkivskyib692dc82017-02-13 22:50:14 +01001354 if key in _prohibited:
1355 raise AttributeError("Cannot overwrite NamedTuple attribute " + key)
1356 elif key not in _special and key not in nm_tpl._fields:
Guido van Rossum95919c02017-01-22 17:47:20 -08001357 setattr(nm_tpl, key, ns[key])
Guido van Rossum3c268be2017-01-18 08:03:50 -08001358 return nm_tpl
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001359
Guido van Rossumd7adfe12017-01-22 17:43:53 -08001360
Guido van Rossum2f841442016-11-15 09:48:06 -08001361class NamedTuple(metaclass=NamedTupleMeta):
1362 """Typed version of namedtuple.
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001363
Guido van Rossum2f841442016-11-15 09:48:06 -08001364 Usage in Python versions >= 3.6::
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001365
Guido van Rossum2f841442016-11-15 09:48:06 -08001366 class Employee(NamedTuple):
1367 name: str
1368 id: int
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001369
Guido van Rossum2f841442016-11-15 09:48:06 -08001370 This is equivalent to::
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001371
Guido van Rossum2f841442016-11-15 09:48:06 -08001372 Employee = collections.namedtuple('Employee', ['name', 'id'])
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001373
Guido van Rossum83ec3022017-01-17 20:43:28 -08001374 The resulting class has extra __annotations__ and _field_types
1375 attributes, giving an ordered dict mapping field names to types.
1376 __annotations__ should be preferred, while _field_types
1377 is kept to maintain pre PEP 526 compatibility. (The field names
Guido van Rossum2f841442016-11-15 09:48:06 -08001378 are in the _fields attribute, which is part of the namedtuple
1379 API.) Alternative equivalent keyword syntax is also accepted::
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001380
Guido van Rossum2f841442016-11-15 09:48:06 -08001381 Employee = NamedTuple('Employee', name=str, id=int)
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001382
Guido van Rossum2f841442016-11-15 09:48:06 -08001383 In Python versions <= 3.5 use::
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001384
Guido van Rossum2f841442016-11-15 09:48:06 -08001385 Employee = NamedTuple('Employee', [('name', str), ('id', int)])
1386 """
1387 _root = True
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001388
Guido van Rossum2f841442016-11-15 09:48:06 -08001389 def __new__(self, typename, fields=None, **kwargs):
Guido van Rossum2f841442016-11-15 09:48:06 -08001390 if fields is None:
1391 fields = kwargs.items()
1392 elif kwargs:
1393 raise TypeError("Either list of fields or keywords"
1394 " can be provided to NamedTuple, not both")
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001395 return _make_nmtuple(typename, fields)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001396
1397
Guido van Rossum91185fe2016-06-08 11:19:11 -07001398def NewType(name, tp):
1399 """NewType creates simple unique types with almost zero
1400 runtime overhead. NewType(name, tp) is considered a subtype of tp
1401 by static type checkers. At runtime, NewType(name, tp) returns
1402 a dummy function that simply returns its argument. Usage::
1403
1404 UserId = NewType('UserId', int)
1405
1406 def name_by_id(user_id: UserId) -> str:
1407 ...
1408
1409 UserId('user') # Fails type check
1410
1411 name_by_id(42) # Fails type check
1412 name_by_id(UserId(42)) # OK
1413
1414 num = UserId(5) + 1 # type: int
1415 """
1416
1417 def new_type(x):
1418 return x
1419
1420 new_type.__name__ = name
1421 new_type.__supertype__ = tp
1422 return new_type
1423
1424
Guido van Rossum0e0563c2016-04-05 14:54:25 -07001425# Python-version-specific alias (Python 2: unicode; Python 3: str)
1426Text = str
1427
1428
Guido van Rossum91185fe2016-06-08 11:19:11 -07001429# Constant that's True when type checking, but False here.
1430TYPE_CHECKING = False
1431
1432
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001433class IO(Generic[AnyStr]):
1434 """Generic base class for TextIO and BinaryIO.
1435
1436 This is an abstract, generic version of the return of open().
1437
1438 NOTE: This does not distinguish between the different possible
1439 classes (text vs. binary, read vs. write vs. read/write,
1440 append-only, unbuffered). The TextIO and BinaryIO subclasses
1441 below capture the distinctions between text vs. binary, which is
1442 pervasive in the interface; however we currently do not offer a
1443 way to track the other distinctions in the type system.
1444 """
1445
Guido van Rossumd70fe632015-08-05 12:11:06 +02001446 __slots__ = ()
1447
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001448 @abstractproperty
1449 def mode(self) -> str:
1450 pass
1451
1452 @abstractproperty
1453 def name(self) -> str:
1454 pass
1455
1456 @abstractmethod
1457 def close(self) -> None:
1458 pass
1459
1460 @abstractmethod
1461 def closed(self) -> bool:
1462 pass
1463
1464 @abstractmethod
1465 def fileno(self) -> int:
1466 pass
1467
1468 @abstractmethod
1469 def flush(self) -> None:
1470 pass
1471
1472 @abstractmethod
1473 def isatty(self) -> bool:
1474 pass
1475
1476 @abstractmethod
1477 def read(self, n: int = -1) -> AnyStr:
1478 pass
1479
1480 @abstractmethod
1481 def readable(self) -> bool:
1482 pass
1483
1484 @abstractmethod
1485 def readline(self, limit: int = -1) -> AnyStr:
1486 pass
1487
1488 @abstractmethod
1489 def readlines(self, hint: int = -1) -> List[AnyStr]:
1490 pass
1491
1492 @abstractmethod
1493 def seek(self, offset: int, whence: int = 0) -> int:
1494 pass
1495
1496 @abstractmethod
1497 def seekable(self) -> bool:
1498 pass
1499
1500 @abstractmethod
1501 def tell(self) -> int:
1502 pass
1503
1504 @abstractmethod
1505 def truncate(self, size: int = None) -> int:
1506 pass
1507
1508 @abstractmethod
1509 def writable(self) -> bool:
1510 pass
1511
1512 @abstractmethod
1513 def write(self, s: AnyStr) -> int:
1514 pass
1515
1516 @abstractmethod
1517 def writelines(self, lines: List[AnyStr]) -> None:
1518 pass
1519
1520 @abstractmethod
1521 def __enter__(self) -> 'IO[AnyStr]':
1522 pass
1523
1524 @abstractmethod
1525 def __exit__(self, type, value, traceback) -> None:
1526 pass
1527
1528
1529class BinaryIO(IO[bytes]):
1530 """Typed version of the return of open() in binary mode."""
1531
Guido van Rossumd70fe632015-08-05 12:11:06 +02001532 __slots__ = ()
1533
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001534 @abstractmethod
1535 def write(self, s: Union[bytes, bytearray]) -> int:
1536 pass
1537
1538 @abstractmethod
1539 def __enter__(self) -> 'BinaryIO':
1540 pass
1541
1542
1543class TextIO(IO[str]):
1544 """Typed version of the return of open() in text mode."""
1545
Guido van Rossumd70fe632015-08-05 12:11:06 +02001546 __slots__ = ()
1547
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001548 @abstractproperty
1549 def buffer(self) -> BinaryIO:
1550 pass
1551
1552 @abstractproperty
1553 def encoding(self) -> str:
1554 pass
1555
1556 @abstractproperty
Guido van Rossum991d14f2016-11-09 13:12:51 -08001557 def errors(self) -> Optional[str]:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001558 pass
1559
1560 @abstractproperty
1561 def line_buffering(self) -> bool:
1562 pass
1563
1564 @abstractproperty
1565 def newlines(self) -> Any:
1566 pass
1567
1568 @abstractmethod
1569 def __enter__(self) -> 'TextIO':
1570 pass
1571
1572
1573class io:
1574 """Wrapper namespace for IO generic classes."""
1575
1576 __all__ = ['IO', 'TextIO', 'BinaryIO']
1577 IO = IO
1578 TextIO = TextIO
1579 BinaryIO = BinaryIO
1580
Guido van Rossumd7adfe12017-01-22 17:43:53 -08001581
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001582io.__name__ = __name__ + '.io'
1583sys.modules[io.__name__] = io
1584
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001585Pattern = _alias(stdlib_re.Pattern, AnyStr)
1586Match = _alias(stdlib_re.Match, AnyStr)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001587
1588class re:
1589 """Wrapper namespace for re type aliases."""
1590
1591 __all__ = ['Pattern', 'Match']
1592 Pattern = Pattern
1593 Match = Match
1594
Guido van Rossumd7adfe12017-01-22 17:43:53 -08001595
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001596re.__name__ = __name__ + '.re'
1597sys.modules[re.__name__] = re