• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1"""
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 explicitly 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
21import abc
22from abc import abstractmethod, abstractproperty
23import collections
24import collections.abc
25import contextlib
26import functools
27import operator
28import re as stdlib_re  # Avoid confusion with the re we export.
29import sys
30import types
31from types import WrapperDescriptorType, MethodWrapperType, MethodDescriptorType
32
33# Please keep __all__ alphabetized within each category.
34__all__ = [
35    # Super-special typing primitives.
36    'Any',
37    'Callable',
38    'ClassVar',
39    'Generic',
40    'Optional',
41    'Tuple',
42    'Type',
43    'TypeVar',
44    'Union',
45
46    # ABCs (from collections.abc).
47    'AbstractSet',  # collections.abc.Set.
48    'ByteString',
49    'Container',
50    'ContextManager',
51    'Hashable',
52    'ItemsView',
53    'Iterable',
54    'Iterator',
55    'KeysView',
56    'Mapping',
57    'MappingView',
58    'MutableMapping',
59    'MutableSequence',
60    'MutableSet',
61    'Sequence',
62    'Sized',
63    'ValuesView',
64    'Awaitable',
65    'AsyncIterator',
66    'AsyncIterable',
67    'Coroutine',
68    'Collection',
69    'AsyncGenerator',
70    'AsyncContextManager',
71
72    # Structural checks, a.k.a. protocols.
73    'Reversible',
74    'SupportsAbs',
75    'SupportsBytes',
76    'SupportsComplex',
77    'SupportsFloat',
78    'SupportsInt',
79    'SupportsRound',
80
81    # Concrete collection types.
82    'Counter',
83    'Deque',
84    'Dict',
85    'DefaultDict',
86    'List',
87    'Set',
88    'FrozenSet',
89    'NamedTuple',  # Not really a type.
90    'Generator',
91
92    # One-off things.
93    'AnyStr',
94    'cast',
95    'get_type_hints',
96    'NewType',
97    'no_type_check',
98    'no_type_check_decorator',
99    'NoReturn',
100    'overload',
101    'Text',
102    'TYPE_CHECKING',
103]
104
105# The pseudo-submodules 're' and 'io' are part of the public
106# namespace, but excluded from __all__ because they might stomp on
107# legitimate imports of those modules.
108
109
110def _type_check(arg, msg, is_argument=True):
111    """Check that the argument is a type, and return it (internal helper).
112
113    As a special case, accept None and return type(None) instead. Also wrap strings
114    into ForwardRef instances. Consider several corner cases, for example plain
115    special forms like Union are not valid, while Union[int, str] is OK, etc.
116    The msg argument is a human-readable error message, e.g::
117
118        "Union[arg, ...]: arg should be a type."
119
120    We append the repr() of the actual value (truncated to 100 chars).
121    """
122    invalid_generic_forms = (Generic, _Protocol)
123    if is_argument:
124        invalid_generic_forms = invalid_generic_forms + (ClassVar, )
125
126    if arg is None:
127        return type(None)
128    if isinstance(arg, str):
129        return ForwardRef(arg)
130    if (isinstance(arg, _GenericAlias) and
131            arg.__origin__ in invalid_generic_forms):
132        raise TypeError(f"{arg} is not valid as type argument")
133    if (isinstance(arg, _SpecialForm) and arg not in (Any, NoReturn) or
134            arg in (Generic, _Protocol)):
135        raise TypeError(f"Plain {arg} is not valid as type argument")
136    if isinstance(arg, (type, TypeVar, ForwardRef)):
137        return arg
138    if not callable(arg):
139        raise TypeError(f"{msg} Got {arg!r:.100}.")
140    return arg
141
142
143def _type_repr(obj):
144    """Return the repr() of an object, special-casing types (internal helper).
145
146    If obj is a type, we return a shorter version than the default
147    type.__repr__, based on the module and qualified name, which is
148    typically enough to uniquely identify a type.  For everything
149    else, we fall back on repr(obj).
150    """
151    if isinstance(obj, type):
152        if obj.__module__ == 'builtins':
153            return obj.__qualname__
154        return f'{obj.__module__}.{obj.__qualname__}'
155    if obj is ...:
156        return('...')
157    if isinstance(obj, types.FunctionType):
158        return obj.__name__
159    return repr(obj)
160
161
162def _collect_type_vars(types):
163    """Collect all type variable contained in types in order of
164    first appearance (lexicographic order). For example::
165
166        _collect_type_vars((T, List[S, T])) == (T, S)
167    """
168    tvars = []
169    for t in types:
170        if isinstance(t, TypeVar) and t not in tvars:
171            tvars.append(t)
172        if isinstance(t, _GenericAlias) and not t._special:
173            tvars.extend([t for t in t.__parameters__ if t not in tvars])
174    return tuple(tvars)
175
176
177def _subs_tvars(tp, tvars, subs):
178    """Substitute type variables 'tvars' with substitutions 'subs'.
179    These two must have the same length.
180    """
181    if not isinstance(tp, _GenericAlias):
182        return tp
183    new_args = list(tp.__args__)
184    for a, arg in enumerate(tp.__args__):
185        if isinstance(arg, TypeVar):
186            for i, tvar in enumerate(tvars):
187                if arg == tvar:
188                    new_args[a] = subs[i]
189        else:
190            new_args[a] = _subs_tvars(arg, tvars, subs)
191    if tp.__origin__ is Union:
192        return Union[tuple(new_args)]
193    return tp.copy_with(tuple(new_args))
194
195
196def _check_generic(cls, parameters):
197    """Check correct count for parameters of a generic cls (internal helper).
198    This gives a nice error message in case of count mismatch.
199    """
200    if not cls.__parameters__:
201        raise TypeError(f"{cls} is not a generic class")
202    alen = len(parameters)
203    elen = len(cls.__parameters__)
204    if alen != elen:
205        raise TypeError(f"Too {'many' if alen > elen else 'few'} parameters for {cls};"
206                        f" actual {alen}, expected {elen}")
207
208
209def _remove_dups_flatten(parameters):
210    """An internal helper for Union creation and substitution: flatten Unions
211    among parameters, then remove duplicates.
212    """
213    # Flatten out Union[Union[...], ...].
214    params = []
215    for p in parameters:
216        if isinstance(p, _GenericAlias) and p.__origin__ is Union:
217            params.extend(p.__args__)
218        elif isinstance(p, tuple) and len(p) > 0 and p[0] is Union:
219            params.extend(p[1:])
220        else:
221            params.append(p)
222    # Weed out strict duplicates, preserving the first of each occurrence.
223    all_params = set(params)
224    if len(all_params) < len(params):
225        new_params = []
226        for t in params:
227            if t in all_params:
228                new_params.append(t)
229                all_params.remove(t)
230        params = new_params
231        assert not all_params, all_params
232    return tuple(params)
233
234
235_cleanups = []
236
237
238def _tp_cache(func):
239    """Internal wrapper caching __getitem__ of generic types with a fallback to
240    original function for non-hashable arguments.
241    """
242    cached = functools.lru_cache()(func)
243    _cleanups.append(cached.cache_clear)
244
245    @functools.wraps(func)
246    def inner(*args, **kwds):
247        try:
248            return cached(*args, **kwds)
249        except TypeError:
250            pass  # All real errors (not unhashable args) are raised below.
251        return func(*args, **kwds)
252    return inner
253
254
255def _eval_type(t, globalns, localns):
256    """Evaluate all forward reverences in the given type t.
257    For use of globalns and localns see the docstring for get_type_hints().
258    """
259    if isinstance(t, ForwardRef):
260        return t._evaluate(globalns, localns)
261    if isinstance(t, _GenericAlias):
262        ev_args = tuple(_eval_type(a, globalns, localns) for a in t.__args__)
263        if ev_args == t.__args__:
264            return t
265        res = t.copy_with(ev_args)
266        res._special = t._special
267        return res
268    return t
269
270
271class _Final:
272    """Mixin to prohibit subclassing"""
273
274    __slots__ = ('__weakref__',)
275
276    def __init_subclass__(self, *args, **kwds):
277        if '_root' not in kwds:
278            raise TypeError("Cannot subclass special typing classes")
279
280class _Immutable:
281    """Mixin to indicate that object should not be copied."""
282
283    def __copy__(self):
284        return self
285
286    def __deepcopy__(self, memo):
287        return self
288
289
290class _SpecialForm(_Final, _Immutable, _root=True):
291    """Internal indicator of special typing constructs.
292    See _doc instance attribute for specific docs.
293    """
294
295    __slots__ = ('_name', '_doc')
296
297    def __new__(cls, *args, **kwds):
298        """Constructor.
299
300        This only exists to give a better error message in case
301        someone tries to subclass a special typing object (not a good idea).
302        """
303        if (len(args) == 3 and
304                isinstance(args[0], str) and
305                isinstance(args[1], tuple)):
306            # Close enough.
307            raise TypeError(f"Cannot subclass {cls!r}")
308        return super().__new__(cls)
309
310    def __init__(self, name, doc):
311        self._name = name
312        self._doc = doc
313
314    def __eq__(self, other):
315        if not isinstance(other, _SpecialForm):
316            return NotImplemented
317        return self._name == other._name
318
319    def __hash__(self):
320        return hash((self._name,))
321
322    def __repr__(self):
323        return 'typing.' + self._name
324
325    def __reduce__(self):
326        return self._name
327
328    def __call__(self, *args, **kwds):
329        raise TypeError(f"Cannot instantiate {self!r}")
330
331    def __instancecheck__(self, obj):
332        raise TypeError(f"{self} cannot be used with isinstance()")
333
334    def __subclasscheck__(self, cls):
335        raise TypeError(f"{self} cannot be used with issubclass()")
336
337    @_tp_cache
338    def __getitem__(self, parameters):
339        if self._name == 'ClassVar':
340            item = _type_check(parameters, 'ClassVar accepts only single type.')
341            return _GenericAlias(self, (item,))
342        if self._name == 'Union':
343            if parameters == ():
344                raise TypeError("Cannot take a Union of no types.")
345            if not isinstance(parameters, tuple):
346                parameters = (parameters,)
347            msg = "Union[arg, ...]: each arg must be a type."
348            parameters = tuple(_type_check(p, msg) for p in parameters)
349            parameters = _remove_dups_flatten(parameters)
350            if len(parameters) == 1:
351                return parameters[0]
352            return _GenericAlias(self, parameters)
353        if self._name == 'Optional':
354            arg = _type_check(parameters, "Optional[t] requires a single type.")
355            return Union[arg, type(None)]
356        raise TypeError(f"{self} is not subscriptable")
357
358
359Any = _SpecialForm('Any', doc=
360    """Special type indicating an unconstrained type.
361
362    - Any is compatible with every type.
363    - Any assumed to have all methods.
364    - All values assumed to be instances of Any.
365
366    Note that all the above statements are true from the point of view of
367    static type checkers. At runtime, Any should not be used with instance
368    or class checks.
369    """)
370
371NoReturn = _SpecialForm('NoReturn', doc=
372    """Special type indicating functions that never return.
373    Example::
374
375      from typing import NoReturn
376
377      def stop() -> NoReturn:
378          raise Exception('no way')
379
380    This type is invalid in other positions, e.g., ``List[NoReturn]``
381    will fail in static type checkers.
382    """)
383
384ClassVar = _SpecialForm('ClassVar', doc=
385    """Special type construct to mark class variables.
386
387    An annotation wrapped in ClassVar indicates that a given
388    attribute is intended to be used as a class variable and
389    should not be set on instances of that class. Usage::
390
391      class Starship:
392          stats: ClassVar[Dict[str, int]] = {} # class variable
393          damage: int = 10                     # instance variable
394
395    ClassVar accepts only types and cannot be further subscribed.
396
397    Note that ClassVar is not a class itself, and should not
398    be used with isinstance() or issubclass().
399    """)
400
401Union = _SpecialForm('Union', doc=
402    """Union type; Union[X, Y] means either X or Y.
403
404    To define a union, use e.g. Union[int, str].  Details:
405    - The arguments must be types and there must be at least one.
406    - None as an argument is a special case and is replaced by
407      type(None).
408    - Unions of unions are flattened, e.g.::
409
410        Union[Union[int, str], float] == Union[int, str, float]
411
412    - Unions of a single argument vanish, e.g.::
413
414        Union[int] == int  # The constructor actually returns int
415
416    - Redundant arguments are skipped, e.g.::
417
418        Union[int, str, int] == Union[int, str]
419
420    - When comparing unions, the argument order is ignored, e.g.::
421
422        Union[int, str] == Union[str, int]
423
424    - You cannot subclass or instantiate a union.
425    - You can use Optional[X] as a shorthand for Union[X, None].
426    """)
427
428Optional = _SpecialForm('Optional', doc=
429    """Optional type.
430
431    Optional[X] is equivalent to Union[X, None].
432    """)
433
434
435class ForwardRef(_Final, _root=True):
436    """Internal wrapper to hold a forward reference."""
437
438    __slots__ = ('__forward_arg__', '__forward_code__',
439                 '__forward_evaluated__', '__forward_value__',
440                 '__forward_is_argument__')
441
442    def __init__(self, arg, is_argument=True):
443        if not isinstance(arg, str):
444            raise TypeError(f"Forward reference must be a string -- got {arg!r}")
445        try:
446            code = compile(arg, '<string>', 'eval')
447        except SyntaxError:
448            raise SyntaxError(f"Forward reference must be an expression -- got {arg!r}")
449        self.__forward_arg__ = arg
450        self.__forward_code__ = code
451        self.__forward_evaluated__ = False
452        self.__forward_value__ = None
453        self.__forward_is_argument__ = is_argument
454
455    def _evaluate(self, globalns, localns):
456        if not self.__forward_evaluated__ or localns is not globalns:
457            if globalns is None and localns is None:
458                globalns = localns = {}
459            elif globalns is None:
460                globalns = localns
461            elif localns is None:
462                localns = globalns
463            self.__forward_value__ = _type_check(
464                eval(self.__forward_code__, globalns, localns),
465                "Forward references must evaluate to types.",
466                is_argument=self.__forward_is_argument__)
467            self.__forward_evaluated__ = True
468        return self.__forward_value__
469
470    def __eq__(self, other):
471        if not isinstance(other, ForwardRef):
472            return NotImplemented
473        return (self.__forward_arg__ == other.__forward_arg__ and
474                self.__forward_value__ == other.__forward_value__)
475
476    def __hash__(self):
477        return hash((self.__forward_arg__, self.__forward_value__))
478
479    def __repr__(self):
480        return f'ForwardRef({self.__forward_arg__!r})'
481
482
483class TypeVar(_Final, _Immutable, _root=True):
484    """Type variable.
485
486    Usage::
487
488      T = TypeVar('T')  # Can be anything
489      A = TypeVar('A', str, bytes)  # Must be str or bytes
490
491    Type variables exist primarily for the benefit of static type
492    checkers.  They serve as the parameters for generic types as well
493    as for generic function definitions.  See class Generic for more
494    information on generic types.  Generic functions work as follows:
495
496      def repeat(x: T, n: int) -> List[T]:
497          '''Return a list containing n references to x.'''
498          return [x]*n
499
500      def longest(x: A, y: A) -> A:
501          '''Return the longest of two strings.'''
502          return x if len(x) >= len(y) else y
503
504    The latter example's signature is essentially the overloading
505    of (str, str) -> str and (bytes, bytes) -> bytes.  Also note
506    that if the arguments are instances of some subclass of str,
507    the return type is still plain str.
508
509    At runtime, isinstance(x, T) and issubclass(C, T) will raise TypeError.
510
511    Type variables defined with covariant=True or contravariant=True
512    can be used to declare covariant or contravariant generic types.
513    See PEP 484 for more details. By default generic types are invariant
514    in all type variables.
515
516    Type variables can be introspected. e.g.:
517
518      T.__name__ == 'T'
519      T.__constraints__ == ()
520      T.__covariant__ == False
521      T.__contravariant__ = False
522      A.__constraints__ == (str, bytes)
523
524    Note that only type variables defined in global scope can be pickled.
525    """
526
527    __slots__ = ('__name__', '__bound__', '__constraints__',
528                 '__covariant__', '__contravariant__')
529
530    def __init__(self, name, *constraints, bound=None,
531                 covariant=False, contravariant=False):
532        self.__name__ = name
533        if covariant and contravariant:
534            raise ValueError("Bivariant types are not supported.")
535        self.__covariant__ = bool(covariant)
536        self.__contravariant__ = bool(contravariant)
537        if constraints and bound is not None:
538            raise TypeError("Constraints cannot be combined with bound=...")
539        if constraints and len(constraints) == 1:
540            raise TypeError("A single constraint is not allowed")
541        msg = "TypeVar(name, constraint, ...): constraints must be types."
542        self.__constraints__ = tuple(_type_check(t, msg) for t in constraints)
543        if bound:
544            self.__bound__ = _type_check(bound, "Bound must be a type.")
545        else:
546            self.__bound__ = None
547        def_mod = sys._getframe(1).f_globals['__name__']  # for pickling
548        if def_mod != 'typing':
549            self.__module__ = def_mod
550
551    def __repr__(self):
552        if self.__covariant__:
553            prefix = '+'
554        elif self.__contravariant__:
555            prefix = '-'
556        else:
557            prefix = '~'
558        return prefix + self.__name__
559
560    def __reduce__(self):
561        return self.__name__
562
563
564# Special typing constructs Union, Optional, Generic, Callable and Tuple
565# use three special attributes for internal bookkeeping of generic types:
566# * __parameters__ is a tuple of unique free type parameters of a generic
567#   type, for example, Dict[T, T].__parameters__ == (T,);
568# * __origin__ keeps a reference to a type that was subscripted,
569#   e.g., Union[T, int].__origin__ == Union, or the non-generic version of
570#   the type.
571# * __args__ is a tuple of all arguments used in subscripting,
572#   e.g., Dict[T, int].__args__ == (T, int).
573
574
575# Mapping from non-generic type names that have a generic alias in typing
576# but with a different name.
577_normalize_alias = {'list': 'List',
578                    'tuple': 'Tuple',
579                    'dict': 'Dict',
580                    'set': 'Set',
581                    'frozenset': 'FrozenSet',
582                    'deque': 'Deque',
583                    'defaultdict': 'DefaultDict',
584                    'type': 'Type',
585                    'Set': 'AbstractSet'}
586
587def _is_dunder(attr):
588    return attr.startswith('__') and attr.endswith('__')
589
590
591class _GenericAlias(_Final, _root=True):
592    """The central part of internal API.
593
594    This represents a generic version of type 'origin' with type arguments 'params'.
595    There are two kind of these aliases: user defined and special. The special ones
596    are wrappers around builtin collections and ABCs in collections.abc. These must
597    have 'name' always set. If 'inst' is False, then the alias can't be instantiated,
598    this is used by e.g. typing.List and typing.Dict.
599    """
600    def __init__(self, origin, params, *, inst=True, special=False, name=None):
601        self._inst = inst
602        self._special = special
603        if special and name is None:
604            orig_name = origin.__name__
605            name = _normalize_alias.get(orig_name, orig_name)
606        self._name = name
607        if not isinstance(params, tuple):
608            params = (params,)
609        self.__origin__ = origin
610        self.__args__ = tuple(... if a is _TypingEllipsis else
611                              () if a is _TypingEmpty else
612                              a for a in params)
613        self.__parameters__ = _collect_type_vars(params)
614        self.__slots__ = None  # This is not documented.
615        if not name:
616            self.__module__ = origin.__module__
617
618    @_tp_cache
619    def __getitem__(self, params):
620        if self.__origin__ in (Generic, _Protocol):
621            # Can't subscript Generic[...] or _Protocol[...].
622            raise TypeError(f"Cannot subscript already-subscripted {self}")
623        if not isinstance(params, tuple):
624            params = (params,)
625        msg = "Parameters to generic types must be types."
626        params = tuple(_type_check(p, msg) for p in params)
627        _check_generic(self, params)
628        return _subs_tvars(self, self.__parameters__, params)
629
630    def copy_with(self, params):
631        # We don't copy self._special.
632        return _GenericAlias(self.__origin__, params, name=self._name, inst=self._inst)
633
634    def __repr__(self):
635        if (self._name != 'Callable' or
636                len(self.__args__) == 2 and self.__args__[0] is Ellipsis):
637            if self._name:
638                name = 'typing.' + self._name
639            else:
640                name = _type_repr(self.__origin__)
641            if not self._special:
642                args = f'[{", ".join([_type_repr(a) for a in self.__args__])}]'
643            else:
644                args = ''
645            return (f'{name}{args}')
646        if self._special:
647            return 'typing.Callable'
648        return (f'typing.Callable'
649                f'[[{", ".join([_type_repr(a) for a in self.__args__[:-1]])}], '
650                f'{_type_repr(self.__args__[-1])}]')
651
652    def __eq__(self, other):
653        if not isinstance(other, _GenericAlias):
654            return NotImplemented
655        if self.__origin__ != other.__origin__:
656            return False
657        if self.__origin__ is Union and other.__origin__ is Union:
658            return frozenset(self.__args__) == frozenset(other.__args__)
659        return self.__args__ == other.__args__
660
661    def __hash__(self):
662        if self.__origin__ is Union:
663            return hash((Union, frozenset(self.__args__)))
664        return hash((self.__origin__, self.__args__))
665
666    def __call__(self, *args, **kwargs):
667        if not self._inst:
668            raise TypeError(f"Type {self._name} cannot be instantiated; "
669                            f"use {self._name.lower()}() instead")
670        result = self.__origin__(*args, **kwargs)
671        try:
672            result.__orig_class__ = self
673        except AttributeError:
674            pass
675        return result
676
677    def __mro_entries__(self, bases):
678        if self._name:  # generic version of an ABC or built-in class
679            res = []
680            if self.__origin__ not in bases:
681                res.append(self.__origin__)
682            i = bases.index(self)
683            if not any(isinstance(b, _GenericAlias) or issubclass(b, Generic)
684                       for b in bases[i+1:]):
685                res.append(Generic)
686            return tuple(res)
687        if self.__origin__ is Generic:
688            i = bases.index(self)
689            for b in bases[i+1:]:
690                if isinstance(b, _GenericAlias) and b is not self:
691                    return ()
692        return (self.__origin__,)
693
694    def __getattr__(self, attr):
695        # We are careful for copy and pickle.
696        # Also for simplicity we just don't relay all dunder names
697        if '__origin__' in self.__dict__ and not _is_dunder(attr):
698            return getattr(self.__origin__, attr)
699        raise AttributeError(attr)
700
701    def __setattr__(self, attr, val):
702        if _is_dunder(attr) or attr in ('_name', '_inst', '_special'):
703            super().__setattr__(attr, val)
704        else:
705            setattr(self.__origin__, attr, val)
706
707    def __instancecheck__(self, obj):
708        return self.__subclasscheck__(type(obj))
709
710    def __subclasscheck__(self, cls):
711        if self._special:
712            if not isinstance(cls, _GenericAlias):
713                return issubclass(cls, self.__origin__)
714            if cls._special:
715                return issubclass(cls.__origin__, self.__origin__)
716        raise TypeError("Subscripted generics cannot be used with"
717                        " class and instance checks")
718
719    def __reduce__(self):
720        if self._special:
721            return self._name
722
723        if self._name:
724            origin = globals()[self._name]
725        else:
726            origin = self.__origin__
727        if (origin is Callable and
728            not (len(self.__args__) == 2 and self.__args__[0] is Ellipsis)):
729            args = list(self.__args__[:-1]), self.__args__[-1]
730        else:
731            args = tuple(self.__args__)
732            if len(args) == 1 and not isinstance(args[0], tuple):
733                args, = args
734        return operator.getitem, (origin, args)
735
736
737class _VariadicGenericAlias(_GenericAlias, _root=True):
738    """Same as _GenericAlias above but for variadic aliases. Currently,
739    this is used only by special internal aliases: Tuple and Callable.
740    """
741    def __getitem__(self, params):
742        if self._name != 'Callable' or not self._special:
743            return self.__getitem_inner__(params)
744        if not isinstance(params, tuple) or len(params) != 2:
745            raise TypeError("Callable must be used as "
746                            "Callable[[arg, ...], result].")
747        args, result = params
748        if args is Ellipsis:
749            params = (Ellipsis, result)
750        else:
751            if not isinstance(args, list):
752                raise TypeError(f"Callable[args, result]: args must be a list."
753                                f" Got {args}")
754            params = (tuple(args), result)
755        return self.__getitem_inner__(params)
756
757    @_tp_cache
758    def __getitem_inner__(self, params):
759        if self.__origin__ is tuple and self._special:
760            if params == ():
761                return self.copy_with((_TypingEmpty,))
762            if not isinstance(params, tuple):
763                params = (params,)
764            if len(params) == 2 and params[1] is ...:
765                msg = "Tuple[t, ...]: t must be a type."
766                p = _type_check(params[0], msg)
767                return self.copy_with((p, _TypingEllipsis))
768            msg = "Tuple[t0, t1, ...]: each t must be a type."
769            params = tuple(_type_check(p, msg) for p in params)
770            return self.copy_with(params)
771        if self.__origin__ is collections.abc.Callable and self._special:
772            args, result = params
773            msg = "Callable[args, result]: result must be a type."
774            result = _type_check(result, msg)
775            if args is Ellipsis:
776                return self.copy_with((_TypingEllipsis, result))
777            msg = "Callable[[arg, ...], result]: each arg must be a type."
778            args = tuple(_type_check(arg, msg) for arg in args)
779            params = args + (result,)
780            return self.copy_with(params)
781        return super().__getitem__(params)
782
783
784class Generic:
785    """Abstract base class for generic types.
786
787    A generic type is typically declared by inheriting from
788    this class parameterized with one or more type variables.
789    For example, a generic mapping type might be defined as::
790
791      class Mapping(Generic[KT, VT]):
792          def __getitem__(self, key: KT) -> VT:
793              ...
794          # Etc.
795
796    This class can then be used as follows::
797
798      def lookup_name(mapping: Mapping[KT, VT], key: KT, default: VT) -> VT:
799          try:
800              return mapping[key]
801          except KeyError:
802              return default
803    """
804    __slots__ = ()
805
806    def __new__(cls, *args, **kwds):
807        if cls is Generic:
808            raise TypeError("Type Generic cannot be instantiated; "
809                            "it can be used only as a base class")
810        if super().__new__ is object.__new__ and cls.__init__ is not object.__init__:
811            obj = super().__new__(cls)
812        else:
813            obj = super().__new__(cls, *args, **kwds)
814        return obj
815
816    @_tp_cache
817    def __class_getitem__(cls, params):
818        if not isinstance(params, tuple):
819            params = (params,)
820        if not params and cls is not Tuple:
821            raise TypeError(
822                f"Parameter list to {cls.__qualname__}[...] cannot be empty")
823        msg = "Parameters to generic types must be types."
824        params = tuple(_type_check(p, msg) for p in params)
825        if cls is Generic:
826            # Generic can only be subscripted with unique type variables.
827            if not all(isinstance(p, TypeVar) for p in params):
828                raise TypeError(
829                    "Parameters to Generic[...] must all be type variables")
830            if len(set(params)) != len(params):
831                raise TypeError(
832                    "Parameters to Generic[...] must all be unique")
833        elif cls is _Protocol:
834            # _Protocol is internal at the moment, just skip the check
835            pass
836        else:
837            # Subscripting a regular Generic subclass.
838            _check_generic(cls, params)
839        return _GenericAlias(cls, params)
840
841    def __init_subclass__(cls, *args, **kwargs):
842        super().__init_subclass__(*args, **kwargs)
843        tvars = []
844        if '__orig_bases__' in cls.__dict__:
845            error = Generic in cls.__orig_bases__
846        else:
847            error = Generic in cls.__bases__ and cls.__name__ != '_Protocol'
848        if error:
849            raise TypeError("Cannot inherit from plain Generic")
850        if '__orig_bases__' in cls.__dict__:
851            tvars = _collect_type_vars(cls.__orig_bases__)
852            # Look for Generic[T1, ..., Tn].
853            # If found, tvars must be a subset of it.
854            # If not found, tvars is it.
855            # Also check for and reject plain Generic,
856            # and reject multiple Generic[...].
857            gvars = None
858            for base in cls.__orig_bases__:
859                if (isinstance(base, _GenericAlias) and
860                        base.__origin__ is Generic):
861                    if gvars is not None:
862                        raise TypeError(
863                            "Cannot inherit from Generic[...] multiple types.")
864                    gvars = base.__parameters__
865            if gvars is None:
866                gvars = tvars
867            else:
868                tvarset = set(tvars)
869                gvarset = set(gvars)
870                if not tvarset <= gvarset:
871                    s_vars = ', '.join(str(t) for t in tvars if t not in gvarset)
872                    s_args = ', '.join(str(g) for g in gvars)
873                    raise TypeError(f"Some type variables ({s_vars}) are"
874                                    f" not listed in Generic[{s_args}]")
875                tvars = gvars
876        cls.__parameters__ = tuple(tvars)
877
878
879class _TypingEmpty:
880    """Internal placeholder for () or []. Used by TupleMeta and CallableMeta
881    to allow empty list/tuple in specific places, without allowing them
882    to sneak in where prohibited.
883    """
884
885
886class _TypingEllipsis:
887    """Internal placeholder for ... (ellipsis)."""
888
889
890def cast(typ, val):
891    """Cast a value to a type.
892
893    This returns the value unchanged.  To the type checker this
894    signals that the return value has the designated type, but at
895    runtime we intentionally don't check anything (we want this
896    to be as fast as possible).
897    """
898    return val
899
900
901def _get_defaults(func):
902    """Internal helper to extract the default arguments, by name."""
903    try:
904        code = func.__code__
905    except AttributeError:
906        # Some built-in functions don't have __code__, __defaults__, etc.
907        return {}
908    pos_count = code.co_argcount
909    arg_names = code.co_varnames
910    arg_names = arg_names[:pos_count]
911    defaults = func.__defaults__ or ()
912    kwdefaults = func.__kwdefaults__
913    res = dict(kwdefaults) if kwdefaults else {}
914    pos_offset = pos_count - len(defaults)
915    for name, value in zip(arg_names[pos_offset:], defaults):
916        assert name not in res
917        res[name] = value
918    return res
919
920
921_allowed_types = (types.FunctionType, types.BuiltinFunctionType,
922                  types.MethodType, types.ModuleType,
923                  WrapperDescriptorType, MethodWrapperType, MethodDescriptorType)
924
925
926def get_type_hints(obj, globalns=None, localns=None):
927    """Return type hints for an object.
928
929    This is often the same as obj.__annotations__, but it handles
930    forward references encoded as string literals, and if necessary
931    adds Optional[t] if a default value equal to None is set.
932
933    The argument may be a module, class, method, or function. The annotations
934    are returned as a dictionary. For classes, annotations include also
935    inherited members.
936
937    TypeError is raised if the argument is not of a type that can contain
938    annotations, and an empty dictionary is returned if no annotations are
939    present.
940
941    BEWARE -- the behavior of globalns and localns is counterintuitive
942    (unless you are familiar with how eval() and exec() work).  The
943    search order is locals first, then globals.
944
945    - If no dict arguments are passed, an attempt is made to use the
946      globals from obj (or the respective module's globals for classes),
947      and these are also used as the locals.  If the object does not appear
948      to have globals, an empty dictionary is used.
949
950    - If one dict argument is passed, it is used for both globals and
951      locals.
952
953    - If two dict arguments are passed, they specify globals and
954      locals, respectively.
955    """
956
957    if getattr(obj, '__no_type_check__', None):
958        return {}
959    # Classes require a special treatment.
960    if isinstance(obj, type):
961        hints = {}
962        for base in reversed(obj.__mro__):
963            if globalns is None:
964                base_globals = sys.modules[base.__module__].__dict__
965            else:
966                base_globals = globalns
967            ann = base.__dict__.get('__annotations__', {})
968            for name, value in ann.items():
969                if value is None:
970                    value = type(None)
971                if isinstance(value, str):
972                    value = ForwardRef(value, is_argument=False)
973                value = _eval_type(value, base_globals, localns)
974                hints[name] = value
975        return hints
976
977    if globalns is None:
978        if isinstance(obj, types.ModuleType):
979            globalns = obj.__dict__
980        else:
981            globalns = getattr(obj, '__globals__', {})
982        if localns is None:
983            localns = globalns
984    elif localns is None:
985        localns = globalns
986    hints = getattr(obj, '__annotations__', None)
987    if hints is None:
988        # Return empty annotations for something that _could_ have them.
989        if isinstance(obj, _allowed_types):
990            return {}
991        else:
992            raise TypeError('{!r} is not a module, class, method, '
993                            'or function.'.format(obj))
994    defaults = _get_defaults(obj)
995    hints = dict(hints)
996    for name, value in hints.items():
997        if value is None:
998            value = type(None)
999        if isinstance(value, str):
1000            value = ForwardRef(value)
1001        value = _eval_type(value, globalns, localns)
1002        if name in defaults and defaults[name] is None:
1003            value = Optional[value]
1004        hints[name] = value
1005    return hints
1006
1007
1008def no_type_check(arg):
1009    """Decorator to indicate that annotations are not type hints.
1010
1011    The argument must be a class or function; if it is a class, it
1012    applies recursively to all methods and classes defined in that class
1013    (but not to methods defined in its superclasses or subclasses).
1014
1015    This mutates the function(s) or class(es) in place.
1016    """
1017    if isinstance(arg, type):
1018        arg_attrs = arg.__dict__.copy()
1019        for attr, val in arg.__dict__.items():
1020            if val in arg.__bases__ + (arg,):
1021                arg_attrs.pop(attr)
1022        for obj in arg_attrs.values():
1023            if isinstance(obj, types.FunctionType):
1024                obj.__no_type_check__ = True
1025            if isinstance(obj, type):
1026                no_type_check(obj)
1027    try:
1028        arg.__no_type_check__ = True
1029    except TypeError:  # built-in classes
1030        pass
1031    return arg
1032
1033
1034def no_type_check_decorator(decorator):
1035    """Decorator to give another decorator the @no_type_check effect.
1036
1037    This wraps the decorator with something that wraps the decorated
1038    function in @no_type_check.
1039    """
1040
1041    @functools.wraps(decorator)
1042    def wrapped_decorator(*args, **kwds):
1043        func = decorator(*args, **kwds)
1044        func = no_type_check(func)
1045        return func
1046
1047    return wrapped_decorator
1048
1049
1050def _overload_dummy(*args, **kwds):
1051    """Helper for @overload to raise when called."""
1052    raise NotImplementedError(
1053        "You should not call an overloaded function. "
1054        "A series of @overload-decorated functions "
1055        "outside a stub module should always be followed "
1056        "by an implementation that is not @overload-ed.")
1057
1058
1059def overload(func):
1060    """Decorator for overloaded functions/methods.
1061
1062    In a stub file, place two or more stub definitions for the same
1063    function in a row, each decorated with @overload.  For example:
1064
1065      @overload
1066      def utf8(value: None) -> None: ...
1067      @overload
1068      def utf8(value: bytes) -> bytes: ...
1069      @overload
1070      def utf8(value: str) -> bytes: ...
1071
1072    In a non-stub file (i.e. a regular .py file), do the same but
1073    follow it with an implementation.  The implementation should *not*
1074    be decorated with @overload.  For example:
1075
1076      @overload
1077      def utf8(value: None) -> None: ...
1078      @overload
1079      def utf8(value: bytes) -> bytes: ...
1080      @overload
1081      def utf8(value: str) -> bytes: ...
1082      def utf8(value):
1083          # implementation goes here
1084    """
1085    return _overload_dummy
1086
1087
1088class _ProtocolMeta(type):
1089    """Internal metaclass for _Protocol.
1090
1091    This exists so _Protocol classes can be generic without deriving
1092    from Generic.
1093    """
1094
1095    def __instancecheck__(self, obj):
1096        if _Protocol not in self.__bases__:
1097            return super().__instancecheck__(obj)
1098        raise TypeError("Protocols cannot be used with isinstance().")
1099
1100    def __subclasscheck__(self, cls):
1101        if not self._is_protocol:
1102            # No structural checks since this isn't a protocol.
1103            return NotImplemented
1104
1105        if self is _Protocol:
1106            # Every class is a subclass of the empty protocol.
1107            return True
1108
1109        # Find all attributes defined in the protocol.
1110        attrs = self._get_protocol_attrs()
1111
1112        for attr in attrs:
1113            if not any(attr in d.__dict__ for d in cls.__mro__):
1114                return False
1115        return True
1116
1117    def _get_protocol_attrs(self):
1118        # Get all Protocol base classes.
1119        protocol_bases = []
1120        for c in self.__mro__:
1121            if getattr(c, '_is_protocol', False) and c.__name__ != '_Protocol':
1122                protocol_bases.append(c)
1123
1124        # Get attributes included in protocol.
1125        attrs = set()
1126        for base in protocol_bases:
1127            for attr in base.__dict__.keys():
1128                # Include attributes not defined in any non-protocol bases.
1129                for c in self.__mro__:
1130                    if (c is not base and attr in c.__dict__ and
1131                            not getattr(c, '_is_protocol', False)):
1132                        break
1133                else:
1134                    if (not attr.startswith('_abc_') and
1135                            attr != '__abstractmethods__' and
1136                            attr != '__annotations__' and
1137                            attr != '__weakref__' and
1138                            attr != '_is_protocol' and
1139                            attr != '_gorg' and
1140                            attr != '__dict__' and
1141                            attr != '__args__' and
1142                            attr != '__slots__' and
1143                            attr != '_get_protocol_attrs' and
1144                            attr != '__next_in_mro__' and
1145                            attr != '__parameters__' and
1146                            attr != '__origin__' and
1147                            attr != '__orig_bases__' and
1148                            attr != '__extra__' and
1149                            attr != '__tree_hash__' and
1150                            attr != '__module__'):
1151                        attrs.add(attr)
1152
1153        return attrs
1154
1155
1156class _Protocol(Generic, metaclass=_ProtocolMeta):
1157    """Internal base class for protocol classes.
1158
1159    This implements a simple-minded structural issubclass check
1160    (similar but more general than the one-offs in collections.abc
1161    such as Hashable).
1162    """
1163
1164    __slots__ = ()
1165
1166    _is_protocol = True
1167
1168    def __class_getitem__(cls, params):
1169        return super().__class_getitem__(params)
1170
1171
1172# Some unconstrained type variables.  These are used by the container types.
1173# (These are not for export.)
1174T = TypeVar('T')  # Any type.
1175KT = TypeVar('KT')  # Key type.
1176VT = TypeVar('VT')  # Value type.
1177T_co = TypeVar('T_co', covariant=True)  # Any type covariant containers.
1178V_co = TypeVar('V_co', covariant=True)  # Any type covariant containers.
1179VT_co = TypeVar('VT_co', covariant=True)  # Value type covariant containers.
1180T_contra = TypeVar('T_contra', contravariant=True)  # Ditto contravariant.
1181# Internal type variable used for Type[].
1182CT_co = TypeVar('CT_co', covariant=True, bound=type)
1183
1184# A useful type variable with constraints.  This represents string types.
1185# (This one *is* for export!)
1186AnyStr = TypeVar('AnyStr', bytes, str)
1187
1188
1189# Various ABCs mimicking those in collections.abc.
1190def _alias(origin, params, inst=True):
1191    return _GenericAlias(origin, params, special=True, inst=inst)
1192
1193Hashable = _alias(collections.abc.Hashable, ())  # Not generic.
1194Awaitable = _alias(collections.abc.Awaitable, T_co)
1195Coroutine = _alias(collections.abc.Coroutine, (T_co, T_contra, V_co))
1196AsyncIterable = _alias(collections.abc.AsyncIterable, T_co)
1197AsyncIterator = _alias(collections.abc.AsyncIterator, T_co)
1198Iterable = _alias(collections.abc.Iterable, T_co)
1199Iterator = _alias(collections.abc.Iterator, T_co)
1200Reversible = _alias(collections.abc.Reversible, T_co)
1201Sized = _alias(collections.abc.Sized, ())  # Not generic.
1202Container = _alias(collections.abc.Container, T_co)
1203Collection = _alias(collections.abc.Collection, T_co)
1204Callable = _VariadicGenericAlias(collections.abc.Callable, (), special=True)
1205Callable.__doc__ = \
1206    """Callable type; Callable[[int], str] is a function of (int) -> str.
1207
1208    The subscription syntax must always be used with exactly two
1209    values: the argument list and the return type.  The argument list
1210    must be a list of types or ellipsis; the return type must be a single type.
1211
1212    There is no syntax to indicate optional or keyword arguments,
1213    such function types are rarely used as callback types.
1214    """
1215AbstractSet = _alias(collections.abc.Set, T_co)
1216MutableSet = _alias(collections.abc.MutableSet, T)
1217# NOTE: Mapping is only covariant in the value type.
1218Mapping = _alias(collections.abc.Mapping, (KT, VT_co))
1219MutableMapping = _alias(collections.abc.MutableMapping, (KT, VT))
1220Sequence = _alias(collections.abc.Sequence, T_co)
1221MutableSequence = _alias(collections.abc.MutableSequence, T)
1222ByteString = _alias(collections.abc.ByteString, ())  # Not generic
1223Tuple = _VariadicGenericAlias(tuple, (), inst=False, special=True)
1224Tuple.__doc__ = \
1225    """Tuple type; Tuple[X, Y] is the cross-product type of X and Y.
1226
1227    Example: Tuple[T1, T2] is a tuple of two elements corresponding
1228    to type variables T1 and T2.  Tuple[int, float, str] is a tuple
1229    of an int, a float and a string.
1230
1231    To specify a variable-length tuple of homogeneous type, use Tuple[T, ...].
1232    """
1233List = _alias(list, T, inst=False)
1234Deque = _alias(collections.deque, T)
1235Set = _alias(set, T, inst=False)
1236FrozenSet = _alias(frozenset, T_co, inst=False)
1237MappingView = _alias(collections.abc.MappingView, T_co)
1238KeysView = _alias(collections.abc.KeysView, KT)
1239ItemsView = _alias(collections.abc.ItemsView, (KT, VT_co))
1240ValuesView = _alias(collections.abc.ValuesView, VT_co)
1241ContextManager = _alias(contextlib.AbstractContextManager, T_co)
1242AsyncContextManager = _alias(contextlib.AbstractAsyncContextManager, T_co)
1243Dict = _alias(dict, (KT, VT), inst=False)
1244DefaultDict = _alias(collections.defaultdict, (KT, VT))
1245OrderedDict = _alias(collections.OrderedDict, (KT, VT))
1246Counter = _alias(collections.Counter, T)
1247ChainMap = _alias(collections.ChainMap, (KT, VT))
1248Generator = _alias(collections.abc.Generator, (T_co, T_contra, V_co))
1249AsyncGenerator = _alias(collections.abc.AsyncGenerator, (T_co, T_contra))
1250Type = _alias(type, CT_co, inst=False)
1251Type.__doc__ = \
1252    """A special construct usable to annotate class objects.
1253
1254    For example, suppose we have the following classes::
1255
1256      class User: ...  # Abstract base for User classes
1257      class BasicUser(User): ...
1258      class ProUser(User): ...
1259      class TeamUser(User): ...
1260
1261    And a function that takes a class argument that's a subclass of
1262    User and returns an instance of the corresponding class::
1263
1264      U = TypeVar('U', bound=User)
1265      def new_user(user_class: Type[U]) -> U:
1266          user = user_class()
1267          # (Here we could write the user object to a database)
1268          return user
1269
1270      joe = new_user(BasicUser)
1271
1272    At this point the type checker knows that joe has type BasicUser.
1273    """
1274
1275
1276class SupportsInt(_Protocol):
1277    __slots__ = ()
1278
1279    @abstractmethod
1280    def __int__(self) -> int:
1281        pass
1282
1283
1284class SupportsFloat(_Protocol):
1285    __slots__ = ()
1286
1287    @abstractmethod
1288    def __float__(self) -> float:
1289        pass
1290
1291
1292class SupportsComplex(_Protocol):
1293    __slots__ = ()
1294
1295    @abstractmethod
1296    def __complex__(self) -> complex:
1297        pass
1298
1299
1300class SupportsBytes(_Protocol):
1301    __slots__ = ()
1302
1303    @abstractmethod
1304    def __bytes__(self) -> bytes:
1305        pass
1306
1307
1308class SupportsAbs(_Protocol[T_co]):
1309    __slots__ = ()
1310
1311    @abstractmethod
1312    def __abs__(self) -> T_co:
1313        pass
1314
1315
1316class SupportsRound(_Protocol[T_co]):
1317    __slots__ = ()
1318
1319    @abstractmethod
1320    def __round__(self, ndigits: int = 0) -> T_co:
1321        pass
1322
1323
1324def _make_nmtuple(name, types):
1325    msg = "NamedTuple('Name', [(f0, t0), (f1, t1), ...]); each t must be a type"
1326    types = [(n, _type_check(t, msg)) for n, t in types]
1327    nm_tpl = collections.namedtuple(name, [n for n, t in types])
1328    # Prior to PEP 526, only _field_types attribute was assigned.
1329    # Now, both __annotations__ and _field_types are used to maintain compatibility.
1330    nm_tpl.__annotations__ = nm_tpl._field_types = collections.OrderedDict(types)
1331    try:
1332        nm_tpl.__module__ = sys._getframe(2).f_globals.get('__name__', '__main__')
1333    except (AttributeError, ValueError):
1334        pass
1335    return nm_tpl
1336
1337
1338# attributes prohibited to set in NamedTuple class syntax
1339_prohibited = ('__new__', '__init__', '__slots__', '__getnewargs__',
1340               '_fields', '_field_defaults', '_field_types',
1341               '_make', '_replace', '_asdict', '_source')
1342
1343_special = ('__module__', '__name__', '__qualname__', '__annotations__')
1344
1345
1346class NamedTupleMeta(type):
1347
1348    def __new__(cls, typename, bases, ns):
1349        if ns.get('_root', False):
1350            return super().__new__(cls, typename, bases, ns)
1351        types = ns.get('__annotations__', {})
1352        nm_tpl = _make_nmtuple(typename, types.items())
1353        defaults = []
1354        defaults_dict = {}
1355        for field_name in types:
1356            if field_name in ns:
1357                default_value = ns[field_name]
1358                defaults.append(default_value)
1359                defaults_dict[field_name] = default_value
1360            elif defaults:
1361                raise TypeError("Non-default namedtuple field {field_name} cannot "
1362                                "follow default field(s) {default_names}"
1363                                .format(field_name=field_name,
1364                                        default_names=', '.join(defaults_dict.keys())))
1365        nm_tpl.__new__.__annotations__ = collections.OrderedDict(types)
1366        nm_tpl.__new__.__defaults__ = tuple(defaults)
1367        nm_tpl._field_defaults = defaults_dict
1368        # update from user namespace without overriding special namedtuple attributes
1369        for key in ns:
1370            if key in _prohibited:
1371                raise AttributeError("Cannot overwrite NamedTuple attribute " + key)
1372            elif key not in _special and key not in nm_tpl._fields:
1373                setattr(nm_tpl, key, ns[key])
1374        return nm_tpl
1375
1376
1377class NamedTuple(metaclass=NamedTupleMeta):
1378    """Typed version of namedtuple.
1379
1380    Usage in Python versions >= 3.6::
1381
1382        class Employee(NamedTuple):
1383            name: str
1384            id: int
1385
1386    This is equivalent to::
1387
1388        Employee = collections.namedtuple('Employee', ['name', 'id'])
1389
1390    The resulting class has extra __annotations__ and _field_types
1391    attributes, giving an ordered dict mapping field names to types.
1392    __annotations__ should be preferred, while _field_types
1393    is kept to maintain pre PEP 526 compatibility. (The field names
1394    are in the _fields attribute, which is part of the namedtuple
1395    API.) Alternative equivalent keyword syntax is also accepted::
1396
1397        Employee = NamedTuple('Employee', name=str, id=int)
1398
1399    In Python versions <= 3.5 use::
1400
1401        Employee = NamedTuple('Employee', [('name', str), ('id', int)])
1402    """
1403    _root = True
1404
1405    def __new__(self, typename, fields=None, **kwargs):
1406        if fields is None:
1407            fields = kwargs.items()
1408        elif kwargs:
1409            raise TypeError("Either list of fields or keywords"
1410                            " can be provided to NamedTuple, not both")
1411        return _make_nmtuple(typename, fields)
1412
1413
1414def NewType(name, tp):
1415    """NewType creates simple unique types with almost zero
1416    runtime overhead. NewType(name, tp) is considered a subtype of tp
1417    by static type checkers. At runtime, NewType(name, tp) returns
1418    a dummy function that simply returns its argument. Usage::
1419
1420        UserId = NewType('UserId', int)
1421
1422        def name_by_id(user_id: UserId) -> str:
1423            ...
1424
1425        UserId('user')          # Fails type check
1426
1427        name_by_id(42)          # Fails type check
1428        name_by_id(UserId(42))  # OK
1429
1430        num = UserId(5) + 1     # type: int
1431    """
1432
1433    def new_type(x):
1434        return x
1435
1436    new_type.__name__ = name
1437    new_type.__supertype__ = tp
1438    return new_type
1439
1440
1441# Python-version-specific alias (Python 2: unicode; Python 3: str)
1442Text = str
1443
1444
1445# Constant that's True when type checking, but False here.
1446TYPE_CHECKING = False
1447
1448
1449class IO(Generic[AnyStr]):
1450    """Generic base class for TextIO and BinaryIO.
1451
1452    This is an abstract, generic version of the return of open().
1453
1454    NOTE: This does not distinguish between the different possible
1455    classes (text vs. binary, read vs. write vs. read/write,
1456    append-only, unbuffered).  The TextIO and BinaryIO subclasses
1457    below capture the distinctions between text vs. binary, which is
1458    pervasive in the interface; however we currently do not offer a
1459    way to track the other distinctions in the type system.
1460    """
1461
1462    __slots__ = ()
1463
1464    @abstractproperty
1465    def mode(self) -> str:
1466        pass
1467
1468    @abstractproperty
1469    def name(self) -> str:
1470        pass
1471
1472    @abstractmethod
1473    def close(self) -> None:
1474        pass
1475
1476    @abstractmethod
1477    def closed(self) -> bool:
1478        pass
1479
1480    @abstractmethod
1481    def fileno(self) -> int:
1482        pass
1483
1484    @abstractmethod
1485    def flush(self) -> None:
1486        pass
1487
1488    @abstractmethod
1489    def isatty(self) -> bool:
1490        pass
1491
1492    @abstractmethod
1493    def read(self, n: int = -1) -> AnyStr:
1494        pass
1495
1496    @abstractmethod
1497    def readable(self) -> bool:
1498        pass
1499
1500    @abstractmethod
1501    def readline(self, limit: int = -1) -> AnyStr:
1502        pass
1503
1504    @abstractmethod
1505    def readlines(self, hint: int = -1) -> List[AnyStr]:
1506        pass
1507
1508    @abstractmethod
1509    def seek(self, offset: int, whence: int = 0) -> int:
1510        pass
1511
1512    @abstractmethod
1513    def seekable(self) -> bool:
1514        pass
1515
1516    @abstractmethod
1517    def tell(self) -> int:
1518        pass
1519
1520    @abstractmethod
1521    def truncate(self, size: int = None) -> int:
1522        pass
1523
1524    @abstractmethod
1525    def writable(self) -> bool:
1526        pass
1527
1528    @abstractmethod
1529    def write(self, s: AnyStr) -> int:
1530        pass
1531
1532    @abstractmethod
1533    def writelines(self, lines: List[AnyStr]) -> None:
1534        pass
1535
1536    @abstractmethod
1537    def __enter__(self) -> 'IO[AnyStr]':
1538        pass
1539
1540    @abstractmethod
1541    def __exit__(self, type, value, traceback) -> None:
1542        pass
1543
1544
1545class BinaryIO(IO[bytes]):
1546    """Typed version of the return of open() in binary mode."""
1547
1548    __slots__ = ()
1549
1550    @abstractmethod
1551    def write(self, s: Union[bytes, bytearray]) -> int:
1552        pass
1553
1554    @abstractmethod
1555    def __enter__(self) -> 'BinaryIO':
1556        pass
1557
1558
1559class TextIO(IO[str]):
1560    """Typed version of the return of open() in text mode."""
1561
1562    __slots__ = ()
1563
1564    @abstractproperty
1565    def buffer(self) -> BinaryIO:
1566        pass
1567
1568    @abstractproperty
1569    def encoding(self) -> str:
1570        pass
1571
1572    @abstractproperty
1573    def errors(self) -> Optional[str]:
1574        pass
1575
1576    @abstractproperty
1577    def line_buffering(self) -> bool:
1578        pass
1579
1580    @abstractproperty
1581    def newlines(self) -> Any:
1582        pass
1583
1584    @abstractmethod
1585    def __enter__(self) -> 'TextIO':
1586        pass
1587
1588
1589class io:
1590    """Wrapper namespace for IO generic classes."""
1591
1592    __all__ = ['IO', 'TextIO', 'BinaryIO']
1593    IO = IO
1594    TextIO = TextIO
1595    BinaryIO = BinaryIO
1596
1597
1598io.__name__ = __name__ + '.io'
1599sys.modules[io.__name__] = io
1600
1601Pattern = _alias(stdlib_re.Pattern, AnyStr)
1602Match = _alias(stdlib_re.Match, AnyStr)
1603
1604class re:
1605    """Wrapper namespace for re type aliases."""
1606
1607    __all__ = ['Pattern', 'Match']
1608    Pattern = Pattern
1609    Match = Match
1610
1611
1612re.__name__ = __name__ + '.re'
1613sys.modules[re.__name__] = re
1614