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* Public helper functions: get_type_hints, overload, cast, no_type_check,
14  no_type_check_decorator.
15* Generic aliases for collections.abc ABCs and few additional protocols.
16* Special types: NewType, NamedTuple, TypedDict.
17* Wrapper submodules for re and io related types.
18"""
19
20from abc import abstractmethod, ABCMeta
21import collections
22import collections.abc
23import contextlib
24import functools
25import operator
26import re as stdlib_re  # Avoid confusion with the re we export.
27import sys
28import types
29from types import WrapperDescriptorType, MethodWrapperType, MethodDescriptorType, GenericAlias
30
31# Please keep __all__ alphabetized within each category.
32__all__ = [
33    # Super-special typing primitives.
34    'Annotated',
35    'Any',
36    'Callable',
37    'ClassVar',
38    'Final',
39    'ForwardRef',
40    'Generic',
41    'Literal',
42    'Optional',
43    'Protocol',
44    'Tuple',
45    'Type',
46    'TypeVar',
47    'Union',
48
49    # ABCs (from collections.abc).
50    'AbstractSet',  # collections.abc.Set.
51    'ByteString',
52    'Container',
53    'ContextManager',
54    'Hashable',
55    'ItemsView',
56    'Iterable',
57    'Iterator',
58    'KeysView',
59    'Mapping',
60    'MappingView',
61    'MutableMapping',
62    'MutableSequence',
63    'MutableSet',
64    'Sequence',
65    'Sized',
66    'ValuesView',
67    'Awaitable',
68    'AsyncIterator',
69    'AsyncIterable',
70    'Coroutine',
71    'Collection',
72    'AsyncGenerator',
73    'AsyncContextManager',
74
75    # Structural checks, a.k.a. protocols.
76    'Reversible',
77    'SupportsAbs',
78    'SupportsBytes',
79    'SupportsComplex',
80    'SupportsFloat',
81    'SupportsIndex',
82    'SupportsInt',
83    'SupportsRound',
84
85    # Concrete collection types.
86    'ChainMap',
87    'Counter',
88    'Deque',
89    'Dict',
90    'DefaultDict',
91    'List',
92    'OrderedDict',
93    'Set',
94    'FrozenSet',
95    'NamedTuple',  # Not really a type.
96    'TypedDict',  # Not really a type.
97    'Generator',
98
99    # One-off things.
100    'AnyStr',
101    'cast',
102    'final',
103    'get_args',
104    'get_origin',
105    'get_type_hints',
106    'NewType',
107    'no_type_check',
108    'no_type_check_decorator',
109    'NoReturn',
110    'overload',
111    'runtime_checkable',
112    'Text',
113    'TYPE_CHECKING',
114]
115
116# The pseudo-submodules 're' and 'io' are part of the public
117# namespace, but excluded from __all__ because they might stomp on
118# legitimate imports of those modules.
119
120
121def _type_check(arg, msg, is_argument=True):
122    """Check that the argument is a type, and return it (internal helper).
123
124    As a special case, accept None and return type(None) instead. Also wrap strings
125    into ForwardRef instances. Consider several corner cases, for example plain
126    special forms like Union are not valid, while Union[int, str] is OK, etc.
127    The msg argument is a human-readable error message, e.g::
128
129        "Union[arg, ...]: arg should be a type."
130
131    We append the repr() of the actual value (truncated to 100 chars).
132    """
133    invalid_generic_forms = (Generic, Protocol)
134    if is_argument:
135        invalid_generic_forms = invalid_generic_forms + (ClassVar, Final)
136
137    if arg is None:
138        return type(None)
139    if isinstance(arg, str):
140        return ForwardRef(arg)
141    if (isinstance(arg, _GenericAlias) and
142            arg.__origin__ in invalid_generic_forms):
143        raise TypeError(f"{arg} is not valid as type argument")
144    if arg in (Any, NoReturn):
145        return arg
146    if isinstance(arg, _SpecialForm) or arg in (Generic, Protocol):
147        raise TypeError(f"Plain {arg} is not valid as type argument")
148    if isinstance(arg, (type, TypeVar, ForwardRef)):
149        return arg
150    if not callable(arg):
151        raise TypeError(f"{msg} Got {arg!r:.100}.")
152    return arg
153
154
155def _type_repr(obj):
156    """Return the repr() of an object, special-casing types (internal helper).
157
158    If obj is a type, we return a shorter version than the default
159    type.__repr__, based on the module and qualified name, which is
160    typically enough to uniquely identify a type.  For everything
161    else, we fall back on repr(obj).
162    """
163    if isinstance(obj, types.GenericAlias):
164        return repr(obj)
165    if isinstance(obj, type):
166        if obj.__module__ == 'builtins':
167            return obj.__qualname__
168        return f'{obj.__module__}.{obj.__qualname__}'
169    if obj is ...:
170        return('...')
171    if isinstance(obj, types.FunctionType):
172        return obj.__name__
173    return repr(obj)
174
175
176def _collect_type_vars(types):
177    """Collect all type variable contained in types in order of
178    first appearance (lexicographic order). For example::
179
180        _collect_type_vars((T, List[S, T])) == (T, S)
181    """
182    tvars = []
183    for t in types:
184        if isinstance(t, TypeVar) and t not in tvars:
185            tvars.append(t)
186        if isinstance(t, (_GenericAlias, GenericAlias)):
187            tvars.extend([t for t in t.__parameters__ if t not in tvars])
188    return tuple(tvars)
189
190
191def _check_generic(cls, parameters, elen):
192    """Check correct count for parameters of a generic cls (internal helper).
193    This gives a nice error message in case of count mismatch.
194    """
195    if not elen:
196        raise TypeError(f"{cls} is not a generic class")
197    alen = len(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 _deduplicate(params):
204    # Weed out strict duplicates, preserving the first of each occurrence.
205    all_params = set(params)
206    if len(all_params) < len(params):
207        new_params = []
208        for t in params:
209            if t in all_params:
210                new_params.append(t)
211                all_params.remove(t)
212        params = new_params
213        assert not all_params, all_params
214    return params
215
216
217def _remove_dups_flatten(parameters):
218    """An internal helper for Union creation and substitution: flatten Unions
219    among parameters, then remove duplicates.
220    """
221    # Flatten out Union[Union[...], ...].
222    params = []
223    for p in parameters:
224        if isinstance(p, _UnionGenericAlias):
225            params.extend(p.__args__)
226        elif isinstance(p, tuple) and len(p) > 0 and p[0] is Union:
227            params.extend(p[1:])
228        else:
229            params.append(p)
230
231    return tuple(_deduplicate(params))
232
233
234def _flatten_literal_params(parameters):
235    """An internal helper for Literal creation: flatten Literals among parameters"""
236    params = []
237    for p in parameters:
238        if isinstance(p, _LiteralGenericAlias):
239            params.extend(p.__args__)
240        else:
241            params.append(p)
242    return tuple(params)
243
244
245_cleanups = []
246
247
248def _tp_cache(func=None, /, *, typed=False):
249    """Internal wrapper caching __getitem__ of generic types with a fallback to
250    original function for non-hashable arguments.
251    """
252    def decorator(func):
253        cached = functools.lru_cache(typed=typed)(func)
254        _cleanups.append(cached.cache_clear)
255
256        @functools.wraps(func)
257        def inner(*args, **kwds):
258            try:
259                return cached(*args, **kwds)
260            except TypeError:
261                pass  # All real errors (not unhashable args) are raised below.
262            return func(*args, **kwds)
263        return inner
264
265    if func is not None:
266        return decorator(func)
267
268    return decorator
269
270def _eval_type(t, globalns, localns, recursive_guard=frozenset()):
271    """Evaluate all forward references in the given type t.
272    For use of globalns and localns see the docstring for get_type_hints().
273    recursive_guard is used to prevent prevent infinite recursion
274    with recursive ForwardRef.
275    """
276    if isinstance(t, ForwardRef):
277        return t._evaluate(globalns, localns, recursive_guard)
278    if isinstance(t, (_GenericAlias, GenericAlias)):
279        ev_args = tuple(_eval_type(a, globalns, localns, recursive_guard) for a in t.__args__)
280        if ev_args == t.__args__:
281            return t
282        if isinstance(t, GenericAlias):
283            return GenericAlias(t.__origin__, ev_args)
284        else:
285            return t.copy_with(ev_args)
286    return t
287
288
289class _Final:
290    """Mixin to prohibit subclassing"""
291
292    __slots__ = ('__weakref__',)
293
294    def __init_subclass__(self, /, *args, **kwds):
295        if '_root' not in kwds:
296            raise TypeError("Cannot subclass special typing classes")
297
298class _Immutable:
299    """Mixin to indicate that object should not be copied."""
300    __slots__ = ()
301
302    def __copy__(self):
303        return self
304
305    def __deepcopy__(self, memo):
306        return self
307
308
309# Internal indicator of special typing constructs.
310# See __doc__ instance attribute for specific docs.
311class _SpecialForm(_Final, _root=True):
312    __slots__ = ('_name', '__doc__', '_getitem')
313
314    def __init__(self, getitem):
315        self._getitem = getitem
316        self._name = getitem.__name__
317        self.__doc__ = getitem.__doc__
318
319    def __mro_entries__(self, bases):
320        raise TypeError(f"Cannot subclass {self!r}")
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        return self._getitem(self, parameters)
340
341
342class _LiteralSpecialForm(_SpecialForm, _root=True):
343    @_tp_cache(typed=True)
344    def __getitem__(self, parameters):
345        return self._getitem(self, parameters)
346
347
348@_SpecialForm
349def Any(self, parameters):
350    """Special type indicating an unconstrained type.
351
352    - Any is compatible with every type.
353    - Any assumed to have all methods.
354    - All values assumed to be instances of Any.
355
356    Note that all the above statements are true from the point of view of
357    static type checkers. At runtime, Any should not be used with instance
358    or class checks.
359    """
360    raise TypeError(f"{self} is not subscriptable")
361
362@_SpecialForm
363def NoReturn(self, parameters):
364    """Special type indicating functions that never return.
365    Example::
366
367      from typing import NoReturn
368
369      def stop() -> NoReturn:
370          raise Exception('no way')
371
372    This type is invalid in other positions, e.g., ``List[NoReturn]``
373    will fail in static type checkers.
374    """
375    raise TypeError(f"{self} is not subscriptable")
376
377@_SpecialForm
378def ClassVar(self, parameters):
379    """Special type construct to mark class variables.
380
381    An annotation wrapped in ClassVar indicates that a given
382    attribute is intended to be used as a class variable and
383    should not be set on instances of that class. Usage::
384
385      class Starship:
386          stats: ClassVar[Dict[str, int]] = {} # class variable
387          damage: int = 10                     # instance variable
388
389    ClassVar accepts only types and cannot be further subscribed.
390
391    Note that ClassVar is not a class itself, and should not
392    be used with isinstance() or issubclass().
393    """
394    item = _type_check(parameters, f'{self} accepts only single type.')
395    return _GenericAlias(self, (item,))
396
397@_SpecialForm
398def Final(self, parameters):
399    """Special typing construct to indicate final names to type checkers.
400
401    A final name cannot be re-assigned or overridden in a subclass.
402    For example:
403
404      MAX_SIZE: Final = 9000
405      MAX_SIZE += 1  # Error reported by type checker
406
407      class Connection:
408          TIMEOUT: Final[int] = 10
409
410      class FastConnector(Connection):
411          TIMEOUT = 1  # Error reported by type checker
412
413    There is no runtime checking of these properties.
414    """
415    item = _type_check(parameters, f'{self} accepts only single type.')
416    return _GenericAlias(self, (item,))
417
418@_SpecialForm
419def Union(self, parameters):
420    """Union type; Union[X, Y] means either X or Y.
421
422    To define a union, use e.g. Union[int, str].  Details:
423    - The arguments must be types and there must be at least one.
424    - None as an argument is a special case and is replaced by
425      type(None).
426    - Unions of unions are flattened, e.g.::
427
428        Union[Union[int, str], float] == Union[int, str, float]
429
430    - Unions of a single argument vanish, e.g.::
431
432        Union[int] == int  # The constructor actually returns int
433
434    - Redundant arguments are skipped, e.g.::
435
436        Union[int, str, int] == Union[int, str]
437
438    - When comparing unions, the argument order is ignored, e.g.::
439
440        Union[int, str] == Union[str, int]
441
442    - You cannot subclass or instantiate a union.
443    - You can use Optional[X] as a shorthand for Union[X, None].
444    """
445    if parameters == ():
446        raise TypeError("Cannot take a Union of no types.")
447    if not isinstance(parameters, tuple):
448        parameters = (parameters,)
449    msg = "Union[arg, ...]: each arg must be a type."
450    parameters = tuple(_type_check(p, msg) for p in parameters)
451    parameters = _remove_dups_flatten(parameters)
452    if len(parameters) == 1:
453        return parameters[0]
454    return _UnionGenericAlias(self, parameters)
455
456@_SpecialForm
457def Optional(self, parameters):
458    """Optional type.
459
460    Optional[X] is equivalent to Union[X, None].
461    """
462    arg = _type_check(parameters, f"{self} requires a single type.")
463    return Union[arg, type(None)]
464
465@_LiteralSpecialForm
466def Literal(self, parameters):
467    """Special typing form to define literal types (a.k.a. value types).
468
469    This form can be used to indicate to type checkers that the corresponding
470    variable or function parameter has a value equivalent to the provided
471    literal (or one of several literals):
472
473      def validate_simple(data: Any) -> Literal[True]:  # always returns True
474          ...
475
476      MODE = Literal['r', 'rb', 'w', 'wb']
477      def open_helper(file: str, mode: MODE) -> str:
478          ...
479
480      open_helper('/some/path', 'r')  # Passes type check
481      open_helper('/other/path', 'typo')  # Error in type checker
482
483    Literal[...] cannot be subclassed. At runtime, an arbitrary value
484    is allowed as type argument to Literal[...], but type checkers may
485    impose restrictions.
486    """
487    # There is no '_type_check' call because arguments to Literal[...] are
488    # values, not types.
489    if not isinstance(parameters, tuple):
490        parameters = (parameters,)
491
492    parameters = _flatten_literal_params(parameters)
493
494    try:
495        parameters = tuple(p for p, _ in _deduplicate(list(_value_and_type_iter(parameters))))
496    except TypeError:  # unhashable parameters
497        pass
498
499    return _LiteralGenericAlias(self, parameters)
500
501
502class ForwardRef(_Final, _root=True):
503    """Internal wrapper to hold a forward reference."""
504
505    __slots__ = ('__forward_arg__', '__forward_code__',
506                 '__forward_evaluated__', '__forward_value__',
507                 '__forward_is_argument__')
508
509    def __init__(self, arg, is_argument=True):
510        if not isinstance(arg, str):
511            raise TypeError(f"Forward reference must be a string -- got {arg!r}")
512        try:
513            code = compile(arg, '<string>', 'eval')
514        except SyntaxError:
515            raise SyntaxError(f"Forward reference must be an expression -- got {arg!r}")
516        self.__forward_arg__ = arg
517        self.__forward_code__ = code
518        self.__forward_evaluated__ = False
519        self.__forward_value__ = None
520        self.__forward_is_argument__ = is_argument
521
522    def _evaluate(self, globalns, localns, recursive_guard):
523        if self.__forward_arg__ in recursive_guard:
524            return self
525        if not self.__forward_evaluated__ or localns is not globalns:
526            if globalns is None and localns is None:
527                globalns = localns = {}
528            elif globalns is None:
529                globalns = localns
530            elif localns is None:
531                localns = globalns
532            type_ =_type_check(
533                eval(self.__forward_code__, globalns, localns),
534                "Forward references must evaluate to types.",
535                is_argument=self.__forward_is_argument__,
536            )
537            self.__forward_value__ = _eval_type(
538                type_, globalns, localns, recursive_guard | {self.__forward_arg__}
539            )
540            self.__forward_evaluated__ = True
541        return self.__forward_value__
542
543    def __eq__(self, other):
544        if not isinstance(other, ForwardRef):
545            return NotImplemented
546        if self.__forward_evaluated__ and other.__forward_evaluated__:
547            return (self.__forward_arg__ == other.__forward_arg__ and
548                    self.__forward_value__ == other.__forward_value__)
549        return self.__forward_arg__ == other.__forward_arg__
550
551    def __hash__(self):
552        return hash(self.__forward_arg__)
553
554    def __repr__(self):
555        return f'ForwardRef({self.__forward_arg__!r})'
556
557
558class TypeVar(_Final, _Immutable, _root=True):
559    """Type variable.
560
561    Usage::
562
563      T = TypeVar('T')  # Can be anything
564      A = TypeVar('A', str, bytes)  # Must be str or bytes
565
566    Type variables exist primarily for the benefit of static type
567    checkers.  They serve as the parameters for generic types as well
568    as for generic function definitions.  See class Generic for more
569    information on generic types.  Generic functions work as follows:
570
571      def repeat(x: T, n: int) -> List[T]:
572          '''Return a list containing n references to x.'''
573          return [x]*n
574
575      def longest(x: A, y: A) -> A:
576          '''Return the longest of two strings.'''
577          return x if len(x) >= len(y) else y
578
579    The latter example's signature is essentially the overloading
580    of (str, str) -> str and (bytes, bytes) -> bytes.  Also note
581    that if the arguments are instances of some subclass of str,
582    the return type is still plain str.
583
584    At runtime, isinstance(x, T) and issubclass(C, T) will raise TypeError.
585
586    Type variables defined with covariant=True or contravariant=True
587    can be used to declare covariant or contravariant generic types.
588    See PEP 484 for more details. By default generic types are invariant
589    in all type variables.
590
591    Type variables can be introspected. e.g.:
592
593      T.__name__ == 'T'
594      T.__constraints__ == ()
595      T.__covariant__ == False
596      T.__contravariant__ = False
597      A.__constraints__ == (str, bytes)
598
599    Note that only type variables defined in global scope can be pickled.
600    """
601
602    __slots__ = ('__name__', '__bound__', '__constraints__',
603                 '__covariant__', '__contravariant__', '__dict__')
604
605    def __init__(self, name, *constraints, bound=None,
606                 covariant=False, contravariant=False):
607        self.__name__ = name
608        if covariant and contravariant:
609            raise ValueError("Bivariant types are not supported.")
610        self.__covariant__ = bool(covariant)
611        self.__contravariant__ = bool(contravariant)
612        if constraints and bound is not None:
613            raise TypeError("Constraints cannot be combined with bound=...")
614        if constraints and len(constraints) == 1:
615            raise TypeError("A single constraint is not allowed")
616        msg = "TypeVar(name, constraint, ...): constraints must be types."
617        self.__constraints__ = tuple(_type_check(t, msg) for t in constraints)
618        if bound:
619            self.__bound__ = _type_check(bound, "Bound must be a type.")
620        else:
621            self.__bound__ = None
622        try:
623            def_mod = sys._getframe(1).f_globals.get('__name__', '__main__')  # for pickling
624        except (AttributeError, ValueError):
625            def_mod = None
626        if def_mod != 'typing':
627            self.__module__ = def_mod
628
629    def __repr__(self):
630        if self.__covariant__:
631            prefix = '+'
632        elif self.__contravariant__:
633            prefix = '-'
634        else:
635            prefix = '~'
636        return prefix + self.__name__
637
638    def __reduce__(self):
639        return self.__name__
640
641
642def _is_dunder(attr):
643    return attr.startswith('__') and attr.endswith('__')
644
645class _BaseGenericAlias(_Final, _root=True):
646    """The central part of internal API.
647
648    This represents a generic version of type 'origin' with type arguments 'params'.
649    There are two kind of these aliases: user defined and special. The special ones
650    are wrappers around builtin collections and ABCs in collections.abc. These must
651    have 'name' always set. If 'inst' is False, then the alias can't be instantiated,
652    this is used by e.g. typing.List and typing.Dict.
653    """
654    def __init__(self, origin, *, inst=True, name=None):
655        self._inst = inst
656        self._name = name
657        self.__origin__ = origin
658        self.__slots__ = None  # This is not documented.
659
660    def __call__(self, *args, **kwargs):
661        if not self._inst:
662            raise TypeError(f"Type {self._name} cannot be instantiated; "
663                            f"use {self.__origin__.__name__}() instead")
664        result = self.__origin__(*args, **kwargs)
665        try:
666            result.__orig_class__ = self
667        except AttributeError:
668            pass
669        return result
670
671    def __mro_entries__(self, bases):
672        res = []
673        if self.__origin__ not in bases:
674            res.append(self.__origin__)
675        i = bases.index(self)
676        for b in bases[i+1:]:
677            if isinstance(b, _BaseGenericAlias) or issubclass(b, Generic):
678                break
679        else:
680            res.append(Generic)
681        return tuple(res)
682
683    def __getattr__(self, attr):
684        # We are careful for copy and pickle.
685        # Also for simplicity we just don't relay all dunder names
686        if '__origin__' in self.__dict__ and not _is_dunder(attr):
687            return getattr(self.__origin__, attr)
688        raise AttributeError(attr)
689
690    def __setattr__(self, attr, val):
691        if _is_dunder(attr) or attr in ('_name', '_inst', '_nparams'):
692            super().__setattr__(attr, val)
693        else:
694            setattr(self.__origin__, attr, val)
695
696    def __instancecheck__(self, obj):
697        return self.__subclasscheck__(type(obj))
698
699    def __subclasscheck__(self, cls):
700        raise TypeError("Subscripted generics cannot be used with"
701                        " class and instance checks")
702
703
704# Special typing constructs Union, Optional, Generic, Callable and Tuple
705# use three special attributes for internal bookkeeping of generic types:
706# * __parameters__ is a tuple of unique free type parameters of a generic
707#   type, for example, Dict[T, T].__parameters__ == (T,);
708# * __origin__ keeps a reference to a type that was subscripted,
709#   e.g., Union[T, int].__origin__ == Union, or the non-generic version of
710#   the type.
711# * __args__ is a tuple of all arguments used in subscripting,
712#   e.g., Dict[T, int].__args__ == (T, int).
713
714
715class _GenericAlias(_BaseGenericAlias, _root=True):
716    def __init__(self, origin, params, *, inst=True, name=None):
717        super().__init__(origin, inst=inst, name=name)
718        if not isinstance(params, tuple):
719            params = (params,)
720        self.__args__ = tuple(... if a is _TypingEllipsis else
721                              () if a is _TypingEmpty else
722                              a for a in params)
723        self.__parameters__ = _collect_type_vars(params)
724        if not name:
725            self.__module__ = origin.__module__
726
727    def __eq__(self, other):
728        if not isinstance(other, _GenericAlias):
729            return NotImplemented
730        return (self.__origin__ == other.__origin__
731                and self.__args__ == other.__args__)
732
733    def __hash__(self):
734        return hash((self.__origin__, self.__args__))
735
736    @_tp_cache
737    def __getitem__(self, params):
738        if self.__origin__ in (Generic, Protocol):
739            # Can't subscript Generic[...] or Protocol[...].
740            raise TypeError(f"Cannot subscript already-subscripted {self}")
741        if not isinstance(params, tuple):
742            params = (params,)
743        msg = "Parameters to generic types must be types."
744        params = tuple(_type_check(p, msg) for p in params)
745        _check_generic(self, params, len(self.__parameters__))
746
747        subst = dict(zip(self.__parameters__, params))
748        new_args = []
749        for arg in self.__args__:
750            if isinstance(arg, TypeVar):
751                arg = subst[arg]
752            elif isinstance(arg, (_GenericAlias, GenericAlias)):
753                subparams = arg.__parameters__
754                if subparams:
755                    subargs = tuple(subst[x] for x in subparams)
756                    arg = arg[subargs]
757            new_args.append(arg)
758        return self.copy_with(tuple(new_args))
759
760    def copy_with(self, params):
761        return self.__class__(self.__origin__, params, name=self._name, inst=self._inst)
762
763    def __repr__(self):
764        if self._name:
765            name = 'typing.' + self._name
766        else:
767            name = _type_repr(self.__origin__)
768        args = ", ".join([_type_repr(a) for a in self.__args__])
769        return f'{name}[{args}]'
770
771    def __reduce__(self):
772        if self._name:
773            origin = globals()[self._name]
774        else:
775            origin = self.__origin__
776        args = tuple(self.__args__)
777        if len(args) == 1 and not isinstance(args[0], tuple):
778            args, = args
779        return operator.getitem, (origin, args)
780
781    def __mro_entries__(self, bases):
782        if self._name:  # generic version of an ABC or built-in class
783            return super().__mro_entries__(bases)
784        if self.__origin__ is Generic:
785            if Protocol in bases:
786                return ()
787            i = bases.index(self)
788            for b in bases[i+1:]:
789                if isinstance(b, _BaseGenericAlias) and b is not self:
790                    return ()
791        return (self.__origin__,)
792
793
794# _nparams is the number of accepted parameters, e.g. 0 for Hashable,
795# 1 for List and 2 for Dict.  It may be -1 if variable number of
796# parameters are accepted (needs custom __getitem__).
797
798class _SpecialGenericAlias(_BaseGenericAlias, _root=True):
799    def __init__(self, origin, nparams, *, inst=True, name=None):
800        if name is None:
801            name = origin.__name__
802        super().__init__(origin, inst=inst, name=name)
803        self._nparams = nparams
804        if origin.__module__ == 'builtins':
805            self.__doc__ = f'A generic version of {origin.__qualname__}.'
806        else:
807            self.__doc__ = f'A generic version of {origin.__module__}.{origin.__qualname__}.'
808
809    @_tp_cache
810    def __getitem__(self, params):
811        if not isinstance(params, tuple):
812            params = (params,)
813        msg = "Parameters to generic types must be types."
814        params = tuple(_type_check(p, msg) for p in params)
815        _check_generic(self, params, self._nparams)
816        return self.copy_with(params)
817
818    def copy_with(self, params):
819        return _GenericAlias(self.__origin__, params,
820                             name=self._name, inst=self._inst)
821
822    def __repr__(self):
823        return 'typing.' + self._name
824
825    def __subclasscheck__(self, cls):
826        if isinstance(cls, _SpecialGenericAlias):
827            return issubclass(cls.__origin__, self.__origin__)
828        if not isinstance(cls, _GenericAlias):
829            return issubclass(cls, self.__origin__)
830        return super().__subclasscheck__(cls)
831
832    def __reduce__(self):
833        return self._name
834
835
836class _CallableGenericAlias(_GenericAlias, _root=True):
837    def __repr__(self):
838        assert self._name == 'Callable'
839        if len(self.__args__) == 2 and self.__args__[0] is Ellipsis:
840            return super().__repr__()
841        return (f'typing.Callable'
842                f'[[{", ".join([_type_repr(a) for a in self.__args__[:-1]])}], '
843                f'{_type_repr(self.__args__[-1])}]')
844
845    def __reduce__(self):
846        args = self.__args__
847        if not (len(args) == 2 and args[0] is ...):
848            args = list(args[:-1]), args[-1]
849        return operator.getitem, (Callable, args)
850
851
852class _CallableType(_SpecialGenericAlias, _root=True):
853    def copy_with(self, params):
854        return _CallableGenericAlias(self.__origin__, params,
855                                     name=self._name, inst=self._inst)
856
857    def __getitem__(self, params):
858        if not isinstance(params, tuple) or len(params) != 2:
859            raise TypeError("Callable must be used as "
860                            "Callable[[arg, ...], result].")
861        args, result = params
862        if args is Ellipsis:
863            params = (Ellipsis, result)
864        else:
865            if not isinstance(args, list):
866                raise TypeError(f"Callable[args, result]: args must be a list."
867                                f" Got {args}")
868            params = (tuple(args), result)
869        return self.__getitem_inner__(params)
870
871    @_tp_cache
872    def __getitem_inner__(self, params):
873        args, result = params
874        msg = "Callable[args, result]: result must be a type."
875        result = _type_check(result, msg)
876        if args is Ellipsis:
877            return self.copy_with((_TypingEllipsis, result))
878        msg = "Callable[[arg, ...], result]: each arg must be a type."
879        args = tuple(_type_check(arg, msg) for arg in args)
880        params = args + (result,)
881        return self.copy_with(params)
882
883
884class _TupleType(_SpecialGenericAlias, _root=True):
885    @_tp_cache
886    def __getitem__(self, params):
887        if params == ():
888            return self.copy_with((_TypingEmpty,))
889        if not isinstance(params, tuple):
890            params = (params,)
891        if len(params) == 2 and params[1] is ...:
892            msg = "Tuple[t, ...]: t must be a type."
893            p = _type_check(params[0], msg)
894            return self.copy_with((p, _TypingEllipsis))
895        msg = "Tuple[t0, t1, ...]: each t must be a type."
896        params = tuple(_type_check(p, msg) for p in params)
897        return self.copy_with(params)
898
899
900class _UnionGenericAlias(_GenericAlias, _root=True):
901    def copy_with(self, params):
902        return Union[params]
903
904    def __eq__(self, other):
905        if not isinstance(other, _UnionGenericAlias):
906            return NotImplemented
907        return set(self.__args__) == set(other.__args__)
908
909    def __hash__(self):
910        return hash(frozenset(self.__args__))
911
912    def __repr__(self):
913        args = self.__args__
914        if len(args) == 2:
915            if args[0] is type(None):
916                return f'typing.Optional[{_type_repr(args[1])}]'
917            elif args[1] is type(None):
918                return f'typing.Optional[{_type_repr(args[0])}]'
919        return super().__repr__()
920
921
922def _value_and_type_iter(parameters):
923    return ((p, type(p)) for p in parameters)
924
925
926class _LiteralGenericAlias(_GenericAlias, _root=True):
927
928    def __eq__(self, other):
929        if not isinstance(other, _LiteralGenericAlias):
930            return NotImplemented
931
932        return set(_value_and_type_iter(self.__args__)) == set(_value_and_type_iter(other.__args__))
933
934    def __hash__(self):
935        return hash(frozenset(_value_and_type_iter(self.__args__)))
936
937
938class Generic:
939    """Abstract base class for generic types.
940
941    A generic type is typically declared by inheriting from
942    this class parameterized with one or more type variables.
943    For example, a generic mapping type might be defined as::
944
945      class Mapping(Generic[KT, VT]):
946          def __getitem__(self, key: KT) -> VT:
947              ...
948          # Etc.
949
950    This class can then be used as follows::
951
952      def lookup_name(mapping: Mapping[KT, VT], key: KT, default: VT) -> VT:
953          try:
954              return mapping[key]
955          except KeyError:
956              return default
957    """
958    __slots__ = ()
959    _is_protocol = False
960
961    @_tp_cache
962    def __class_getitem__(cls, params):
963        if not isinstance(params, tuple):
964            params = (params,)
965        if not params and cls is not Tuple:
966            raise TypeError(
967                f"Parameter list to {cls.__qualname__}[...] cannot be empty")
968        msg = "Parameters to generic types must be types."
969        params = tuple(_type_check(p, msg) for p in params)
970        if cls in (Generic, Protocol):
971            # Generic and Protocol can only be subscripted with unique type variables.
972            if not all(isinstance(p, TypeVar) for p in params):
973                raise TypeError(
974                    f"Parameters to {cls.__name__}[...] must all be type variables")
975            if len(set(params)) != len(params):
976                raise TypeError(
977                    f"Parameters to {cls.__name__}[...] must all be unique")
978        else:
979            # Subscripting a regular Generic subclass.
980            _check_generic(cls, params, len(cls.__parameters__))
981        return _GenericAlias(cls, params)
982
983    def __init_subclass__(cls, *args, **kwargs):
984        super().__init_subclass__(*args, **kwargs)
985        tvars = []
986        if '__orig_bases__' in cls.__dict__:
987            error = Generic in cls.__orig_bases__
988        else:
989            error = Generic in cls.__bases__ and cls.__name__ != 'Protocol'
990        if error:
991            raise TypeError("Cannot inherit from plain Generic")
992        if '__orig_bases__' in cls.__dict__:
993            tvars = _collect_type_vars(cls.__orig_bases__)
994            # Look for Generic[T1, ..., Tn].
995            # If found, tvars must be a subset of it.
996            # If not found, tvars is it.
997            # Also check for and reject plain Generic,
998            # and reject multiple Generic[...].
999            gvars = None
1000            for base in cls.__orig_bases__:
1001                if (isinstance(base, _GenericAlias) and
1002                        base.__origin__ is Generic):
1003                    if gvars is not None:
1004                        raise TypeError(
1005                            "Cannot inherit from Generic[...] multiple types.")
1006                    gvars = base.__parameters__
1007            if gvars is not None:
1008                tvarset = set(tvars)
1009                gvarset = set(gvars)
1010                if not tvarset <= gvarset:
1011                    s_vars = ', '.join(str(t) for t in tvars if t not in gvarset)
1012                    s_args = ', '.join(str(g) for g in gvars)
1013                    raise TypeError(f"Some type variables ({s_vars}) are"
1014                                    f" not listed in Generic[{s_args}]")
1015                tvars = gvars
1016        cls.__parameters__ = tuple(tvars)
1017
1018
1019class _TypingEmpty:
1020    """Internal placeholder for () or []. Used by TupleMeta and CallableMeta
1021    to allow empty list/tuple in specific places, without allowing them
1022    to sneak in where prohibited.
1023    """
1024
1025
1026class _TypingEllipsis:
1027    """Internal placeholder for ... (ellipsis)."""
1028
1029
1030_TYPING_INTERNALS = ['__parameters__', '__orig_bases__',  '__orig_class__',
1031                     '_is_protocol', '_is_runtime_protocol']
1032
1033_SPECIAL_NAMES = ['__abstractmethods__', '__annotations__', '__dict__', '__doc__',
1034                  '__init__', '__module__', '__new__', '__slots__',
1035                  '__subclasshook__', '__weakref__', '__class_getitem__']
1036
1037# These special attributes will be not collected as protocol members.
1038EXCLUDED_ATTRIBUTES = _TYPING_INTERNALS + _SPECIAL_NAMES + ['_MutableMapping__marker']
1039
1040
1041def _get_protocol_attrs(cls):
1042    """Collect protocol members from a protocol class objects.
1043
1044    This includes names actually defined in the class dictionary, as well
1045    as names that appear in annotations. Special names (above) are skipped.
1046    """
1047    attrs = set()
1048    for base in cls.__mro__[:-1]:  # without object
1049        if base.__name__ in ('Protocol', 'Generic'):
1050            continue
1051        annotations = getattr(base, '__annotations__', {})
1052        for attr in list(base.__dict__.keys()) + list(annotations.keys()):
1053            if not attr.startswith('_abc_') and attr not in EXCLUDED_ATTRIBUTES:
1054                attrs.add(attr)
1055    return attrs
1056
1057
1058def _is_callable_members_only(cls):
1059    # PEP 544 prohibits using issubclass() with protocols that have non-method members.
1060    return all(callable(getattr(cls, attr, None)) for attr in _get_protocol_attrs(cls))
1061
1062
1063def _no_init(self, *args, **kwargs):
1064    if type(self)._is_protocol:
1065        raise TypeError('Protocols cannot be instantiated')
1066
1067
1068def _allow_reckless_class_cheks():
1069    """Allow instance and class checks for special stdlib modules.
1070
1071    The abc and functools modules indiscriminately call isinstance() and
1072    issubclass() on the whole MRO of a user class, which may contain protocols.
1073    """
1074    try:
1075        return sys._getframe(3).f_globals['__name__'] in ['abc', 'functools']
1076    except (AttributeError, ValueError):  # For platforms without _getframe().
1077        return True
1078
1079
1080_PROTO_WHITELIST = {
1081    'collections.abc': [
1082        'Callable', 'Awaitable', 'Iterable', 'Iterator', 'AsyncIterable',
1083        'Hashable', 'Sized', 'Container', 'Collection', 'Reversible',
1084    ],
1085    'contextlib': ['AbstractContextManager', 'AbstractAsyncContextManager'],
1086}
1087
1088
1089class _ProtocolMeta(ABCMeta):
1090    # This metaclass is really unfortunate and exists only because of
1091    # the lack of __instancehook__.
1092    def __instancecheck__(cls, instance):
1093        # We need this method for situations where attributes are
1094        # assigned in __init__.
1095        if ((not getattr(cls, '_is_protocol', False) or
1096                _is_callable_members_only(cls)) and
1097                issubclass(instance.__class__, cls)):
1098            return True
1099        if cls._is_protocol:
1100            if all(hasattr(instance, attr) and
1101                    # All *methods* can be blocked by setting them to None.
1102                    (not callable(getattr(cls, attr, None)) or
1103                     getattr(instance, attr) is not None)
1104                    for attr in _get_protocol_attrs(cls)):
1105                return True
1106        return super().__instancecheck__(instance)
1107
1108
1109class Protocol(Generic, metaclass=_ProtocolMeta):
1110    """Base class for protocol classes.
1111
1112    Protocol classes are defined as::
1113
1114        class Proto(Protocol):
1115            def meth(self) -> int:
1116                ...
1117
1118    Such classes are primarily used with static type checkers that recognize
1119    structural subtyping (static duck-typing), for example::
1120
1121        class C:
1122            def meth(self) -> int:
1123                return 0
1124
1125        def func(x: Proto) -> int:
1126            return x.meth()
1127
1128        func(C())  # Passes static type check
1129
1130    See PEP 544 for details. Protocol classes decorated with
1131    @typing.runtime_checkable act as simple-minded runtime protocols that check
1132    only the presence of given attributes, ignoring their type signatures.
1133    Protocol classes can be generic, they are defined as::
1134
1135        class GenProto(Protocol[T]):
1136            def meth(self) -> T:
1137                ...
1138    """
1139    __slots__ = ()
1140    _is_protocol = True
1141    _is_runtime_protocol = False
1142
1143    def __init_subclass__(cls, *args, **kwargs):
1144        super().__init_subclass__(*args, **kwargs)
1145
1146        # Determine if this is a protocol or a concrete subclass.
1147        if not cls.__dict__.get('_is_protocol', False):
1148            cls._is_protocol = any(b is Protocol for b in cls.__bases__)
1149
1150        # Set (or override) the protocol subclass hook.
1151        def _proto_hook(other):
1152            if not cls.__dict__.get('_is_protocol', False):
1153                return NotImplemented
1154
1155            # First, perform various sanity checks.
1156            if not getattr(cls, '_is_runtime_protocol', False):
1157                if _allow_reckless_class_cheks():
1158                    return NotImplemented
1159                raise TypeError("Instance and class checks can only be used with"
1160                                " @runtime_checkable protocols")
1161            if not _is_callable_members_only(cls):
1162                if _allow_reckless_class_cheks():
1163                    return NotImplemented
1164                raise TypeError("Protocols with non-method members"
1165                                " don't support issubclass()")
1166            if not isinstance(other, type):
1167                # Same error message as for issubclass(1, int).
1168                raise TypeError('issubclass() arg 1 must be a class')
1169
1170            # Second, perform the actual structural compatibility check.
1171            for attr in _get_protocol_attrs(cls):
1172                for base in other.__mro__:
1173                    # Check if the members appears in the class dictionary...
1174                    if attr in base.__dict__:
1175                        if base.__dict__[attr] is None:
1176                            return NotImplemented
1177                        break
1178
1179                    # ...or in annotations, if it is a sub-protocol.
1180                    annotations = getattr(base, '__annotations__', {})
1181                    if (isinstance(annotations, collections.abc.Mapping) and
1182                            attr in annotations and
1183                            issubclass(other, Generic) and other._is_protocol):
1184                        break
1185                else:
1186                    return NotImplemented
1187            return True
1188
1189        if '__subclasshook__' not in cls.__dict__:
1190            cls.__subclasshook__ = _proto_hook
1191
1192        # We have nothing more to do for non-protocols...
1193        if not cls._is_protocol:
1194            return
1195
1196        # ... otherwise check consistency of bases, and prohibit instantiation.
1197        for base in cls.__bases__:
1198            if not (base in (object, Generic) or
1199                    base.__module__ in _PROTO_WHITELIST and
1200                    base.__name__ in _PROTO_WHITELIST[base.__module__] or
1201                    issubclass(base, Generic) and base._is_protocol):
1202                raise TypeError('Protocols can only inherit from other'
1203                                ' protocols, got %r' % base)
1204        cls.__init__ = _no_init
1205
1206
1207class _AnnotatedAlias(_GenericAlias, _root=True):
1208    """Runtime representation of an annotated type.
1209
1210    At its core 'Annotated[t, dec1, dec2, ...]' is an alias for the type 't'
1211    with extra annotations. The alias behaves like a normal typing alias,
1212    instantiating is the same as instantiating the underlying type, binding
1213    it to types is also the same.
1214    """
1215    def __init__(self, origin, metadata):
1216        if isinstance(origin, _AnnotatedAlias):
1217            metadata = origin.__metadata__ + metadata
1218            origin = origin.__origin__
1219        super().__init__(origin, origin)
1220        self.__metadata__ = metadata
1221
1222    def copy_with(self, params):
1223        assert len(params) == 1
1224        new_type = params[0]
1225        return _AnnotatedAlias(new_type, self.__metadata__)
1226
1227    def __repr__(self):
1228        return "typing.Annotated[{}, {}]".format(
1229            _type_repr(self.__origin__),
1230            ", ".join(repr(a) for a in self.__metadata__)
1231        )
1232
1233    def __reduce__(self):
1234        return operator.getitem, (
1235            Annotated, (self.__origin__,) + self.__metadata__
1236        )
1237
1238    def __eq__(self, other):
1239        if not isinstance(other, _AnnotatedAlias):
1240            return NotImplemented
1241        return (self.__origin__ == other.__origin__
1242                and self.__metadata__ == other.__metadata__)
1243
1244    def __hash__(self):
1245        return hash((self.__origin__, self.__metadata__))
1246
1247
1248class Annotated:
1249    """Add context specific metadata to a type.
1250
1251    Example: Annotated[int, runtime_check.Unsigned] indicates to the
1252    hypothetical runtime_check module that this type is an unsigned int.
1253    Every other consumer of this type can ignore this metadata and treat
1254    this type as int.
1255
1256    The first argument to Annotated must be a valid type.
1257
1258    Details:
1259
1260    - It's an error to call `Annotated` with less than two arguments.
1261    - Nested Annotated are flattened::
1262
1263        Annotated[Annotated[T, Ann1, Ann2], Ann3] == Annotated[T, Ann1, Ann2, Ann3]
1264
1265    - Instantiating an annotated type is equivalent to instantiating the
1266    underlying type::
1267
1268        Annotated[C, Ann1](5) == C(5)
1269
1270    - Annotated can be used as a generic type alias::
1271
1272        Optimized = Annotated[T, runtime.Optimize()]
1273        Optimized[int] == Annotated[int, runtime.Optimize()]
1274
1275        OptimizedList = Annotated[List[T], runtime.Optimize()]
1276        OptimizedList[int] == Annotated[List[int], runtime.Optimize()]
1277    """
1278
1279    __slots__ = ()
1280
1281    def __new__(cls, *args, **kwargs):
1282        raise TypeError("Type Annotated cannot be instantiated.")
1283
1284    @_tp_cache
1285    def __class_getitem__(cls, params):
1286        if not isinstance(params, tuple) or len(params) < 2:
1287            raise TypeError("Annotated[...] should be used "
1288                            "with at least two arguments (a type and an "
1289                            "annotation).")
1290        msg = "Annotated[t, ...]: t must be a type."
1291        origin = _type_check(params[0], msg)
1292        metadata = tuple(params[1:])
1293        return _AnnotatedAlias(origin, metadata)
1294
1295    def __init_subclass__(cls, *args, **kwargs):
1296        raise TypeError(
1297            "Cannot subclass {}.Annotated".format(cls.__module__)
1298        )
1299
1300
1301def runtime_checkable(cls):
1302    """Mark a protocol class as a runtime protocol.
1303
1304    Such protocol can be used with isinstance() and issubclass().
1305    Raise TypeError if applied to a non-protocol class.
1306    This allows a simple-minded structural check very similar to
1307    one trick ponies in collections.abc such as Iterable.
1308    For example::
1309
1310        @runtime_checkable
1311        class Closable(Protocol):
1312            def close(self): ...
1313
1314        assert isinstance(open('/some/file'), Closable)
1315
1316    Warning: this will check only the presence of the required methods,
1317    not their type signatures!
1318    """
1319    if not issubclass(cls, Generic) or not cls._is_protocol:
1320        raise TypeError('@runtime_checkable can be only applied to protocol classes,'
1321                        ' got %r' % cls)
1322    cls._is_runtime_protocol = True
1323    return cls
1324
1325
1326def cast(typ, val):
1327    """Cast a value to a type.
1328
1329    This returns the value unchanged.  To the type checker this
1330    signals that the return value has the designated type, but at
1331    runtime we intentionally don't check anything (we want this
1332    to be as fast as possible).
1333    """
1334    return val
1335
1336
1337def _get_defaults(func):
1338    """Internal helper to extract the default arguments, by name."""
1339    try:
1340        code = func.__code__
1341    except AttributeError:
1342        # Some built-in functions don't have __code__, __defaults__, etc.
1343        return {}
1344    pos_count = code.co_argcount
1345    arg_names = code.co_varnames
1346    arg_names = arg_names[:pos_count]
1347    defaults = func.__defaults__ or ()
1348    kwdefaults = func.__kwdefaults__
1349    res = dict(kwdefaults) if kwdefaults else {}
1350    pos_offset = pos_count - len(defaults)
1351    for name, value in zip(arg_names[pos_offset:], defaults):
1352        assert name not in res
1353        res[name] = value
1354    return res
1355
1356
1357_allowed_types = (types.FunctionType, types.BuiltinFunctionType,
1358                  types.MethodType, types.ModuleType,
1359                  WrapperDescriptorType, MethodWrapperType, MethodDescriptorType)
1360
1361
1362def get_type_hints(obj, globalns=None, localns=None, include_extras=False):
1363    """Return type hints for an object.
1364
1365    This is often the same as obj.__annotations__, but it handles
1366    forward references encoded as string literals, adds Optional[t] if a
1367    default value equal to None is set and recursively replaces all
1368    'Annotated[T, ...]' with 'T' (unless 'include_extras=True').
1369
1370    The argument may be a module, class, method, or function. The annotations
1371    are returned as a dictionary. For classes, annotations include also
1372    inherited members.
1373
1374    TypeError is raised if the argument is not of a type that can contain
1375    annotations, and an empty dictionary is returned if no annotations are
1376    present.
1377
1378    BEWARE -- the behavior of globalns and localns is counterintuitive
1379    (unless you are familiar with how eval() and exec() work).  The
1380    search order is locals first, then globals.
1381
1382    - If no dict arguments are passed, an attempt is made to use the
1383      globals from obj (or the respective module's globals for classes),
1384      and these are also used as the locals.  If the object does not appear
1385      to have globals, an empty dictionary is used.
1386
1387    - If one dict argument is passed, it is used for both globals and
1388      locals.
1389
1390    - If two dict arguments are passed, they specify globals and
1391      locals, respectively.
1392    """
1393
1394    if getattr(obj, '__no_type_check__', None):
1395        return {}
1396    # Classes require a special treatment.
1397    if isinstance(obj, type):
1398        hints = {}
1399        for base in reversed(obj.__mro__):
1400            if globalns is None:
1401                base_globals = sys.modules[base.__module__].__dict__
1402            else:
1403                base_globals = globalns
1404            ann = base.__dict__.get('__annotations__', {})
1405            for name, value in ann.items():
1406                if value is None:
1407                    value = type(None)
1408                if isinstance(value, str):
1409                    value = ForwardRef(value, is_argument=False)
1410                value = _eval_type(value, base_globals, localns)
1411                hints[name] = value
1412        return hints if include_extras else {k: _strip_annotations(t) for k, t in hints.items()}
1413
1414    if globalns is None:
1415        if isinstance(obj, types.ModuleType):
1416            globalns = obj.__dict__
1417        else:
1418            nsobj = obj
1419            # Find globalns for the unwrapped object.
1420            while hasattr(nsobj, '__wrapped__'):
1421                nsobj = nsobj.__wrapped__
1422            globalns = getattr(nsobj, '__globals__', {})
1423        if localns is None:
1424            localns = globalns
1425    elif localns is None:
1426        localns = globalns
1427    hints = getattr(obj, '__annotations__', None)
1428    if hints is None:
1429        # Return empty annotations for something that _could_ have them.
1430        if isinstance(obj, _allowed_types):
1431            return {}
1432        else:
1433            raise TypeError('{!r} is not a module, class, method, '
1434                            'or function.'.format(obj))
1435    defaults = _get_defaults(obj)
1436    hints = dict(hints)
1437    for name, value in hints.items():
1438        if value is None:
1439            value = type(None)
1440        if isinstance(value, str):
1441            value = ForwardRef(value)
1442        value = _eval_type(value, globalns, localns)
1443        if name in defaults and defaults[name] is None:
1444            value = Optional[value]
1445        hints[name] = value
1446    return hints if include_extras else {k: _strip_annotations(t) for k, t in hints.items()}
1447
1448
1449def _strip_annotations(t):
1450    """Strips the annotations from a given type.
1451    """
1452    if isinstance(t, _AnnotatedAlias):
1453        return _strip_annotations(t.__origin__)
1454    if isinstance(t, _GenericAlias):
1455        stripped_args = tuple(_strip_annotations(a) for a in t.__args__)
1456        if stripped_args == t.__args__:
1457            return t
1458        return t.copy_with(stripped_args)
1459    if isinstance(t, GenericAlias):
1460        stripped_args = tuple(_strip_annotations(a) for a in t.__args__)
1461        if stripped_args == t.__args__:
1462            return t
1463        return GenericAlias(t.__origin__, stripped_args)
1464    return t
1465
1466
1467def get_origin(tp):
1468    """Get the unsubscripted version of a type.
1469
1470    This supports generic types, Callable, Tuple, Union, Literal, Final, ClassVar
1471    and Annotated. Return None for unsupported types. Examples::
1472
1473        get_origin(Literal[42]) is Literal
1474        get_origin(int) is None
1475        get_origin(ClassVar[int]) is ClassVar
1476        get_origin(Generic) is Generic
1477        get_origin(Generic[T]) is Generic
1478        get_origin(Union[T, int]) is Union
1479        get_origin(List[Tuple[T, T]][int]) == list
1480    """
1481    if isinstance(tp, _AnnotatedAlias):
1482        return Annotated
1483    if isinstance(tp, (_BaseGenericAlias, GenericAlias)):
1484        return tp.__origin__
1485    if tp is Generic:
1486        return Generic
1487    return None
1488
1489
1490def get_args(tp):
1491    """Get type arguments with all substitutions performed.
1492
1493    For unions, basic simplifications used by Union constructor are performed.
1494    Examples::
1495        get_args(Dict[str, int]) == (str, int)
1496        get_args(int) == ()
1497        get_args(Union[int, Union[T, int], str][int]) == (int, str)
1498        get_args(Union[int, Tuple[T, int]][str]) == (int, Tuple[str, int])
1499        get_args(Callable[[], T][int]) == ([], int)
1500    """
1501    if isinstance(tp, _AnnotatedAlias):
1502        return (tp.__origin__,) + tp.__metadata__
1503    if isinstance(tp, _GenericAlias):
1504        res = tp.__args__
1505        if tp.__origin__ is collections.abc.Callable and res[0] is not Ellipsis:
1506            res = (list(res[:-1]), res[-1])
1507        return res
1508    if isinstance(tp, GenericAlias):
1509        return tp.__args__
1510    return ()
1511
1512
1513def no_type_check(arg):
1514    """Decorator to indicate that annotations are not type hints.
1515
1516    The argument must be a class or function; if it is a class, it
1517    applies recursively to all methods and classes defined in that class
1518    (but not to methods defined in its superclasses or subclasses).
1519
1520    This mutates the function(s) or class(es) in place.
1521    """
1522    if isinstance(arg, type):
1523        arg_attrs = arg.__dict__.copy()
1524        for attr, val in arg.__dict__.items():
1525            if val in arg.__bases__ + (arg,):
1526                arg_attrs.pop(attr)
1527        for obj in arg_attrs.values():
1528            if isinstance(obj, types.FunctionType):
1529                obj.__no_type_check__ = True
1530            if isinstance(obj, type):
1531                no_type_check(obj)
1532    try:
1533        arg.__no_type_check__ = True
1534    except TypeError:  # built-in classes
1535        pass
1536    return arg
1537
1538
1539def no_type_check_decorator(decorator):
1540    """Decorator to give another decorator the @no_type_check effect.
1541
1542    This wraps the decorator with something that wraps the decorated
1543    function in @no_type_check.
1544    """
1545
1546    @functools.wraps(decorator)
1547    def wrapped_decorator(*args, **kwds):
1548        func = decorator(*args, **kwds)
1549        func = no_type_check(func)
1550        return func
1551
1552    return wrapped_decorator
1553
1554
1555def _overload_dummy(*args, **kwds):
1556    """Helper for @overload to raise when called."""
1557    raise NotImplementedError(
1558        "You should not call an overloaded function. "
1559        "A series of @overload-decorated functions "
1560        "outside a stub module should always be followed "
1561        "by an implementation that is not @overload-ed.")
1562
1563
1564def overload(func):
1565    """Decorator for overloaded functions/methods.
1566
1567    In a stub file, place two or more stub definitions for the same
1568    function in a row, each decorated with @overload.  For example:
1569
1570      @overload
1571      def utf8(value: None) -> None: ...
1572      @overload
1573      def utf8(value: bytes) -> bytes: ...
1574      @overload
1575      def utf8(value: str) -> bytes: ...
1576
1577    In a non-stub file (i.e. a regular .py file), do the same but
1578    follow it with an implementation.  The implementation should *not*
1579    be decorated with @overload.  For example:
1580
1581      @overload
1582      def utf8(value: None) -> None: ...
1583      @overload
1584      def utf8(value: bytes) -> bytes: ...
1585      @overload
1586      def utf8(value: str) -> bytes: ...
1587      def utf8(value):
1588          # implementation goes here
1589    """
1590    return _overload_dummy
1591
1592
1593def final(f):
1594    """A decorator to indicate final methods and final classes.
1595
1596    Use this decorator to indicate to type checkers that the decorated
1597    method cannot be overridden, and decorated class cannot be subclassed.
1598    For example:
1599
1600      class Base:
1601          @final
1602          def done(self) -> None:
1603              ...
1604      class Sub(Base):
1605          def done(self) -> None:  # Error reported by type checker
1606                ...
1607
1608      @final
1609      class Leaf:
1610          ...
1611      class Other(Leaf):  # Error reported by type checker
1612          ...
1613
1614    There is no runtime checking of these properties.
1615    """
1616    return f
1617
1618
1619# Some unconstrained type variables.  These are used by the container types.
1620# (These are not for export.)
1621T = TypeVar('T')  # Any type.
1622KT = TypeVar('KT')  # Key type.
1623VT = TypeVar('VT')  # Value type.
1624T_co = TypeVar('T_co', covariant=True)  # Any type covariant containers.
1625V_co = TypeVar('V_co', covariant=True)  # Any type covariant containers.
1626VT_co = TypeVar('VT_co', covariant=True)  # Value type covariant containers.
1627T_contra = TypeVar('T_contra', contravariant=True)  # Ditto contravariant.
1628# Internal type variable used for Type[].
1629CT_co = TypeVar('CT_co', covariant=True, bound=type)
1630
1631# A useful type variable with constraints.  This represents string types.
1632# (This one *is* for export!)
1633AnyStr = TypeVar('AnyStr', bytes, str)
1634
1635
1636# Various ABCs mimicking those in collections.abc.
1637_alias = _SpecialGenericAlias
1638
1639Hashable = _alias(collections.abc.Hashable, 0)  # Not generic.
1640Awaitable = _alias(collections.abc.Awaitable, 1)
1641Coroutine = _alias(collections.abc.Coroutine, 3)
1642AsyncIterable = _alias(collections.abc.AsyncIterable, 1)
1643AsyncIterator = _alias(collections.abc.AsyncIterator, 1)
1644Iterable = _alias(collections.abc.Iterable, 1)
1645Iterator = _alias(collections.abc.Iterator, 1)
1646Reversible = _alias(collections.abc.Reversible, 1)
1647Sized = _alias(collections.abc.Sized, 0)  # Not generic.
1648Container = _alias(collections.abc.Container, 1)
1649Collection = _alias(collections.abc.Collection, 1)
1650Callable = _CallableType(collections.abc.Callable, 2)
1651Callable.__doc__ = \
1652    """Callable type; Callable[[int], str] is a function of (int) -> str.
1653
1654    The subscription syntax must always be used with exactly two
1655    values: the argument list and the return type.  The argument list
1656    must be a list of types or ellipsis; the return type must be a single type.
1657
1658    There is no syntax to indicate optional or keyword arguments,
1659    such function types are rarely used as callback types.
1660    """
1661AbstractSet = _alias(collections.abc.Set, 1, name='AbstractSet')
1662MutableSet = _alias(collections.abc.MutableSet, 1)
1663# NOTE: Mapping is only covariant in the value type.
1664Mapping = _alias(collections.abc.Mapping, 2)
1665MutableMapping = _alias(collections.abc.MutableMapping, 2)
1666Sequence = _alias(collections.abc.Sequence, 1)
1667MutableSequence = _alias(collections.abc.MutableSequence, 1)
1668ByteString = _alias(collections.abc.ByteString, 0)  # Not generic
1669# Tuple accepts variable number of parameters.
1670Tuple = _TupleType(tuple, -1, inst=False, name='Tuple')
1671Tuple.__doc__ = \
1672    """Tuple type; Tuple[X, Y] is the cross-product type of X and Y.
1673
1674    Example: Tuple[T1, T2] is a tuple of two elements corresponding
1675    to type variables T1 and T2.  Tuple[int, float, str] is a tuple
1676    of an int, a float and a string.
1677
1678    To specify a variable-length tuple of homogeneous type, use Tuple[T, ...].
1679    """
1680List = _alias(list, 1, inst=False, name='List')
1681Deque = _alias(collections.deque, 1, name='Deque')
1682Set = _alias(set, 1, inst=False, name='Set')
1683FrozenSet = _alias(frozenset, 1, inst=False, name='FrozenSet')
1684MappingView = _alias(collections.abc.MappingView, 1)
1685KeysView = _alias(collections.abc.KeysView, 1)
1686ItemsView = _alias(collections.abc.ItemsView, 2)
1687ValuesView = _alias(collections.abc.ValuesView, 1)
1688ContextManager = _alias(contextlib.AbstractContextManager, 1, name='ContextManager')
1689AsyncContextManager = _alias(contextlib.AbstractAsyncContextManager, 1, name='AsyncContextManager')
1690Dict = _alias(dict, 2, inst=False, name='Dict')
1691DefaultDict = _alias(collections.defaultdict, 2, name='DefaultDict')
1692OrderedDict = _alias(collections.OrderedDict, 2)
1693Counter = _alias(collections.Counter, 1)
1694ChainMap = _alias(collections.ChainMap, 2)
1695Generator = _alias(collections.abc.Generator, 3)
1696AsyncGenerator = _alias(collections.abc.AsyncGenerator, 2)
1697Type = _alias(type, 1, inst=False, name='Type')
1698Type.__doc__ = \
1699    """A special construct usable to annotate class objects.
1700
1701    For example, suppose we have the following classes::
1702
1703      class User: ...  # Abstract base for User classes
1704      class BasicUser(User): ...
1705      class ProUser(User): ...
1706      class TeamUser(User): ...
1707
1708    And a function that takes a class argument that's a subclass of
1709    User and returns an instance of the corresponding class::
1710
1711      U = TypeVar('U', bound=User)
1712      def new_user(user_class: Type[U]) -> U:
1713          user = user_class()
1714          # (Here we could write the user object to a database)
1715          return user
1716
1717      joe = new_user(BasicUser)
1718
1719    At this point the type checker knows that joe has type BasicUser.
1720    """
1721
1722
1723@runtime_checkable
1724class SupportsInt(Protocol):
1725    """An ABC with one abstract method __int__."""
1726    __slots__ = ()
1727
1728    @abstractmethod
1729    def __int__(self) -> int:
1730        pass
1731
1732
1733@runtime_checkable
1734class SupportsFloat(Protocol):
1735    """An ABC with one abstract method __float__."""
1736    __slots__ = ()
1737
1738    @abstractmethod
1739    def __float__(self) -> float:
1740        pass
1741
1742
1743@runtime_checkable
1744class SupportsComplex(Protocol):
1745    """An ABC with one abstract method __complex__."""
1746    __slots__ = ()
1747
1748    @abstractmethod
1749    def __complex__(self) -> complex:
1750        pass
1751
1752
1753@runtime_checkable
1754class SupportsBytes(Protocol):
1755    """An ABC with one abstract method __bytes__."""
1756    __slots__ = ()
1757
1758    @abstractmethod
1759    def __bytes__(self) -> bytes:
1760        pass
1761
1762
1763@runtime_checkable
1764class SupportsIndex(Protocol):
1765    """An ABC with one abstract method __index__."""
1766    __slots__ = ()
1767
1768    @abstractmethod
1769    def __index__(self) -> int:
1770        pass
1771
1772
1773@runtime_checkable
1774class SupportsAbs(Protocol[T_co]):
1775    """An ABC with one abstract method __abs__ that is covariant in its return type."""
1776    __slots__ = ()
1777
1778    @abstractmethod
1779    def __abs__(self) -> T_co:
1780        pass
1781
1782
1783@runtime_checkable
1784class SupportsRound(Protocol[T_co]):
1785    """An ABC with one abstract method __round__ that is covariant in its return type."""
1786    __slots__ = ()
1787
1788    @abstractmethod
1789    def __round__(self, ndigits: int = 0) -> T_co:
1790        pass
1791
1792
1793def _make_nmtuple(name, types, module, defaults = ()):
1794    fields = [n for n, t in types]
1795    types = {n: _type_check(t, f"field {n} annotation must be a type")
1796             for n, t in types}
1797    nm_tpl = collections.namedtuple(name, fields,
1798                                    defaults=defaults, module=module)
1799    nm_tpl.__annotations__ = nm_tpl.__new__.__annotations__ = types
1800    return nm_tpl
1801
1802
1803# attributes prohibited to set in NamedTuple class syntax
1804_prohibited = frozenset({'__new__', '__init__', '__slots__', '__getnewargs__',
1805                         '_fields', '_field_defaults',
1806                         '_make', '_replace', '_asdict', '_source'})
1807
1808_special = frozenset({'__module__', '__name__', '__annotations__'})
1809
1810
1811class NamedTupleMeta(type):
1812
1813    def __new__(cls, typename, bases, ns):
1814        assert bases[0] is _NamedTuple
1815        types = ns.get('__annotations__', {})
1816        default_names = []
1817        for field_name in types:
1818            if field_name in ns:
1819                default_names.append(field_name)
1820            elif default_names:
1821                raise TypeError(f"Non-default namedtuple field {field_name} "
1822                                f"cannot follow default field"
1823                                f"{'s' if len(default_names) > 1 else ''} "
1824                                f"{', '.join(default_names)}")
1825        nm_tpl = _make_nmtuple(typename, types.items(),
1826                               defaults=[ns[n] for n in default_names],
1827                               module=ns['__module__'])
1828        # update from user namespace without overriding special namedtuple attributes
1829        for key in ns:
1830            if key in _prohibited:
1831                raise AttributeError("Cannot overwrite NamedTuple attribute " + key)
1832            elif key not in _special and key not in nm_tpl._fields:
1833                setattr(nm_tpl, key, ns[key])
1834        return nm_tpl
1835
1836
1837def NamedTuple(typename, fields=None, /, **kwargs):
1838    """Typed version of namedtuple.
1839
1840    Usage in Python versions >= 3.6::
1841
1842        class Employee(NamedTuple):
1843            name: str
1844            id: int
1845
1846    This is equivalent to::
1847
1848        Employee = collections.namedtuple('Employee', ['name', 'id'])
1849
1850    The resulting class has an extra __annotations__ attribute, giving a
1851    dict that maps field names to types.  (The field names are also in
1852    the _fields attribute, which is part of the namedtuple API.)
1853    Alternative equivalent keyword syntax is also accepted::
1854
1855        Employee = NamedTuple('Employee', name=str, id=int)
1856
1857    In Python versions <= 3.5 use::
1858
1859        Employee = NamedTuple('Employee', [('name', str), ('id', int)])
1860    """
1861    if fields is None:
1862        fields = kwargs.items()
1863    elif kwargs:
1864        raise TypeError("Either list of fields or keywords"
1865                        " can be provided to NamedTuple, not both")
1866    try:
1867        module = sys._getframe(1).f_globals.get('__name__', '__main__')
1868    except (AttributeError, ValueError):
1869        module = None
1870    return _make_nmtuple(typename, fields, module=module)
1871
1872_NamedTuple = type.__new__(NamedTupleMeta, 'NamedTuple', (), {})
1873
1874def _namedtuple_mro_entries(bases):
1875    if len(bases) > 1:
1876        raise TypeError("Multiple inheritance with NamedTuple is not supported")
1877    assert bases[0] is NamedTuple
1878    return (_NamedTuple,)
1879
1880NamedTuple.__mro_entries__ = _namedtuple_mro_entries
1881
1882
1883class _TypedDictMeta(type):
1884    def __new__(cls, name, bases, ns, total=True):
1885        """Create new typed dict class object.
1886
1887        This method is called when TypedDict is subclassed,
1888        or when TypedDict is instantiated. This way
1889        TypedDict supports all three syntax forms described in its docstring.
1890        Subclasses and instances of TypedDict return actual dictionaries.
1891        """
1892        for base in bases:
1893            if type(base) is not _TypedDictMeta:
1894                raise TypeError('cannot inherit from both a TypedDict type '
1895                                'and a non-TypedDict base class')
1896        tp_dict = type.__new__(_TypedDictMeta, name, (dict,), ns)
1897
1898        annotations = {}
1899        own_annotations = ns.get('__annotations__', {})
1900        own_annotation_keys = set(own_annotations.keys())
1901        msg = "TypedDict('Name', {f0: t0, f1: t1, ...}); each t must be a type"
1902        own_annotations = {
1903            n: _type_check(tp, msg) for n, tp in own_annotations.items()
1904        }
1905        required_keys = set()
1906        optional_keys = set()
1907
1908        for base in bases:
1909            annotations.update(base.__dict__.get('__annotations__', {}))
1910            required_keys.update(base.__dict__.get('__required_keys__', ()))
1911            optional_keys.update(base.__dict__.get('__optional_keys__', ()))
1912
1913        annotations.update(own_annotations)
1914        if total:
1915            required_keys.update(own_annotation_keys)
1916        else:
1917            optional_keys.update(own_annotation_keys)
1918
1919        tp_dict.__annotations__ = annotations
1920        tp_dict.__required_keys__ = frozenset(required_keys)
1921        tp_dict.__optional_keys__ = frozenset(optional_keys)
1922        if not hasattr(tp_dict, '__total__'):
1923            tp_dict.__total__ = total
1924        return tp_dict
1925
1926    __call__ = dict  # static method
1927
1928    def __subclasscheck__(cls, other):
1929        # Typed dicts are only for static structural subtyping.
1930        raise TypeError('TypedDict does not support instance and class checks')
1931
1932    __instancecheck__ = __subclasscheck__
1933
1934
1935def TypedDict(typename, fields=None, /, *, total=True, **kwargs):
1936    """A simple typed namespace. At runtime it is equivalent to a plain dict.
1937
1938    TypedDict creates a dictionary type that expects all of its
1939    instances to have a certain set of keys, where each key is
1940    associated with a value of a consistent type. This expectation
1941    is not checked at runtime but is only enforced by type checkers.
1942    Usage::
1943
1944        class Point2D(TypedDict):
1945            x: int
1946            y: int
1947            label: str
1948
1949        a: Point2D = {'x': 1, 'y': 2, 'label': 'good'}  # OK
1950        b: Point2D = {'z': 3, 'label': 'bad'}           # Fails type check
1951
1952        assert Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first')
1953
1954    The type info can be accessed via the Point2D.__annotations__ dict, and
1955    the Point2D.__required_keys__ and Point2D.__optional_keys__ frozensets.
1956    TypedDict supports two additional equivalent forms::
1957
1958        Point2D = TypedDict('Point2D', x=int, y=int, label=str)
1959        Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str})
1960
1961    By default, all keys must be present in a TypedDict. It is possible
1962    to override this by specifying totality.
1963    Usage::
1964
1965        class point2D(TypedDict, total=False):
1966            x: int
1967            y: int
1968
1969    This means that a point2D TypedDict can have any of the keys omitted.A type
1970    checker is only expected to support a literal False or True as the value of
1971    the total argument. True is the default, and makes all items defined in the
1972    class body be required.
1973
1974    The class syntax is only supported in Python 3.6+, while two other
1975    syntax forms work for Python 2.7 and 3.2+
1976    """
1977    if fields is None:
1978        fields = kwargs
1979    elif kwargs:
1980        raise TypeError("TypedDict takes either a dict or keyword arguments,"
1981                        " but not both")
1982
1983    ns = {'__annotations__': dict(fields), '__total__': total}
1984    try:
1985        # Setting correct module is necessary to make typed dict classes pickleable.
1986        ns['__module__'] = sys._getframe(1).f_globals.get('__name__', '__main__')
1987    except (AttributeError, ValueError):
1988        pass
1989
1990    return _TypedDictMeta(typename, (), ns)
1991
1992_TypedDict = type.__new__(_TypedDictMeta, 'TypedDict', (), {})
1993TypedDict.__mro_entries__ = lambda bases: (_TypedDict,)
1994
1995
1996def NewType(name, tp):
1997    """NewType creates simple unique types with almost zero
1998    runtime overhead. NewType(name, tp) is considered a subtype of tp
1999    by static type checkers. At runtime, NewType(name, tp) returns
2000    a dummy function that simply returns its argument. Usage::
2001
2002        UserId = NewType('UserId', int)
2003
2004        def name_by_id(user_id: UserId) -> str:
2005            ...
2006
2007        UserId('user')          # Fails type check
2008
2009        name_by_id(42)          # Fails type check
2010        name_by_id(UserId(42))  # OK
2011
2012        num = UserId(5) + 1     # type: int
2013    """
2014
2015    def new_type(x):
2016        return x
2017
2018    new_type.__name__ = name
2019    new_type.__supertype__ = tp
2020    return new_type
2021
2022
2023# Python-version-specific alias (Python 2: unicode; Python 3: str)
2024Text = str
2025
2026
2027# Constant that's True when type checking, but False here.
2028TYPE_CHECKING = False
2029
2030
2031class IO(Generic[AnyStr]):
2032    """Generic base class for TextIO and BinaryIO.
2033
2034    This is an abstract, generic version of the return of open().
2035
2036    NOTE: This does not distinguish between the different possible
2037    classes (text vs. binary, read vs. write vs. read/write,
2038    append-only, unbuffered).  The TextIO and BinaryIO subclasses
2039    below capture the distinctions between text vs. binary, which is
2040    pervasive in the interface; however we currently do not offer a
2041    way to track the other distinctions in the type system.
2042    """
2043
2044    __slots__ = ()
2045
2046    @property
2047    @abstractmethod
2048    def mode(self) -> str:
2049        pass
2050
2051    @property
2052    @abstractmethod
2053    def name(self) -> str:
2054        pass
2055
2056    @abstractmethod
2057    def close(self) -> None:
2058        pass
2059
2060    @property
2061    @abstractmethod
2062    def closed(self) -> bool:
2063        pass
2064
2065    @abstractmethod
2066    def fileno(self) -> int:
2067        pass
2068
2069    @abstractmethod
2070    def flush(self) -> None:
2071        pass
2072
2073    @abstractmethod
2074    def isatty(self) -> bool:
2075        pass
2076
2077    @abstractmethod
2078    def read(self, n: int = -1) -> AnyStr:
2079        pass
2080
2081    @abstractmethod
2082    def readable(self) -> bool:
2083        pass
2084
2085    @abstractmethod
2086    def readline(self, limit: int = -1) -> AnyStr:
2087        pass
2088
2089    @abstractmethod
2090    def readlines(self, hint: int = -1) -> List[AnyStr]:
2091        pass
2092
2093    @abstractmethod
2094    def seek(self, offset: int, whence: int = 0) -> int:
2095        pass
2096
2097    @abstractmethod
2098    def seekable(self) -> bool:
2099        pass
2100
2101    @abstractmethod
2102    def tell(self) -> int:
2103        pass
2104
2105    @abstractmethod
2106    def truncate(self, size: int = None) -> int:
2107        pass
2108
2109    @abstractmethod
2110    def writable(self) -> bool:
2111        pass
2112
2113    @abstractmethod
2114    def write(self, s: AnyStr) -> int:
2115        pass
2116
2117    @abstractmethod
2118    def writelines(self, lines: List[AnyStr]) -> None:
2119        pass
2120
2121    @abstractmethod
2122    def __enter__(self) -> 'IO[AnyStr]':
2123        pass
2124
2125    @abstractmethod
2126    def __exit__(self, type, value, traceback) -> None:
2127        pass
2128
2129
2130class BinaryIO(IO[bytes]):
2131    """Typed version of the return of open() in binary mode."""
2132
2133    __slots__ = ()
2134
2135    @abstractmethod
2136    def write(self, s: Union[bytes, bytearray]) -> int:
2137        pass
2138
2139    @abstractmethod
2140    def __enter__(self) -> 'BinaryIO':
2141        pass
2142
2143
2144class TextIO(IO[str]):
2145    """Typed version of the return of open() in text mode."""
2146
2147    __slots__ = ()
2148
2149    @property
2150    @abstractmethod
2151    def buffer(self) -> BinaryIO:
2152        pass
2153
2154    @property
2155    @abstractmethod
2156    def encoding(self) -> str:
2157        pass
2158
2159    @property
2160    @abstractmethod
2161    def errors(self) -> Optional[str]:
2162        pass
2163
2164    @property
2165    @abstractmethod
2166    def line_buffering(self) -> bool:
2167        pass
2168
2169    @property
2170    @abstractmethod
2171    def newlines(self) -> Any:
2172        pass
2173
2174    @abstractmethod
2175    def __enter__(self) -> 'TextIO':
2176        pass
2177
2178
2179class io:
2180    """Wrapper namespace for IO generic classes."""
2181
2182    __all__ = ['IO', 'TextIO', 'BinaryIO']
2183    IO = IO
2184    TextIO = TextIO
2185    BinaryIO = BinaryIO
2186
2187
2188io.__name__ = __name__ + '.io'
2189sys.modules[io.__name__] = io
2190
2191Pattern = _alias(stdlib_re.Pattern, 1)
2192Match = _alias(stdlib_re.Match, 1)
2193
2194class re:
2195    """Wrapper namespace for re type aliases."""
2196
2197    __all__ = ['Pattern', 'Match']
2198    Pattern = Pattern
2199    Match = Match
2200
2201
2202re.__name__ = __name__ + '.re'
2203sys.modules[re.__name__] = re
2204