blob: 7ca080402e28ac9181592bfd04bac8851d172352 [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',
98 'overload',
Guido van Rossum0e0563c2016-04-05 14:54:25 -070099 'Text',
Guido van Rossum91185fe2016-06-08 11:19:11 -0700100 'TYPE_CHECKING',
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700101]
102
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700103# The pseudo-submodules 're' and 'io' are part of the public
104# namespace, but excluded from __all__ because they might stomp on
105# legitimate imports of those modules.
106
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700107
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000108def _type_check(arg, msg):
109 """Check that the argument is a type, and return it (internal helper).
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700110
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000111 As a special case, accept None and return type(None) instead. Also wrap strings
112 into ForwardRef instances. Consider several corner cases, for example plain
113 special forms like Union are not valid, while Union[int, str] is OK, etc.
114 The msg argument is a human-readable error message, e.g::
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700115
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000116 "Union[arg, ...]: arg should be a type."
Guido van Rossum4cefe742016-09-27 15:20:12 -0700117
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000118 We append the repr() of the actual value (truncated to 100 chars).
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700119 """
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000120 if arg is None:
121 return type(None)
122 if isinstance(arg, str):
123 return ForwardRef(arg)
124 if (isinstance(arg, _GenericAlias) and
125 arg.__origin__ in (Generic, _Protocol, ClassVar)):
126 raise TypeError(f"{arg} is not valid as type argument")
127 if (isinstance(arg, _SpecialForm) and arg is not Any or
128 arg in (Generic, _Protocol)):
129 raise TypeError(f"Plain {arg} is not valid as type argument")
130 if isinstance(arg, (type, TypeVar, ForwardRef)):
131 return arg
132 if not callable(arg):
133 raise TypeError(f"{msg} Got {arg!r:.100}.")
134 return arg
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700135
136
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000137def _type_repr(obj):
138 """Return the repr() of an object, special-casing types (internal helper).
139
140 If obj is a type, we return a shorter version than the default
141 type.__repr__, based on the module and qualified name, which is
142 typically enough to uniquely identify a type. For everything
143 else, we fall back on repr(obj).
144 """
145 if isinstance(obj, type):
146 if obj.__module__ == 'builtins':
147 return obj.__qualname__
148 return f'{obj.__module__}.{obj.__qualname__}'
149 if obj is ...:
150 return('...')
151 if isinstance(obj, types.FunctionType):
152 return obj.__name__
153 return repr(obj)
154
155
156def _collect_type_vars(types):
157 """Collect all type variable contained in types in order of
158 first appearance (lexicographic order). For example::
159
160 _collect_type_vars((T, List[S, T])) == (T, S)
161 """
162 tvars = []
163 for t in types:
164 if isinstance(t, TypeVar) and t not in tvars:
165 tvars.append(t)
166 if isinstance(t, _GenericAlias) and not t._special:
167 tvars.extend([t for t in t.__parameters__ if t not in tvars])
168 return tuple(tvars)
169
170
171def _subs_tvars(tp, tvars, subs):
172 """Substitute type variables 'tvars' with substitutions 'subs'.
173 These two must have the same length.
174 """
175 if not isinstance(tp, _GenericAlias):
176 return tp
177 new_args = list(tp.__args__)
178 for a, arg in enumerate(tp.__args__):
179 if isinstance(arg, TypeVar):
180 for i, tvar in enumerate(tvars):
181 if arg == tvar:
182 new_args[a] = subs[i]
183 else:
184 new_args[a] = _subs_tvars(arg, tvars, subs)
185 if tp.__origin__ is Union:
186 return Union[tuple(new_args)]
187 return tp.copy_with(tuple(new_args))
188
189
190def _check_generic(cls, parameters):
191 """Check correct count for parameters of a generic cls (internal helper).
192 This gives a nice error message in case of count mismatch.
193 """
194 if not cls.__parameters__:
195 raise TypeError(f"{cls} is not a generic class")
196 alen = len(parameters)
197 elen = len(cls.__parameters__)
198 if alen != elen:
199 raise TypeError(f"Too {'many' if alen > elen else 'few'} parameters for {cls};"
200 f" actual {alen}, expected {elen}")
201
202
203def _remove_dups_flatten(parameters):
204 """An internal helper for Union creation and substitution: flatten Union's
205 among parameters, then remove duplicates and strict subclasses.
206 """
207 # Flatten out Union[Union[...], ...].
208 params = []
209 for p in parameters:
210 if isinstance(p, _GenericAlias) and p.__origin__ is Union:
211 params.extend(p.__args__)
212 elif isinstance(p, tuple) and len(p) > 0 and p[0] is Union:
213 params.extend(p[1:])
214 else:
215 params.append(p)
216 # Weed out strict duplicates, preserving the first of each occurrence.
217 all_params = set(params)
218 if len(all_params) < len(params):
219 new_params = []
220 for t in params:
221 if t in all_params:
222 new_params.append(t)
223 all_params.remove(t)
224 params = new_params
225 assert not all_params, all_params
226 # Weed out subclasses.
227 # E.g. Union[int, Employee, Manager] == Union[int, Employee].
228 # If object is present it will be sole survivor among proper classes.
229 # Never discard type variables.
230 # (In particular, Union[str, AnyStr] != AnyStr.)
231 all_params = set(params)
232 for t1 in params:
233 if not isinstance(t1, type):
234 continue
235 if any((isinstance(t2, type) or
236 isinstance(t2, _GenericAlias) and t2._special) and issubclass(t1, t2)
237 for t2 in all_params - {t1}):
238 all_params.remove(t1)
239 return tuple(t for t in params if t in all_params)
240
241
242_cleanups = []
243
244
245def _tp_cache(func):
246 """Internal wrapper caching __getitem__ of generic types with a fallback to
247 original function for non-hashable arguments.
248 """
249 cached = functools.lru_cache()(func)
250 _cleanups.append(cached.cache_clear)
251
252 @functools.wraps(func)
253 def inner(*args, **kwds):
254 try:
255 return cached(*args, **kwds)
256 except TypeError:
257 pass # All real errors (not unhashable args) are raised below.
258 return func(*args, **kwds)
259 return inner
260
261
262def _eval_type(t, globalns, localns):
263 """Evaluate all forward reverences in the given type t.
264 For use of globalns and localns see the docstring for get_type_hints().
265 """
266 if isinstance(t, ForwardRef):
267 return t._evaluate(globalns, localns)
268 if isinstance(t, _GenericAlias):
269 ev_args = tuple(_eval_type(a, globalns, localns) for a in t.__args__)
270 if ev_args == t.__args__:
271 return t
272 res = t.copy_with(ev_args)
273 res._special = t._special
274 return res
275 return t
276
277
278class _Final:
279 """Mixin to prohibit subclassing"""
Guido van Rossum4cefe742016-09-27 15:20:12 -0700280
Guido van Rossum83ec3022017-01-17 20:43:28 -0800281 __slots__ = ('__weakref__',)
Guido van Rossum4cefe742016-09-27 15:20:12 -0700282
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000283 def __init_subclass__(self, *args, **kwds):
284 if '_root' not in kwds:
285 raise TypeError("Cannot subclass special typing classes")
286
287
288class _SpecialForm(_Final, _root=True):
289 """Internal indicator of special typing constructs.
290 See _doc instance attribute for specific docs.
291 """
292
293 __slots__ = ('_name', '_doc')
294
295 def __getstate__(self):
296 return {'name': self._name, 'doc': self._doc}
297
298 def __setstate__(self, state):
299 self._name = state['name']
300 self._doc = state['doc']
Guido van Rossum4cefe742016-09-27 15:20:12 -0700301
302 def __new__(cls, *args, **kwds):
303 """Constructor.
304
305 This only exists to give a better error message in case
306 someone tries to subclass a special typing object (not a good idea).
307 """
308 if (len(args) == 3 and
309 isinstance(args[0], str) and
310 isinstance(args[1], tuple)):
311 # Close enough.
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000312 raise TypeError(f"Cannot subclass {cls!r}")
Guido van Rossumb47c9d22016-10-03 08:40:50 -0700313 return super().__new__(cls)
Guido van Rossum4cefe742016-09-27 15:20:12 -0700314
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000315 def __init__(self, name, doc):
316 self._name = name
317 self._doc = doc
Guido van Rossum4cefe742016-09-27 15:20:12 -0700318
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000319 def __eq__(self, other):
320 if not isinstance(other, _SpecialForm):
321 return NotImplemented
322 return self._name == other._name
323
324 def __hash__(self):
325 return hash((self._name,))
Guido van Rossum4cefe742016-09-27 15:20:12 -0700326
327 def __repr__(self):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000328 return 'typing.' + self._name
329
330 def __copy__(self):
331 return self # Special forms are immutable.
Guido van Rossum4cefe742016-09-27 15:20:12 -0700332
333 def __call__(self, *args, **kwds):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000334 raise TypeError(f"Cannot instantiate {self!r}")
335
336 def __instancecheck__(self, obj):
337 raise TypeError(f"{self} cannot be used with isinstance()")
338
339 def __subclasscheck__(self, cls):
340 raise TypeError(f"{self} cannot be used with issubclass()")
341
342 @_tp_cache
343 def __getitem__(self, parameters):
344 if self._name == 'ClassVar':
345 item = _type_check(parameters, 'ClassVar accepts only single type.')
346 return _GenericAlias(self, (item,))
347 if self._name == 'Union':
348 if parameters == ():
349 raise TypeError("Cannot take a Union of no types.")
350 if not isinstance(parameters, tuple):
351 parameters = (parameters,)
352 msg = "Union[arg, ...]: each arg must be a type."
353 parameters = tuple(_type_check(p, msg) for p in parameters)
354 parameters = _remove_dups_flatten(parameters)
355 if len(parameters) == 1:
356 return parameters[0]
357 return _GenericAlias(self, parameters)
358 if self._name == 'Optional':
359 arg = _type_check(parameters, "Optional[t] requires a single type.")
360 return Union[arg, type(None)]
361 raise TypeError(f"{self} is not subscriptable")
Guido van Rossum4cefe742016-09-27 15:20:12 -0700362
363
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000364Any = _SpecialForm('Any', doc=
365 """Special type indicating an unconstrained type.
Guido van Rossumb47c9d22016-10-03 08:40:50 -0700366
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000367 - Any is compatible with every type.
368 - Any assumed to have all methods.
369 - All values assumed to be instances of Any.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700370
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000371 Note that all the above statements are true from the point of view of
372 static type checkers. At runtime, Any should not be used with instance
373 or class checks.
374 """)
Guido van Rossumd70fe632015-08-05 12:11:06 +0200375
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000376NoReturn = _SpecialForm('NoReturn', doc=
377 """Special type indicating functions that never return.
378 Example::
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700379
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000380 from typing import NoReturn
381
382 def stop() -> NoReturn:
383 raise Exception('no way')
384
385 This type is invalid in other positions, e.g., ``List[NoReturn]``
386 will fail in static type checkers.
387 """)
388
389ClassVar = _SpecialForm('ClassVar', doc=
390 """Special type construct to mark class variables.
391
392 An annotation wrapped in ClassVar indicates that a given
393 attribute is intended to be used as a class variable and
394 should not be set on instances of that class. Usage::
395
396 class Starship:
397 stats: ClassVar[Dict[str, int]] = {} # class variable
398 damage: int = 10 # instance variable
399
400 ClassVar accepts only types and cannot be further subscribed.
401
402 Note that ClassVar is not a class itself, and should not
403 be used with isinstance() or issubclass().
404 """)
405
406Union = _SpecialForm('Union', doc=
407 """Union type; Union[X, Y] means either X or Y.
408
409 To define a union, use e.g. Union[int, str]. Details:
410 - The arguments must be types and there must be at least one.
411 - None as an argument is a special case and is replaced by
412 type(None).
413 - Unions of unions are flattened, e.g.::
414
415 Union[Union[int, str], float] == Union[int, str, float]
416
417 - Unions of a single argument vanish, e.g.::
418
419 Union[int] == int # The constructor actually returns int
420
421 - Redundant arguments are skipped, e.g.::
422
423 Union[int, str, int] == Union[int, str]
424
425 - When comparing unions, the argument order is ignored, e.g.::
426
427 Union[int, str] == Union[str, int]
428
429 - When two arguments have a subclass relationship, the least
430 derived argument is kept, e.g.::
431
432 class Employee: pass
433 class Manager(Employee): pass
434 Union[int, Employee, Manager] == Union[int, Employee]
435 Union[Manager, int, Employee] == Union[int, Employee]
436 Union[Employee, Manager] == Employee
437
438 - Similar for object::
439
440 Union[int, object] == object
441
442 - You cannot subclass or instantiate a union.
443 - You can use Optional[X] as a shorthand for Union[X, None].
444 """)
445
446Optional = _SpecialForm('Optional', doc=
447 """Optional type.
448
449 Optional[X] is equivalent to Union[X, None].
450 """)
Guido van Rossumb7dedc82016-10-29 12:44:29 -0700451
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700452
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000453class ForwardRef(_Final, _root=True):
Guido van Rossumb24569a2016-11-20 18:01:29 -0800454 """Internal wrapper to hold a forward reference."""
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700455
Guido van Rossum4cefe742016-09-27 15:20:12 -0700456 __slots__ = ('__forward_arg__', '__forward_code__',
Guido van Rossumc7b92952016-11-10 08:24:06 -0800457 '__forward_evaluated__', '__forward_value__')
Guido van Rossum4cefe742016-09-27 15:20:12 -0700458
459 def __init__(self, arg):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700460 if not isinstance(arg, str):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000461 raise TypeError(f"Forward reference must be a string -- got {arg!r}")
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700462 try:
463 code = compile(arg, '<string>', 'eval')
464 except SyntaxError:
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000465 raise SyntaxError(f"Forward reference must be an expression -- got {arg!r}")
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700466 self.__forward_arg__ = arg
467 self.__forward_code__ = code
468 self.__forward_evaluated__ = False
469 self.__forward_value__ = None
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700470
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000471 def _evaluate(self, globalns, localns):
Guido van Rossumdad17902016-11-10 08:29:18 -0800472 if not self.__forward_evaluated__ or localns is not globalns:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700473 if globalns is None and localns is None:
474 globalns = localns = {}
475 elif globalns is None:
476 globalns = localns
477 elif localns is None:
478 localns = globalns
479 self.__forward_value__ = _type_check(
480 eval(self.__forward_code__, globalns, localns),
481 "Forward references must evaluate to types.")
482 self.__forward_evaluated__ = True
483 return self.__forward_value__
484
Guido van Rossum4cefe742016-09-27 15:20:12 -0700485 def __eq__(self, other):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000486 if not isinstance(other, ForwardRef):
Guido van Rossum4cefe742016-09-27 15:20:12 -0700487 return NotImplemented
488 return (self.__forward_arg__ == other.__forward_arg__ and
Guido van Rossumc7b92952016-11-10 08:24:06 -0800489 self.__forward_value__ == other.__forward_value__)
Guido van Rossum4cefe742016-09-27 15:20:12 -0700490
491 def __hash__(self):
Guido van Rossumc7b92952016-11-10 08:24:06 -0800492 return hash((self.__forward_arg__, self.__forward_value__))
Guido van Rossum4cefe742016-09-27 15:20:12 -0700493
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700494 def __repr__(self):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000495 return f'ForwardRef({self.__forward_arg__!r})'
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700496
497
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000498class TypeVar(_Final, _root=True):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700499 """Type variable.
500
501 Usage::
502
503 T = TypeVar('T') # Can be anything
504 A = TypeVar('A', str, bytes) # Must be str or bytes
505
506 Type variables exist primarily for the benefit of static type
507 checkers. They serve as the parameters for generic types as well
508 as for generic function definitions. See class Generic for more
509 information on generic types. Generic functions work as follows:
510
Guido van Rossumb24569a2016-11-20 18:01:29 -0800511 def repeat(x: T, n: int) -> List[T]:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700512 '''Return a list containing n references to x.'''
513 return [x]*n
514
515 def longest(x: A, y: A) -> A:
516 '''Return the longest of two strings.'''
517 return x if len(x) >= len(y) else y
518
519 The latter example's signature is essentially the overloading
520 of (str, str) -> str and (bytes, bytes) -> bytes. Also note
521 that if the arguments are instances of some subclass of str,
522 the return type is still plain str.
523
Guido van Rossumb24569a2016-11-20 18:01:29 -0800524 At runtime, isinstance(x, T) and issubclass(C, T) will raise TypeError.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700525
Guido van Rossumefa798d2016-08-23 11:01:50 -0700526 Type variables defined with covariant=True or contravariant=True
527 can be used do declare covariant or contravariant generic types.
528 See PEP 484 for more details. By default generic types are invariant
529 in all type variables.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700530
531 Type variables can be introspected. e.g.:
532
533 T.__name__ == 'T'
534 T.__constraints__ == ()
535 T.__covariant__ == False
536 T.__contravariant__ = False
537 A.__constraints__ == (str, bytes)
538 """
539
Guido van Rossum4cefe742016-09-27 15:20:12 -0700540 __slots__ = ('__name__', '__bound__', '__constraints__',
541 '__covariant__', '__contravariant__')
542
543 def __init__(self, name, *constraints, bound=None,
Guido van Rossumd7adfe12017-01-22 17:43:53 -0800544 covariant=False, contravariant=False):
Guido van Rossum4cefe742016-09-27 15:20:12 -0700545 self.__name__ = name
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700546 if covariant and contravariant:
Guido van Rossumefa798d2016-08-23 11:01:50 -0700547 raise ValueError("Bivariant types are not supported.")
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700548 self.__covariant__ = bool(covariant)
549 self.__contravariant__ = bool(contravariant)
550 if constraints and bound is not None:
551 raise TypeError("Constraints cannot be combined with bound=...")
552 if constraints and len(constraints) == 1:
553 raise TypeError("A single constraint is not allowed")
554 msg = "TypeVar(name, constraint, ...): constraints must be types."
555 self.__constraints__ = tuple(_type_check(t, msg) for t in constraints)
556 if bound:
557 self.__bound__ = _type_check(bound, "Bound must be a type.")
558 else:
559 self.__bound__ = None
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700560
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000561 def __getstate__(self):
562 return {'name': self.__name__,
563 'bound': self.__bound__,
564 'constraints': self.__constraints__,
565 'co': self.__covariant__,
566 'contra': self.__contravariant__}
567
568 def __setstate__(self, state):
569 self.__name__ = state['name']
570 self.__bound__ = state['bound']
571 self.__constraints__ = state['constraints']
572 self.__covariant__ = state['co']
573 self.__contravariant__ = state['contra']
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700574
575 def __repr__(self):
576 if self.__covariant__:
577 prefix = '+'
578 elif self.__contravariant__:
579 prefix = '-'
580 else:
581 prefix = '~'
582 return prefix + self.__name__
583
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700584
Guido van Rossum83ec3022017-01-17 20:43:28 -0800585# Special typing constructs Union, Optional, Generic, Callable and Tuple
586# use three special attributes for internal bookkeeping of generic types:
587# * __parameters__ is a tuple of unique free type parameters of a generic
588# type, for example, Dict[T, T].__parameters__ == (T,);
589# * __origin__ keeps a reference to a type that was subscripted,
590# e.g., Union[T, int].__origin__ == Union;
591# * __args__ is a tuple of all arguments used in subscripting,
592# e.g., Dict[T, int].__args__ == (T, int).
593
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000594def _is_dunder(attr):
595 return attr.startswith('__') and attr.endswith('__')
Guido van Rossum83ec3022017-01-17 20:43:28 -0800596
Guido van Rossumb24569a2016-11-20 18:01:29 -0800597
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000598class _GenericAlias(_Final, _root=True):
599 """The central part of internal API.
600
601 This represents a generic version of type 'origin' with type arguments 'params'.
602 There are two kind of these aliases: user defined and special. The special ones
603 are wrappers around builtin collections and ABCs in collections.abc. These must
604 have 'name' always set. If 'inst' is False, then the alias can't be instantiated,
605 this is used by e.g. typing.List and typing.Dict.
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700606 """
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000607 def __init__(self, origin, params, *, inst=True, special=False, name=None):
608 self._inst = inst
609 self._special = special
610 if special and name is None:
611 orig_name = origin.__name__
612 name = orig_name[0].title() + orig_name[1:]
613 self._name = name
614 if not isinstance(params, tuple):
615 params = (params,)
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700616 self.__origin__ = origin
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700617 self.__args__ = tuple(... if a is _TypingEllipsis else
618 () if a is _TypingEmpty else
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000619 a for a in params)
620 self.__parameters__ = _collect_type_vars(params)
621 self.__slots__ = None # This is not documented.
622 if not name:
623 self.__module__ = origin.__module__
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700624
Guido van Rossum4cefe742016-09-27 15:20:12 -0700625 @_tp_cache
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700626 def __getitem__(self, params):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000627 if self.__origin__ in (Generic, _Protocol):
628 # Can't subscript Generic[...] or _Protocol[...].
629 raise TypeError(f"Cannot subscript already-subscripted {self}")
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700630 if not isinstance(params, tuple):
631 params = (params,)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700632 msg = "Parameters to generic types must be types."
633 params = tuple(_type_check(p, msg) for p in params)
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000634 _check_generic(self, params)
635 return _subs_tvars(self, self.__parameters__, params)
Ivan Levkivskyib692dc82017-02-13 22:50:14 +0100636
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000637 def copy_with(self, params):
638 # We don't copy self._special.
639 return _GenericAlias(self.__origin__, params, name=self._name, inst=self._inst)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700640
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000641 def __repr__(self):
642 if (self._name != 'Callable' or
643 len(self.__args__) == 2 and self.__args__[0] is Ellipsis):
644 if self._name:
645 name = 'typing.' + self._name
646 else:
647 name = _type_repr(self.__origin__)
648 if not self._special:
649 args = f'[{", ".join([_type_repr(a) for a in self.__args__])}]'
650 else:
651 args = ''
652 return (f'{name}{args}')
653 if self._special:
654 return 'typing.Callable'
655 return (f'typing.Callable'
656 f'[[{", ".join([_type_repr(a) for a in self.__args__[:-1]])}], '
657 f'{_type_repr(self.__args__[-1])}]')
658
659 def __eq__(self, other):
660 if not isinstance(other, _GenericAlias):
661 return NotImplemented
662 if self.__origin__ != other.__origin__:
Ivan Levkivskyib692dc82017-02-13 22:50:14 +0100663 return False
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000664 if self.__origin__ is Union and other.__origin__ is Union:
665 return frozenset(self.__args__) == frozenset(other.__args__)
666 return self.__args__ == other.__args__
Ivan Levkivskyib692dc82017-02-13 22:50:14 +0100667
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000668 def __hash__(self):
669 if self.__origin__ is Union:
670 return hash((Union, frozenset(self.__args__)))
671 return hash((self.__origin__, self.__args__))
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700672
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000673 def __call__(self, *args, **kwargs):
674 if not self._inst:
675 raise TypeError(f"Type {self._name} cannot be instantiated; "
676 f"use {self._name.lower()}() instead")
677 result = self.__origin__(*args, **kwargs)
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700678 try:
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000679 result.__orig_class__ = self
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700680 except AttributeError:
681 pass
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000682 return result
683
684 def __mro_entries__(self, bases):
685 if self._name: # generic version of an ABC or built-in class
686 res = []
687 if self.__origin__ not in bases:
688 res.append(self.__origin__)
689 i = bases.index(self)
690 if not any(isinstance(b, _GenericAlias) or issubclass(b, Generic)
691 for b in bases[i+1:]):
692 res.append(Generic)
693 return tuple(res)
694 if self.__origin__ is Generic:
695 i = bases.index(self)
696 for b in bases[i+1:]:
697 if isinstance(b, _GenericAlias) and b is not self:
698 return ()
699 return (self.__origin__,)
700
701 def __getattr__(self, attr):
702 # We are carefull for copy and pickle.
703 # Also for simplicity we just don't relay all dunder names
704 if '__origin__' in self.__dict__ and not _is_dunder(attr):
705 return getattr(self.__origin__, attr)
706 raise AttributeError(attr)
707
708 def __setattr__(self, attr, val):
709 if _is_dunder(attr) or attr in ('_name', '_inst', '_special'):
710 super().__setattr__(attr, val)
711 else:
712 setattr(self.__origin__, attr, val)
713
714 def __instancecheck__(self, obj):
715 return self.__subclasscheck__(type(obj))
716
717 def __subclasscheck__(self, cls):
718 if self._special:
719 if not isinstance(cls, _GenericAlias):
720 return issubclass(cls, self.__origin__)
721 if cls._special:
722 return issubclass(cls.__origin__, self.__origin__)
723 raise TypeError("Subscripted generics cannot be used with"
724 " class and instance checks")
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700725
726
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000727class _VariadicGenericAlias(_GenericAlias, _root=True):
728 """Same as _GenericAlias above but for variadic aliases. Currently,
729 this is used only by special internal aliases: Tuple and Callable.
730 """
731 def __getitem__(self, params):
732 if self._name != 'Callable' or not self._special:
733 return self.__getitem_inner__(params)
734 if not isinstance(params, tuple) or len(params) != 2:
735 raise TypeError("Callable must be used as "
736 "Callable[[arg, ...], result].")
737 args, result = params
738 if args is Ellipsis:
739 params = (Ellipsis, result)
740 else:
741 if not isinstance(args, list):
742 raise TypeError(f"Callable[args, result]: args must be a list."
743 f" Got {args}")
744 params = (tuple(args), result)
745 return self.__getitem_inner__(params)
746
747 @_tp_cache
748 def __getitem_inner__(self, params):
749 if self.__origin__ is tuple and self._special:
750 if params == ():
751 return self.copy_with((_TypingEmpty,))
752 if not isinstance(params, tuple):
753 params = (params,)
754 if len(params) == 2 and params[1] is ...:
755 msg = "Tuple[t, ...]: t must be a type."
756 p = _type_check(params[0], msg)
757 return self.copy_with((p, _TypingEllipsis))
758 msg = "Tuple[t0, t1, ...]: each t must be a type."
759 params = tuple(_type_check(p, msg) for p in params)
760 return self.copy_with(params)
761 if self.__origin__ is collections.abc.Callable and self._special:
762 args, result = params
763 msg = "Callable[args, result]: result must be a type."
764 result = _type_check(result, msg)
765 if args is Ellipsis:
766 return self.copy_with((_TypingEllipsis, result))
767 msg = "Callable[[arg, ...], result]: each arg must be a type."
768 args = tuple(_type_check(arg, msg) for arg in args)
769 params = args + (result,)
770 return self.copy_with(params)
771 return super().__getitem__(params)
772
773
774class Generic:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700775 """Abstract base class for generic types.
776
Guido van Rossumb24569a2016-11-20 18:01:29 -0800777 A generic type is typically declared by inheriting from
778 this class parameterized with one or more type variables.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700779 For example, a generic mapping type might be defined as::
780
781 class Mapping(Generic[KT, VT]):
782 def __getitem__(self, key: KT) -> VT:
783 ...
784 # Etc.
785
786 This class can then be used as follows::
787
Guido van Rossumbd5b9a02016-04-05 08:28:52 -0700788 def lookup_name(mapping: Mapping[KT, VT], key: KT, default: VT) -> VT:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700789 try:
790 return mapping[key]
791 except KeyError:
792 return default
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700793 """
Guido van Rossumd70fe632015-08-05 12:11:06 +0200794 __slots__ = ()
795
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700796 def __new__(cls, *args, **kwds):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000797 if cls is Generic:
Guido van Rossum62fe1bb2016-10-29 16:05:26 -0700798 raise TypeError("Type Generic cannot be instantiated; "
799 "it can be used only as a base class")
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000800 return super().__new__(cls)
801
802 @_tp_cache
803 def __class_getitem__(cls, params):
804 if not isinstance(params, tuple):
805 params = (params,)
806 if not params and cls is not Tuple:
807 raise TypeError(
808 f"Parameter list to {cls.__qualname__}[...] cannot be empty")
809 msg = "Parameters to generic types must be types."
810 params = tuple(_type_check(p, msg) for p in params)
811 if cls is Generic:
812 # Generic can only be subscripted with unique type variables.
813 if not all(isinstance(p, TypeVar) for p in params):
814 raise TypeError(
815 "Parameters to Generic[...] must all be type variables")
816 if len(set(params)) != len(params):
817 raise TypeError(
818 "Parameters to Generic[...] must all be unique")
819 elif cls is _Protocol:
820 # _Protocol is internal at the moment, just skip the check
821 pass
822 else:
823 # Subscripting a regular Generic subclass.
824 _check_generic(cls, params)
825 return _GenericAlias(cls, params)
826
827 def __init_subclass__(cls, *args, **kwargs):
828 tvars = []
829 if '__orig_bases__' in cls.__dict__:
830 error = Generic in cls.__orig_bases__
831 else:
832 error = Generic in cls.__bases__ and cls.__name__ != '_Protocol'
833 if error:
834 raise TypeError("Cannot inherit from plain Generic")
835 if '__orig_bases__' in cls.__dict__:
836 tvars = _collect_type_vars(cls.__orig_bases__)
837 # Look for Generic[T1, ..., Tn].
838 # If found, tvars must be a subset of it.
839 # If not found, tvars is it.
840 # Also check for and reject plain Generic,
841 # and reject multiple Generic[...].
842 gvars = None
843 for base in cls.__orig_bases__:
844 if (isinstance(base, _GenericAlias) and
845 base.__origin__ is Generic):
846 if gvars is not None:
847 raise TypeError(
848 "Cannot inherit from Generic[...] multiple types.")
849 gvars = base.__parameters__
850 if gvars is None:
851 gvars = tvars
852 else:
853 tvarset = set(tvars)
854 gvarset = set(gvars)
855 if not tvarset <= gvarset:
856 s_vars = ', '.join(str(t) for t in tvars if t not in gvarset)
857 s_args = ', '.join(str(g) for g in gvars)
858 raise TypeError(f"Some type variables ({s_vars}) are"
859 f" not listed in Generic[{s_args}]")
860 tvars = gvars
861 cls.__parameters__ = tuple(tvars)
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700862
863
864class _TypingEmpty:
Guido van Rossumb24569a2016-11-20 18:01:29 -0800865 """Internal placeholder for () or []. Used by TupleMeta and CallableMeta
866 to allow empty list/tuple in specific places, without allowing them
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700867 to sneak in where prohibited.
868 """
869
870
871class _TypingEllipsis:
Guido van Rossumb24569a2016-11-20 18:01:29 -0800872 """Internal placeholder for ... (ellipsis)."""
Guido van Rossum5fc25a82016-10-29 08:54:56 -0700873
874
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700875def cast(typ, val):
876 """Cast a value to a type.
877
878 This returns the value unchanged. To the type checker this
879 signals that the return value has the designated type, but at
880 runtime we intentionally don't check anything (we want this
881 to be as fast as possible).
882 """
883 return val
884
885
886def _get_defaults(func):
887 """Internal helper to extract the default arguments, by name."""
Guido van Rossum991d14f2016-11-09 13:12:51 -0800888 try:
889 code = func.__code__
890 except AttributeError:
891 # Some built-in functions don't have __code__, __defaults__, etc.
892 return {}
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700893 pos_count = code.co_argcount
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700894 arg_names = code.co_varnames
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700895 arg_names = arg_names[:pos_count]
896 defaults = func.__defaults__ or ()
897 kwdefaults = func.__kwdefaults__
898 res = dict(kwdefaults) if kwdefaults else {}
899 pos_offset = pos_count - len(defaults)
900 for name, value in zip(arg_names[pos_offset:], defaults):
901 assert name not in res
902 res[name] = value
903 return res
904
905
Ivan Levkivskyib692dc82017-02-13 22:50:14 +0100906_allowed_types = (types.FunctionType, types.BuiltinFunctionType,
907 types.MethodType, types.ModuleType,
Ivan Levkivskyif06e0212017-05-02 19:14:07 +0200908 WrapperDescriptorType, MethodWrapperType, MethodDescriptorType)
Ivan Levkivskyib692dc82017-02-13 22:50:14 +0100909
910
Guido van Rossum991d14f2016-11-09 13:12:51 -0800911def get_type_hints(obj, globalns=None, localns=None):
912 """Return type hints for an object.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700913
Guido van Rossum991d14f2016-11-09 13:12:51 -0800914 This is often the same as obj.__annotations__, but it handles
915 forward references encoded as string literals, and if necessary
916 adds Optional[t] if a default value equal to None is set.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700917
Guido van Rossum991d14f2016-11-09 13:12:51 -0800918 The argument may be a module, class, method, or function. The annotations
919 are returned as a dictionary. For classes, annotations include also
920 inherited members.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700921
Guido van Rossum991d14f2016-11-09 13:12:51 -0800922 TypeError is raised if the argument is not of a type that can contain
923 annotations, and an empty dictionary is returned if no annotations are
924 present.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700925
Guido van Rossum991d14f2016-11-09 13:12:51 -0800926 BEWARE -- the behavior of globalns and localns is counterintuitive
927 (unless you are familiar with how eval() and exec() work). The
928 search order is locals first, then globals.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700929
Guido van Rossum991d14f2016-11-09 13:12:51 -0800930 - If no dict arguments are passed, an attempt is made to use the
Łukasz Langaf350a262017-09-14 14:33:00 -0400931 globals from obj (or the respective module's globals for classes),
932 and these are also used as the locals. If the object does not appear
933 to have globals, an empty dictionary is used.
Guido van Rossum0a6976d2016-09-11 15:34:56 -0700934
Guido van Rossum991d14f2016-11-09 13:12:51 -0800935 - If one dict argument is passed, it is used for both globals and
936 locals.
Guido van Rossum0a6976d2016-09-11 15:34:56 -0700937
Guido van Rossum991d14f2016-11-09 13:12:51 -0800938 - If two dict arguments are passed, they specify globals and
939 locals, respectively.
940 """
Guido van Rossum0a6976d2016-09-11 15:34:56 -0700941
Guido van Rossum991d14f2016-11-09 13:12:51 -0800942 if getattr(obj, '__no_type_check__', None):
943 return {}
Guido van Rossum991d14f2016-11-09 13:12:51 -0800944 # Classes require a special treatment.
945 if isinstance(obj, type):
946 hints = {}
947 for base in reversed(obj.__mro__):
Łukasz Langaf350a262017-09-14 14:33:00 -0400948 if globalns is None:
949 base_globals = sys.modules[base.__module__].__dict__
950 else:
951 base_globals = globalns
Guido van Rossum991d14f2016-11-09 13:12:51 -0800952 ann = base.__dict__.get('__annotations__', {})
953 for name, value in ann.items():
954 if value is None:
955 value = type(None)
956 if isinstance(value, str):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000957 value = ForwardRef(value)
Łukasz Langaf350a262017-09-14 14:33:00 -0400958 value = _eval_type(value, base_globals, localns)
Guido van Rossum991d14f2016-11-09 13:12:51 -0800959 hints[name] = value
960 return hints
Łukasz Langaf350a262017-09-14 14:33:00 -0400961
962 if globalns is None:
963 if isinstance(obj, types.ModuleType):
964 globalns = obj.__dict__
965 else:
966 globalns = getattr(obj, '__globals__', {})
967 if localns is None:
968 localns = globalns
969 elif localns is None:
970 localns = globalns
Guido van Rossum991d14f2016-11-09 13:12:51 -0800971 hints = getattr(obj, '__annotations__', None)
972 if hints is None:
973 # Return empty annotations for something that _could_ have them.
Ivan Levkivskyib692dc82017-02-13 22:50:14 +0100974 if isinstance(obj, _allowed_types):
Guido van Rossum0a6976d2016-09-11 15:34:56 -0700975 return {}
Guido van Rossum991d14f2016-11-09 13:12:51 -0800976 else:
977 raise TypeError('{!r} is not a module, class, method, '
978 'or function.'.format(obj))
979 defaults = _get_defaults(obj)
980 hints = dict(hints)
981 for name, value in hints.items():
982 if value is None:
983 value = type(None)
984 if isinstance(value, str):
Ivan Levkivskyid911e402018-01-20 11:23:59 +0000985 value = ForwardRef(value)
Guido van Rossum991d14f2016-11-09 13:12:51 -0800986 value = _eval_type(value, globalns, localns)
987 if name in defaults and defaults[name] is None:
988 value = Optional[value]
989 hints[name] = value
990 return hints
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700991
992
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700993def no_type_check(arg):
994 """Decorator to indicate that annotations are not type hints.
995
996 The argument must be a class or function; if it is a class, it
Guido van Rossum0a6976d2016-09-11 15:34:56 -0700997 applies recursively to all methods and classes defined in that class
998 (but not to methods defined in its superclasses or subclasses).
Guido van Rossum46dbb7d2015-05-22 10:14:11 -0700999
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001000 This mutates the function(s) or class(es) in place.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001001 """
1002 if isinstance(arg, type):
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001003 arg_attrs = arg.__dict__.copy()
1004 for attr, val in arg.__dict__.items():
Ivan Levkivskyi65bc6202017-09-14 01:25:15 +02001005 if val in arg.__bases__ + (arg,):
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001006 arg_attrs.pop(attr)
1007 for obj in arg_attrs.values():
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001008 if isinstance(obj, types.FunctionType):
1009 obj.__no_type_check__ = True
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001010 if isinstance(obj, type):
1011 no_type_check(obj)
1012 try:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001013 arg.__no_type_check__ = True
Guido van Rossumd7adfe12017-01-22 17:43:53 -08001014 except TypeError: # built-in classes
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001015 pass
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001016 return arg
1017
1018
1019def no_type_check_decorator(decorator):
1020 """Decorator to give another decorator the @no_type_check effect.
1021
1022 This wraps the decorator with something that wraps the decorated
1023 function in @no_type_check.
1024 """
1025
1026 @functools.wraps(decorator)
1027 def wrapped_decorator(*args, **kwds):
1028 func = decorator(*args, **kwds)
1029 func = no_type_check(func)
1030 return func
1031
1032 return wrapped_decorator
1033
1034
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001035def _overload_dummy(*args, **kwds):
1036 """Helper for @overload to raise when called."""
1037 raise NotImplementedError(
1038 "You should not call an overloaded function. "
1039 "A series of @overload-decorated functions "
1040 "outside a stub module should always be followed "
1041 "by an implementation that is not @overload-ed.")
1042
1043
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001044def overload(func):
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001045 """Decorator for overloaded functions/methods.
1046
1047 In a stub file, place two or more stub definitions for the same
1048 function in a row, each decorated with @overload. For example:
1049
1050 @overload
1051 def utf8(value: None) -> None: ...
1052 @overload
1053 def utf8(value: bytes) -> bytes: ...
1054 @overload
1055 def utf8(value: str) -> bytes: ...
1056
1057 In a non-stub file (i.e. a regular .py file), do the same but
1058 follow it with an implementation. The implementation should *not*
1059 be decorated with @overload. For example:
1060
1061 @overload
1062 def utf8(value: None) -> None: ...
1063 @overload
1064 def utf8(value: bytes) -> bytes: ...
1065 @overload
1066 def utf8(value: str) -> bytes: ...
1067 def utf8(value):
1068 # implementation goes here
1069 """
1070 return _overload_dummy
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001071
1072
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001073class _ProtocolMeta(type):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001074 """Internal metaclass for _Protocol.
1075
1076 This exists so _Protocol classes can be generic without deriving
1077 from Generic.
1078 """
1079
Guido van Rossumd70fe632015-08-05 12:11:06 +02001080 def __instancecheck__(self, obj):
Guido van Rossumca4b2522016-11-19 10:32:41 -08001081 if _Protocol not in self.__bases__:
1082 return super().__instancecheck__(obj)
Guido van Rossumd70fe632015-08-05 12:11:06 +02001083 raise TypeError("Protocols cannot be used with isinstance().")
1084
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001085 def __subclasscheck__(self, cls):
1086 if not self._is_protocol:
1087 # No structural checks since this isn't a protocol.
1088 return NotImplemented
1089
1090 if self is _Protocol:
1091 # Every class is a subclass of the empty protocol.
1092 return True
1093
1094 # Find all attributes defined in the protocol.
1095 attrs = self._get_protocol_attrs()
1096
1097 for attr in attrs:
1098 if not any(attr in d.__dict__ for d in cls.__mro__):
1099 return False
1100 return True
1101
1102 def _get_protocol_attrs(self):
1103 # Get all Protocol base classes.
1104 protocol_bases = []
1105 for c in self.__mro__:
1106 if getattr(c, '_is_protocol', False) and c.__name__ != '_Protocol':
1107 protocol_bases.append(c)
1108
1109 # Get attributes included in protocol.
1110 attrs = set()
1111 for base in protocol_bases:
1112 for attr in base.__dict__.keys():
1113 # Include attributes not defined in any non-protocol bases.
1114 for c in self.__mro__:
1115 if (c is not base and attr in c.__dict__ and
1116 not getattr(c, '_is_protocol', False)):
1117 break
1118 else:
1119 if (not attr.startswith('_abc_') and
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001120 attr != '__abstractmethods__' and
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001121 attr != '__annotations__' and
1122 attr != '__weakref__' and
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001123 attr != '_is_protocol' and
Ivan Levkivskyi65bc6202017-09-14 01:25:15 +02001124 attr != '_gorg' and
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001125 attr != '__dict__' and
1126 attr != '__args__' and
1127 attr != '__slots__' and
1128 attr != '_get_protocol_attrs' and
1129 attr != '__next_in_mro__' and
1130 attr != '__parameters__' and
1131 attr != '__origin__' and
Guido van Rossum7ef22d62016-10-21 14:27:58 -07001132 attr != '__orig_bases__' and
Guido van Rossum1cea70f2016-05-18 08:35:00 -07001133 attr != '__extra__' and
Guido van Rossum5fc25a82016-10-29 08:54:56 -07001134 attr != '__tree_hash__' and
Guido van Rossumbd5b9a02016-04-05 08:28:52 -07001135 attr != '__module__'):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001136 attrs.add(attr)
1137
1138 return attrs
1139
1140
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001141class _Protocol(Generic, metaclass=_ProtocolMeta):
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001142 """Internal base class for protocol classes.
1143
Guido van Rossumb24569a2016-11-20 18:01:29 -08001144 This implements a simple-minded structural issubclass check
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001145 (similar but more general than the one-offs in collections.abc
1146 such as Hashable).
1147 """
1148
Guido van Rossumd70fe632015-08-05 12:11:06 +02001149 __slots__ = ()
1150
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001151 _is_protocol = True
1152
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001153 def __class_getitem__(cls, params):
1154 return super().__class_getitem__(params)
1155
1156
1157# Some unconstrained type variables. These are used by the container types.
1158# (These are not for export.)
1159T = TypeVar('T') # Any type.
1160KT = TypeVar('KT') # Key type.
1161VT = TypeVar('VT') # Value type.
1162T_co = TypeVar('T_co', covariant=True) # Any type covariant containers.
1163V_co = TypeVar('V_co', covariant=True) # Any type covariant containers.
1164VT_co = TypeVar('VT_co', covariant=True) # Value type covariant containers.
1165T_contra = TypeVar('T_contra', contravariant=True) # Ditto contravariant.
1166# Internal type variable used for Type[].
1167CT_co = TypeVar('CT_co', covariant=True, bound=type)
1168
1169# A useful type variable with constraints. This represents string types.
1170# (This one *is* for export!)
1171AnyStr = TypeVar('AnyStr', bytes, str)
1172
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001173
1174# Various ABCs mimicking those in collections.abc.
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001175def _alias(origin, params, inst=True):
1176 return _GenericAlias(origin, params, special=True, inst=inst)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001177
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001178Hashable = _alias(collections.abc.Hashable, ()) # Not generic.
1179Awaitable = _alias(collections.abc.Awaitable, T_co)
1180Coroutine = _alias(collections.abc.Coroutine, (T_co, T_contra, V_co))
1181AsyncIterable = _alias(collections.abc.AsyncIterable, T_co)
1182AsyncIterator = _alias(collections.abc.AsyncIterator, T_co)
1183Iterable = _alias(collections.abc.Iterable, T_co)
1184Iterator = _alias(collections.abc.Iterator, T_co)
1185Reversible = _alias(collections.abc.Reversible, T_co)
1186Sized = _alias(collections.abc.Sized, ()) # Not generic.
1187Container = _alias(collections.abc.Container, T_co)
1188Collection = _alias(collections.abc.Collection, T_co)
1189Callable = _VariadicGenericAlias(collections.abc.Callable, (), special=True)
1190Callable.__doc__ = \
1191 """Callable type; Callable[[int], str] is a function of (int) -> str.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001192
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001193 The subscription syntax must always be used with exactly two
1194 values: the argument list and the return type. The argument list
1195 must be a list of types or ellipsis; the return type must be a single type.
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001196
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001197 There is no syntax to indicate optional or keyword arguments,
1198 such function types are rarely used as callback types.
1199 """
1200AbstractSet = _alias(collections.abc.Set, T_co)
1201MutableSet = _alias(collections.abc.MutableSet, T)
1202# NOTE: Mapping is only covariant in the value type.
1203Mapping = _alias(collections.abc.Mapping, (KT, VT_co))
1204MutableMapping = _alias(collections.abc.MutableMapping, (KT, VT))
1205Sequence = _alias(collections.abc.Sequence, T_co)
1206MutableSequence = _alias(collections.abc.MutableSequence, T)
1207ByteString = _alias(collections.abc.ByteString, ()) # Not generic
1208Tuple = _VariadicGenericAlias(tuple, (), inst=False, special=True)
1209Tuple.__doc__ = \
1210 """Tuple type; Tuple[X, Y] is the cross-product type of X and Y.
Guido van Rossum62fe1bb2016-10-29 16:05:26 -07001211
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001212 Example: Tuple[T1, T2] is a tuple of two elements corresponding
1213 to type variables T1 and T2. Tuple[int, float, str] is a tuple
1214 of an int, a float and a string.
Guido van Rossum62fe1bb2016-10-29 16:05:26 -07001215
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001216 To specify a variable-length tuple of homogeneous type, use Tuple[T, ...].
1217 """
1218List = _alias(list, T, inst=False)
1219Deque = _alias(collections.deque, T)
1220Set = _alias(set, T, inst=False)
1221FrozenSet = _alias(frozenset, T_co, inst=False)
1222MappingView = _alias(collections.abc.MappingView, T_co)
1223KeysView = _alias(collections.abc.KeysView, KT)
1224ItemsView = _alias(collections.abc.ItemsView, (KT, VT_co))
1225ValuesView = _alias(collections.abc.ValuesView, VT_co)
1226ContextManager = _alias(contextlib.AbstractContextManager, T_co)
1227AsyncContextManager = _alias(contextlib.AbstractAsyncContextManager, T_co)
1228Dict = _alias(dict, (KT, VT), inst=False)
1229DefaultDict = _alias(collections.defaultdict, (KT, VT))
1230Counter = _alias(collections.Counter, T)
1231ChainMap = _alias(collections.ChainMap, (KT, VT))
1232Generator = _alias(collections.abc.Generator, (T_co, T_contra, V_co))
1233AsyncGenerator = _alias(collections.abc.AsyncGenerator, (T_co, T_contra))
1234Type = _alias(type, CT_co, inst=False)
1235Type.__doc__ = \
1236 """A special construct usable to annotate class objects.
Guido van Rossum62fe1bb2016-10-29 16:05:26 -07001237
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001238 For example, suppose we have the following classes::
Guido van Rossum62fe1bb2016-10-29 16:05:26 -07001239
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001240 class User: ... # Abstract base for User classes
1241 class BasicUser(User): ...
1242 class ProUser(User): ...
1243 class TeamUser(User): ...
Guido van Rossumf17c2002015-12-03 17:31:24 -08001244
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001245 And a function that takes a class argument that's a subclass of
1246 User and returns an instance of the corresponding class::
Guido van Rossumf17c2002015-12-03 17:31:24 -08001247
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001248 U = TypeVar('U', bound=User)
1249 def new_user(user_class: Type[U]) -> U:
1250 user = user_class()
1251 # (Here we could write the user object to a database)
1252 return user
Guido van Rossumf17c2002015-12-03 17:31:24 -08001253
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001254 joe = new_user(BasicUser)
Guido van Rossumf17c2002015-12-03 17:31:24 -08001255
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001256 At this point the type checker knows that joe has type BasicUser.
1257 """
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001258
1259
1260class SupportsInt(_Protocol):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001261 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001262
1263 @abstractmethod
1264 def __int__(self) -> int:
1265 pass
1266
1267
1268class SupportsFloat(_Protocol):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001269 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001270
1271 @abstractmethod
1272 def __float__(self) -> float:
1273 pass
1274
1275
1276class SupportsComplex(_Protocol):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001277 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001278
1279 @abstractmethod
1280 def __complex__(self) -> complex:
1281 pass
1282
1283
1284class SupportsBytes(_Protocol):
Guido van Rossumd70fe632015-08-05 12:11:06 +02001285 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001286
1287 @abstractmethod
1288 def __bytes__(self) -> bytes:
1289 pass
1290
1291
Guido van Rossumd70fe632015-08-05 12:11:06 +02001292class SupportsAbs(_Protocol[T_co]):
1293 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001294
1295 @abstractmethod
Guido van Rossumd70fe632015-08-05 12:11:06 +02001296 def __abs__(self) -> T_co:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001297 pass
1298
1299
Guido van Rossumd70fe632015-08-05 12:11:06 +02001300class SupportsRound(_Protocol[T_co]):
1301 __slots__ = ()
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001302
1303 @abstractmethod
Guido van Rossumd70fe632015-08-05 12:11:06 +02001304 def __round__(self, ndigits: int = 0) -> T_co:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001305 pass
1306
1307
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001308def _make_nmtuple(name, types):
Guido van Rossum2f841442016-11-15 09:48:06 -08001309 msg = "NamedTuple('Name', [(f0, t0), (f1, t1), ...]); each t must be a type"
1310 types = [(n, _type_check(t, msg)) for n, t in types]
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001311 nm_tpl = collections.namedtuple(name, [n for n, t in types])
Guido van Rossum83ec3022017-01-17 20:43:28 -08001312 # Prior to PEP 526, only _field_types attribute was assigned.
1313 # Now, both __annotations__ and _field_types are used to maintain compatibility.
1314 nm_tpl.__annotations__ = nm_tpl._field_types = collections.OrderedDict(types)
Guido van Rossum557d1eb2015-11-19 08:16:31 -08001315 try:
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001316 nm_tpl.__module__ = sys._getframe(2).f_globals.get('__name__', '__main__')
Guido van Rossum557d1eb2015-11-19 08:16:31 -08001317 except (AttributeError, ValueError):
1318 pass
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001319 return nm_tpl
1320
1321
Ivan Levkivskyib692dc82017-02-13 22:50:14 +01001322# attributes prohibited to set in NamedTuple class syntax
1323_prohibited = ('__new__', '__init__', '__slots__', '__getnewargs__',
1324 '_fields', '_field_defaults', '_field_types',
Ivan Levkivskyif06e0212017-05-02 19:14:07 +02001325 '_make', '_replace', '_asdict', '_source')
Ivan Levkivskyib692dc82017-02-13 22:50:14 +01001326
1327_special = ('__module__', '__name__', '__qualname__', '__annotations__')
1328
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001329
Guido van Rossum2f841442016-11-15 09:48:06 -08001330class NamedTupleMeta(type):
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001331
Guido van Rossum2f841442016-11-15 09:48:06 -08001332 def __new__(cls, typename, bases, ns):
1333 if ns.get('_root', False):
1334 return super().__new__(cls, typename, bases, ns)
Guido van Rossum2f841442016-11-15 09:48:06 -08001335 types = ns.get('__annotations__', {})
Guido van Rossum3c268be2017-01-18 08:03:50 -08001336 nm_tpl = _make_nmtuple(typename, types.items())
1337 defaults = []
1338 defaults_dict = {}
1339 for field_name in types:
1340 if field_name in ns:
1341 default_value = ns[field_name]
1342 defaults.append(default_value)
1343 defaults_dict[field_name] = default_value
1344 elif defaults:
Guido van Rossumd7adfe12017-01-22 17:43:53 -08001345 raise TypeError("Non-default namedtuple field {field_name} cannot "
1346 "follow default field(s) {default_names}"
Guido van Rossum3c268be2017-01-18 08:03:50 -08001347 .format(field_name=field_name,
1348 default_names=', '.join(defaults_dict.keys())))
1349 nm_tpl.__new__.__defaults__ = tuple(defaults)
1350 nm_tpl._field_defaults = defaults_dict
Guido van Rossum95919c02017-01-22 17:47:20 -08001351 # update from user namespace without overriding special namedtuple attributes
1352 for key in ns:
Ivan Levkivskyib692dc82017-02-13 22:50:14 +01001353 if key in _prohibited:
1354 raise AttributeError("Cannot overwrite NamedTuple attribute " + key)
1355 elif key not in _special and key not in nm_tpl._fields:
Guido van Rossum95919c02017-01-22 17:47:20 -08001356 setattr(nm_tpl, key, ns[key])
Guido van Rossum3c268be2017-01-18 08:03:50 -08001357 return nm_tpl
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001358
Guido van Rossumd7adfe12017-01-22 17:43:53 -08001359
Guido van Rossum2f841442016-11-15 09:48:06 -08001360class NamedTuple(metaclass=NamedTupleMeta):
1361 """Typed version of namedtuple.
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001362
Guido van Rossum2f841442016-11-15 09:48:06 -08001363 Usage in Python versions >= 3.6::
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001364
Guido van Rossum2f841442016-11-15 09:48:06 -08001365 class Employee(NamedTuple):
1366 name: str
1367 id: int
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001368
Guido van Rossum2f841442016-11-15 09:48:06 -08001369 This is equivalent to::
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001370
Guido van Rossum2f841442016-11-15 09:48:06 -08001371 Employee = collections.namedtuple('Employee', ['name', 'id'])
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001372
Guido van Rossum83ec3022017-01-17 20:43:28 -08001373 The resulting class has extra __annotations__ and _field_types
1374 attributes, giving an ordered dict mapping field names to types.
1375 __annotations__ should be preferred, while _field_types
1376 is kept to maintain pre PEP 526 compatibility. (The field names
Guido van Rossum2f841442016-11-15 09:48:06 -08001377 are in the _fields attribute, which is part of the namedtuple
1378 API.) Alternative equivalent keyword syntax is also accepted::
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001379
Guido van Rossum2f841442016-11-15 09:48:06 -08001380 Employee = NamedTuple('Employee', name=str, id=int)
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001381
Guido van Rossum2f841442016-11-15 09:48:06 -08001382 In Python versions <= 3.5 use::
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001383
Guido van Rossum2f841442016-11-15 09:48:06 -08001384 Employee = NamedTuple('Employee', [('name', str), ('id', int)])
1385 """
1386 _root = True
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001387
Guido van Rossum2f841442016-11-15 09:48:06 -08001388 def __new__(self, typename, fields=None, **kwargs):
Guido van Rossum2f841442016-11-15 09:48:06 -08001389 if fields is None:
1390 fields = kwargs.items()
1391 elif kwargs:
1392 raise TypeError("Either list of fields or keywords"
1393 " can be provided to NamedTuple, not both")
Guido van Rossum0a6976d2016-09-11 15:34:56 -07001394 return _make_nmtuple(typename, fields)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001395
1396
Guido van Rossum91185fe2016-06-08 11:19:11 -07001397def NewType(name, tp):
1398 """NewType creates simple unique types with almost zero
1399 runtime overhead. NewType(name, tp) is considered a subtype of tp
1400 by static type checkers. At runtime, NewType(name, tp) returns
1401 a dummy function that simply returns its argument. Usage::
1402
1403 UserId = NewType('UserId', int)
1404
1405 def name_by_id(user_id: UserId) -> str:
1406 ...
1407
1408 UserId('user') # Fails type check
1409
1410 name_by_id(42) # Fails type check
1411 name_by_id(UserId(42)) # OK
1412
1413 num = UserId(5) + 1 # type: int
1414 """
1415
1416 def new_type(x):
1417 return x
1418
1419 new_type.__name__ = name
1420 new_type.__supertype__ = tp
1421 return new_type
1422
1423
Guido van Rossum0e0563c2016-04-05 14:54:25 -07001424# Python-version-specific alias (Python 2: unicode; Python 3: str)
1425Text = str
1426
1427
Guido van Rossum91185fe2016-06-08 11:19:11 -07001428# Constant that's True when type checking, but False here.
1429TYPE_CHECKING = False
1430
1431
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001432class IO(Generic[AnyStr]):
1433 """Generic base class for TextIO and BinaryIO.
1434
1435 This is an abstract, generic version of the return of open().
1436
1437 NOTE: This does not distinguish between the different possible
1438 classes (text vs. binary, read vs. write vs. read/write,
1439 append-only, unbuffered). The TextIO and BinaryIO subclasses
1440 below capture the distinctions between text vs. binary, which is
1441 pervasive in the interface; however we currently do not offer a
1442 way to track the other distinctions in the type system.
1443 """
1444
Guido van Rossumd70fe632015-08-05 12:11:06 +02001445 __slots__ = ()
1446
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001447 @abstractproperty
1448 def mode(self) -> str:
1449 pass
1450
1451 @abstractproperty
1452 def name(self) -> str:
1453 pass
1454
1455 @abstractmethod
1456 def close(self) -> None:
1457 pass
1458
1459 @abstractmethod
1460 def closed(self) -> bool:
1461 pass
1462
1463 @abstractmethod
1464 def fileno(self) -> int:
1465 pass
1466
1467 @abstractmethod
1468 def flush(self) -> None:
1469 pass
1470
1471 @abstractmethod
1472 def isatty(self) -> bool:
1473 pass
1474
1475 @abstractmethod
1476 def read(self, n: int = -1) -> AnyStr:
1477 pass
1478
1479 @abstractmethod
1480 def readable(self) -> bool:
1481 pass
1482
1483 @abstractmethod
1484 def readline(self, limit: int = -1) -> AnyStr:
1485 pass
1486
1487 @abstractmethod
1488 def readlines(self, hint: int = -1) -> List[AnyStr]:
1489 pass
1490
1491 @abstractmethod
1492 def seek(self, offset: int, whence: int = 0) -> int:
1493 pass
1494
1495 @abstractmethod
1496 def seekable(self) -> bool:
1497 pass
1498
1499 @abstractmethod
1500 def tell(self) -> int:
1501 pass
1502
1503 @abstractmethod
1504 def truncate(self, size: int = None) -> int:
1505 pass
1506
1507 @abstractmethod
1508 def writable(self) -> bool:
1509 pass
1510
1511 @abstractmethod
1512 def write(self, s: AnyStr) -> int:
1513 pass
1514
1515 @abstractmethod
1516 def writelines(self, lines: List[AnyStr]) -> None:
1517 pass
1518
1519 @abstractmethod
1520 def __enter__(self) -> 'IO[AnyStr]':
1521 pass
1522
1523 @abstractmethod
1524 def __exit__(self, type, value, traceback) -> None:
1525 pass
1526
1527
1528class BinaryIO(IO[bytes]):
1529 """Typed version of the return of open() in binary mode."""
1530
Guido van Rossumd70fe632015-08-05 12:11:06 +02001531 __slots__ = ()
1532
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001533 @abstractmethod
1534 def write(self, s: Union[bytes, bytearray]) -> int:
1535 pass
1536
1537 @abstractmethod
1538 def __enter__(self) -> 'BinaryIO':
1539 pass
1540
1541
1542class TextIO(IO[str]):
1543 """Typed version of the return of open() in text mode."""
1544
Guido van Rossumd70fe632015-08-05 12:11:06 +02001545 __slots__ = ()
1546
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001547 @abstractproperty
1548 def buffer(self) -> BinaryIO:
1549 pass
1550
1551 @abstractproperty
1552 def encoding(self) -> str:
1553 pass
1554
1555 @abstractproperty
Guido van Rossum991d14f2016-11-09 13:12:51 -08001556 def errors(self) -> Optional[str]:
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001557 pass
1558
1559 @abstractproperty
1560 def line_buffering(self) -> bool:
1561 pass
1562
1563 @abstractproperty
1564 def newlines(self) -> Any:
1565 pass
1566
1567 @abstractmethod
1568 def __enter__(self) -> 'TextIO':
1569 pass
1570
1571
1572class io:
1573 """Wrapper namespace for IO generic classes."""
1574
1575 __all__ = ['IO', 'TextIO', 'BinaryIO']
1576 IO = IO
1577 TextIO = TextIO
1578 BinaryIO = BinaryIO
1579
Guido van Rossumd7adfe12017-01-22 17:43:53 -08001580
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001581io.__name__ = __name__ + '.io'
1582sys.modules[io.__name__] = io
1583
Ivan Levkivskyid911e402018-01-20 11:23:59 +00001584Pattern = _alias(stdlib_re.Pattern, AnyStr)
1585Match = _alias(stdlib_re.Match, AnyStr)
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001586
1587class re:
1588 """Wrapper namespace for re type aliases."""
1589
1590 __all__ = ['Pattern', 'Match']
1591 Pattern = Pattern
1592 Match = Match
1593
Guido van Rossumd7adfe12017-01-22 17:43:53 -08001594
Guido van Rossum46dbb7d2015-05-22 10:14:11 -07001595re.__name__ = __name__ + '.re'
1596sys.modules[re.__name__] = re