1import abc
2import collections
3import contextlib
4import sys
5import typing
6import collections.abc as collections_abc
7import operator
8
9# These are used by Protocol implementation
10# We use internal typing helpers here, but this significantly reduces
11# code duplication. (Also this is only until Protocol is in typing.)
12from typing import Generic, Callable, TypeVar, Tuple
13
14# After PEP 560, internal typing API was substantially reworked.
15# This is especially important for Protocol class which uses internal APIs
16# quite extensivelly.
17PEP_560 = sys.version_info[:3] >= (3, 7, 0)
18
19if PEP_560:
20    GenericMeta = TypingMeta = type
21else:
22    from typing import GenericMeta, TypingMeta
23OLD_GENERICS = False
24try:
25    from typing import _type_vars, _next_in_mro, _type_check
26except ImportError:
27    OLD_GENERICS = True
28try:
29    from typing import _subs_tree  # noqa
30    SUBS_TREE = True
31except ImportError:
32    SUBS_TREE = False
33try:
34    from typing import _tp_cache
35except ImportError:
36    def _tp_cache(x):
37        return x
38try:
39    from typing import _TypingEllipsis, _TypingEmpty
40except ImportError:
41    class _TypingEllipsis:
42        pass
43
44    class _TypingEmpty:
45        pass
46
47
48# The two functions below are copies of typing internal helpers.
49# They are needed by _ProtocolMeta
50
51
52def _no_slots_copy(dct):
53    dict_copy = dict(dct)
54    if '__slots__' in dict_copy:
55        for slot in dict_copy['__slots__']:
56            dict_copy.pop(slot, None)
57    return dict_copy
58
59
60def _check_generic(cls, parameters):
61    if not cls.__parameters__:
62        raise TypeError("%s is not a generic class" % repr(cls))
63    alen = len(parameters)
64    elen = len(cls.__parameters__)
65    if alen != elen:
66        raise TypeError("Too %s parameters for %s; actual %s, expected %s" %
67                        ("many" if alen > elen else "few", repr(cls), alen, elen))
68
69
70if hasattr(typing, '_generic_new'):
71    _generic_new = typing._generic_new
72else:
73    # Note: The '_generic_new(...)' function is used as a part of the
74    # process of creating a generic type and was added to the typing module
75    # as of Python 3.5.3.
76    #
77    # We've defined '_generic_new(...)' below to exactly match the behavior
78    # implemented in older versions of 'typing' bundled with Python 3.5.0 to
79    # 3.5.2. This helps eliminate redundancy when defining collection types
80    # like 'Deque' later.
81    #
82    # See https://github.com/python/typing/pull/308 for more details -- in
83    # particular, compare and contrast the definition of types like
84    # 'typing.List' before and after the merge.
85
86    def _generic_new(base_cls, cls, *args, **kwargs):
87        return base_cls.__new__(cls, *args, **kwargs)
88
89# See https://github.com/python/typing/pull/439
90if hasattr(typing, '_geqv'):
91    from typing import _geqv
92    _geqv_defined = True
93else:
94    _geqv = None
95    _geqv_defined = False
96
97if sys.version_info[:2] >= (3, 6):
98    import _collections_abc
99    _check_methods_in_mro = _collections_abc._check_methods
100else:
101    def _check_methods_in_mro(C, *methods):
102        mro = C.__mro__
103        for method in methods:
104            for B in mro:
105                if method in B.__dict__:
106                    if B.__dict__[method] is None:
107                        return NotImplemented
108                    break
109            else:
110                return NotImplemented
111        return True
112
113
114# Please keep __all__ alphabetized within each category.
115__all__ = [
116    # Super-special typing primitives.
117    'ClassVar',
118    'Final',
119    'Type',
120
121    # ABCs (from collections.abc).
122    # The following are added depending on presence
123    # of their non-generic counterparts in stdlib:
124    # 'Awaitable',
125    # 'AsyncIterator',
126    # 'AsyncIterable',
127    # 'Coroutine',
128    # 'AsyncGenerator',
129    # 'AsyncContextManager',
130    # 'ChainMap',
131
132    # Concrete collection types.
133    'ContextManager',
134    'Counter',
135    'Deque',
136    'DefaultDict',
137    'TypedDict',
138
139    # Structural checks, a.k.a. protocols.
140    'SupportsIndex',
141
142    # One-off things.
143    'final',
144    'IntVar',
145    'Literal',
146    'NewType',
147    'overload',
148    'Text',
149    'TYPE_CHECKING',
150]
151
152# Annotated relies on substitution trees of pep 560. It will not work for
153# versions of typing older than 3.5.3
154HAVE_ANNOTATED = PEP_560 or SUBS_TREE
155
156if PEP_560:
157    __all__.extend(["get_args", "get_origin", "get_type_hints"])
158
159if HAVE_ANNOTATED:
160    __all__.append("Annotated")
161
162# Protocols are hard to backport to the original version of typing 3.5.0
163HAVE_PROTOCOLS = sys.version_info[:3] != (3, 5, 0)
164
165if HAVE_PROTOCOLS:
166    __all__.extend(['Protocol', 'runtime', 'runtime_checkable'])
167
168
169# TODO
170if hasattr(typing, 'NoReturn'):
171    NoReturn = typing.NoReturn
172elif hasattr(typing, '_FinalTypingBase'):
173    class _NoReturn(typing._FinalTypingBase, _root=True):
174        """Special type indicating functions that never return.
175        Example::
176
177          from typing import NoReturn
178
179          def stop() -> NoReturn:
180              raise Exception('no way')
181
182        This type is invalid in other positions, e.g., ``List[NoReturn]``
183        will fail in static type checkers.
184        """
185        __slots__ = ()
186
187        def __instancecheck__(self, obj):
188            raise TypeError("NoReturn cannot be used with isinstance().")
189
190        def __subclasscheck__(self, cls):
191            raise TypeError("NoReturn cannot be used with issubclass().")
192
193    NoReturn = _NoReturn(_root=True)
194else:
195    class _NoReturnMeta(typing.TypingMeta):
196        """Metaclass for NoReturn"""
197        def __new__(cls, name, bases, namespace, _root=False):
198            return super().__new__(cls, name, bases, namespace, _root=_root)
199
200        def __instancecheck__(self, obj):
201            raise TypeError("NoReturn cannot be used with isinstance().")
202
203        def __subclasscheck__(self, cls):
204            raise TypeError("NoReturn cannot be used with issubclass().")
205
206    class NoReturn(typing.Final, metaclass=_NoReturnMeta, _root=True):
207        """Special type indicating functions that never return.
208        Example::
209
210          from typing import NoReturn
211
212          def stop() -> NoReturn:
213              raise Exception('no way')
214
215        This type is invalid in other positions, e.g., ``List[NoReturn]``
216        will fail in static type checkers.
217        """
218        __slots__ = ()
219
220
221# Some unconstrained type variables.  These are used by the container types.
222# (These are not for export.)
223T = typing.TypeVar('T')  # Any type.
224KT = typing.TypeVar('KT')  # Key type.
225VT = typing.TypeVar('VT')  # Value type.
226T_co = typing.TypeVar('T_co', covariant=True)  # Any type covariant containers.
227V_co = typing.TypeVar('V_co', covariant=True)  # Any type covariant containers.
228VT_co = typing.TypeVar('VT_co', covariant=True)  # Value type covariant containers.
229T_contra = typing.TypeVar('T_contra', contravariant=True)  # Ditto contravariant.
230
231
232if hasattr(typing, 'ClassVar'):
233    ClassVar = typing.ClassVar
234elif hasattr(typing, '_FinalTypingBase'):
235    class _ClassVar(typing._FinalTypingBase, _root=True):
236        """Special type construct to mark class variables.
237
238        An annotation wrapped in ClassVar indicates that a given
239        attribute is intended to be used as a class variable and
240        should not be set on instances of that class. Usage::
241
242          class Starship:
243              stats: ClassVar[Dict[str, int]] = {} # class variable
244              damage: int = 10                     # instance variable
245
246        ClassVar accepts only types and cannot be further subscribed.
247
248        Note that ClassVar is not a class itself, and should not
249        be used with isinstance() or issubclass().
250        """
251
252        __slots__ = ('__type__',)
253
254        def __init__(self, tp=None, **kwds):
255            self.__type__ = tp
256
257        def __getitem__(self, item):
258            cls = type(self)
259            if self.__type__ is None:
260                return cls(typing._type_check(item,
261                           '{} accepts only single type.'.format(cls.__name__[1:])),
262                           _root=True)
263            raise TypeError('{} cannot be further subscripted'
264                            .format(cls.__name__[1:]))
265
266        def _eval_type(self, globalns, localns):
267            new_tp = typing._eval_type(self.__type__, globalns, localns)
268            if new_tp == self.__type__:
269                return self
270            return type(self)(new_tp, _root=True)
271
272        def __repr__(self):
273            r = super().__repr__()
274            if self.__type__ is not None:
275                r += '[{}]'.format(typing._type_repr(self.__type__))
276            return r
277
278        def __hash__(self):
279            return hash((type(self).__name__, self.__type__))
280
281        def __eq__(self, other):
282            if not isinstance(other, _ClassVar):
283                return NotImplemented
284            if self.__type__ is not None:
285                return self.__type__ == other.__type__
286            return self is other
287
288    ClassVar = _ClassVar(_root=True)
289else:
290    class _ClassVarMeta(typing.TypingMeta):
291        """Metaclass for ClassVar"""
292
293        def __new__(cls, name, bases, namespace, tp=None, _root=False):
294            self = super().__new__(cls, name, bases, namespace, _root=_root)
295            if tp is not None:
296                self.__type__ = tp
297            return self
298
299        def __instancecheck__(self, obj):
300            raise TypeError("ClassVar cannot be used with isinstance().")
301
302        def __subclasscheck__(self, cls):
303            raise TypeError("ClassVar cannot be used with issubclass().")
304
305        def __getitem__(self, item):
306            cls = type(self)
307            if self.__type__ is not None:
308                raise TypeError('{} cannot be further subscripted'
309                                .format(cls.__name__[1:]))
310
311            param = typing._type_check(
312                item,
313                '{} accepts only single type.'.format(cls.__name__[1:]))
314            return cls(self.__name__, self.__bases__,
315                       dict(self.__dict__), tp=param, _root=True)
316
317        def _eval_type(self, globalns, localns):
318            new_tp = typing._eval_type(self.__type__, globalns, localns)
319            if new_tp == self.__type__:
320                return self
321            return type(self)(self.__name__, self.__bases__,
322                              dict(self.__dict__), tp=self.__type__,
323                              _root=True)
324
325        def __repr__(self):
326            r = super().__repr__()
327            if self.__type__ is not None:
328                r += '[{}]'.format(typing._type_repr(self.__type__))
329            return r
330
331        def __hash__(self):
332            return hash((type(self).__name__, self.__type__))
333
334        def __eq__(self, other):
335            if not isinstance(other, ClassVar):
336                return NotImplemented
337            if self.__type__ is not None:
338                return self.__type__ == other.__type__
339            return self is other
340
341    class ClassVar(typing.Final, metaclass=_ClassVarMeta, _root=True):
342        """Special type construct to mark class variables.
343
344        An annotation wrapped in ClassVar indicates that a given
345        attribute is intended to be used as a class variable and
346        should not be set on instances of that class. Usage::
347
348          class Starship:
349              stats: ClassVar[Dict[str, int]] = {} # class variable
350              damage: int = 10                     # instance variable
351
352        ClassVar accepts only types and cannot be further subscribed.
353
354        Note that ClassVar is not a class itself, and should not
355        be used with isinstance() or issubclass().
356        """
357
358        __type__ = None
359
360# On older versions of typing there is an internal class named "Final".
361if hasattr(typing, 'Final') and sys.version_info[:2] >= (3, 7):
362    Final = typing.Final
363elif sys.version_info[:2] >= (3, 7):
364    class _FinalForm(typing._SpecialForm, _root=True):
365
366        def __repr__(self):
367            return 'typing_extensions.' + self._name
368
369        def __getitem__(self, parameters):
370            item = typing._type_check(parameters,
371                                      '{} accepts only single type'.format(self._name))
372            return _GenericAlias(self, (item,))
373
374    Final = _FinalForm('Final',
375                       doc="""A special typing construct to indicate that a name
376                       cannot be re-assigned or overridden in a subclass.
377                       For example:
378
379                           MAX_SIZE: Final = 9000
380                           MAX_SIZE += 1  # Error reported by type checker
381
382                           class Connection:
383                               TIMEOUT: Final[int] = 10
384                           class FastConnector(Connection):
385                               TIMEOUT = 1  # Error reported by type checker
386
387                       There is no runtime checking of these properties.""")
388elif hasattr(typing, '_FinalTypingBase'):
389    class _Final(typing._FinalTypingBase, _root=True):
390        """A special typing construct to indicate that a name
391        cannot be re-assigned or overridden in a subclass.
392        For example:
393
394            MAX_SIZE: Final = 9000
395            MAX_SIZE += 1  # Error reported by type checker
396
397            class Connection:
398                TIMEOUT: Final[int] = 10
399            class FastConnector(Connection):
400                TIMEOUT = 1  # Error reported by type checker
401
402        There is no runtime checking of these properties.
403        """
404
405        __slots__ = ('__type__',)
406
407        def __init__(self, tp=None, **kwds):
408            self.__type__ = tp
409
410        def __getitem__(self, item):
411            cls = type(self)
412            if self.__type__ is None:
413                return cls(typing._type_check(item,
414                           '{} accepts only single type.'.format(cls.__name__[1:])),
415                           _root=True)
416            raise TypeError('{} cannot be further subscripted'
417                            .format(cls.__name__[1:]))
418
419        def _eval_type(self, globalns, localns):
420            new_tp = typing._eval_type(self.__type__, globalns, localns)
421            if new_tp == self.__type__:
422                return self
423            return type(self)(new_tp, _root=True)
424
425        def __repr__(self):
426            r = super().__repr__()
427            if self.__type__ is not None:
428                r += '[{}]'.format(typing._type_repr(self.__type__))
429            return r
430
431        def __hash__(self):
432            return hash((type(self).__name__, self.__type__))
433
434        def __eq__(self, other):
435            if not isinstance(other, _Final):
436                return NotImplemented
437            if self.__type__ is not None:
438                return self.__type__ == other.__type__
439            return self is other
440
441    Final = _Final(_root=True)
442else:
443    class _FinalMeta(typing.TypingMeta):
444        """Metaclass for Final"""
445
446        def __new__(cls, name, bases, namespace, tp=None, _root=False):
447            self = super().__new__(cls, name, bases, namespace, _root=_root)
448            if tp is not None:
449                self.__type__ = tp
450            return self
451
452        def __instancecheck__(self, obj):
453            raise TypeError("Final cannot be used with isinstance().")
454
455        def __subclasscheck__(self, cls):
456            raise TypeError("Final cannot be used with issubclass().")
457
458        def __getitem__(self, item):
459            cls = type(self)
460            if self.__type__ is not None:
461                raise TypeError('{} cannot be further subscripted'
462                                .format(cls.__name__[1:]))
463
464            param = typing._type_check(
465                item,
466                '{} accepts only single type.'.format(cls.__name__[1:]))
467            return cls(self.__name__, self.__bases__,
468                       dict(self.__dict__), tp=param, _root=True)
469
470        def _eval_type(self, globalns, localns):
471            new_tp = typing._eval_type(self.__type__, globalns, localns)
472            if new_tp == self.__type__:
473                return self
474            return type(self)(self.__name__, self.__bases__,
475                              dict(self.__dict__), tp=self.__type__,
476                              _root=True)
477
478        def __repr__(self):
479            r = super().__repr__()
480            if self.__type__ is not None:
481                r += '[{}]'.format(typing._type_repr(self.__type__))
482            return r
483
484        def __hash__(self):
485            return hash((type(self).__name__, self.__type__))
486
487        def __eq__(self, other):
488            if not isinstance(other, Final):
489                return NotImplemented
490            if self.__type__ is not None:
491                return self.__type__ == other.__type__
492            return self is other
493
494    class Final(typing.Final, metaclass=_FinalMeta, _root=True):
495        """A special typing construct to indicate that a name
496        cannot be re-assigned or overridden in a subclass.
497        For example:
498
499            MAX_SIZE: Final = 9000
500            MAX_SIZE += 1  # Error reported by type checker
501
502            class Connection:
503                TIMEOUT: Final[int] = 10
504            class FastConnector(Connection):
505                TIMEOUT = 1  # Error reported by type checker
506
507        There is no runtime checking of these properties.
508        """
509
510        __type__ = None
511
512
513if hasattr(typing, 'final'):
514    final = typing.final
515else:
516    def final(f):
517        """This decorator can be used to indicate to type checkers that
518        the decorated method cannot be overridden, and decorated class
519        cannot be subclassed. For example:
520
521            class Base:
522                @final
523                def done(self) -> None:
524                    ...
525            class Sub(Base):
526                def done(self) -> None:  # Error reported by type checker
527                    ...
528            @final
529            class Leaf:
530                ...
531            class Other(Leaf):  # Error reported by type checker
532                ...
533
534        There is no runtime checking of these properties.
535        """
536        return f
537
538
539def IntVar(name):
540    return TypeVar(name)
541
542
543if hasattr(typing, 'Literal'):
544    Literal = typing.Literal
545elif sys.version_info[:2] >= (3, 7):
546    class _LiteralForm(typing._SpecialForm, _root=True):
547
548        def __repr__(self):
549            return 'typing_extensions.' + self._name
550
551        def __getitem__(self, parameters):
552            return _GenericAlias(self, parameters)
553
554    Literal = _LiteralForm('Literal',
555                           doc="""A type that can be used to indicate to type checkers
556                           that the corresponding value has a value literally equivalent
557                           to the provided parameter. For example:
558
559                               var: Literal[4] = 4
560
561                           The type checker understands that 'var' is literally equal to
562                           the value 4 and no other value.
563
564                           Literal[...] cannot be subclassed. There is no runtime
565                           checking verifying that the parameter is actually a value
566                           instead of a type.""")
567elif hasattr(typing, '_FinalTypingBase'):
568    class _Literal(typing._FinalTypingBase, _root=True):
569        """A type that can be used to indicate to type checkers that the
570        corresponding value has a value literally equivalent to the
571        provided parameter. For example:
572
573            var: Literal[4] = 4
574
575        The type checker understands that 'var' is literally equal to the
576        value 4 and no other value.
577
578        Literal[...] cannot be subclassed. There is no runtime checking
579        verifying that the parameter is actually a value instead of a type.
580        """
581
582        __slots__ = ('__values__',)
583
584        def __init__(self, values=None, **kwds):
585            self.__values__ = values
586
587        def __getitem__(self, values):
588            cls = type(self)
589            if self.__values__ is None:
590                if not isinstance(values, tuple):
591                    values = (values,)
592                return cls(values, _root=True)
593            raise TypeError('{} cannot be further subscripted'
594                            .format(cls.__name__[1:]))
595
596        def _eval_type(self, globalns, localns):
597            return self
598
599        def __repr__(self):
600            r = super().__repr__()
601            if self.__values__ is not None:
602                r += '[{}]'.format(', '.join(map(typing._type_repr, self.__values__)))
603            return r
604
605        def __hash__(self):
606            return hash((type(self).__name__, self.__values__))
607
608        def __eq__(self, other):
609            if not isinstance(other, _Literal):
610                return NotImplemented
611            if self.__values__ is not None:
612                return self.__values__ == other.__values__
613            return self is other
614
615    Literal = _Literal(_root=True)
616else:
617    class _LiteralMeta(typing.TypingMeta):
618        """Metaclass for Literal"""
619
620        def __new__(cls, name, bases, namespace, values=None, _root=False):
621            self = super().__new__(cls, name, bases, namespace, _root=_root)
622            if values is not None:
623                self.__values__ = values
624            return self
625
626        def __instancecheck__(self, obj):
627            raise TypeError("Literal cannot be used with isinstance().")
628
629        def __subclasscheck__(self, cls):
630            raise TypeError("Literal cannot be used with issubclass().")
631
632        def __getitem__(self, item):
633            cls = type(self)
634            if self.__values__ is not None:
635                raise TypeError('{} cannot be further subscripted'
636                                .format(cls.__name__[1:]))
637
638            if not isinstance(item, tuple):
639                item = (item,)
640            return cls(self.__name__, self.__bases__,
641                       dict(self.__dict__), values=item, _root=True)
642
643        def _eval_type(self, globalns, localns):
644            return self
645
646        def __repr__(self):
647            r = super().__repr__()
648            if self.__values__ is not None:
649                r += '[{}]'.format(', '.join(map(typing._type_repr, self.__values__)))
650            return r
651
652        def __hash__(self):
653            return hash((type(self).__name__, self.__values__))
654
655        def __eq__(self, other):
656            if not isinstance(other, Literal):
657                return NotImplemented
658            if self.__values__ is not None:
659                return self.__values__ == other.__values__
660            return self is other
661
662    class Literal(typing.Final, metaclass=_LiteralMeta, _root=True):
663        """A type that can be used to indicate to type checkers that the
664        corresponding value has a value literally equivalent to the
665        provided parameter. For example:
666
667            var: Literal[4] = 4
668
669        The type checker understands that 'var' is literally equal to the
670        value 4 and no other value.
671
672        Literal[...] cannot be subclassed. There is no runtime checking
673        verifying that the parameter is actually a value instead of a type.
674        """
675
676        __values__ = None
677
678
679def _overload_dummy(*args, **kwds):
680    """Helper for @overload to raise when called."""
681    raise NotImplementedError(
682        "You should not call an overloaded function. "
683        "A series of @overload-decorated functions "
684        "outside a stub module should always be followed "
685        "by an implementation that is not @overload-ed.")
686
687
688def overload(func):
689    """Decorator for overloaded functions/methods.
690
691    In a stub file, place two or more stub definitions for the same
692    function in a row, each decorated with @overload.  For example:
693
694      @overload
695      def utf8(value: None) -> None: ...
696      @overload
697      def utf8(value: bytes) -> bytes: ...
698      @overload
699      def utf8(value: str) -> bytes: ...
700
701    In a non-stub file (i.e. a regular .py file), do the same but
702    follow it with an implementation.  The implementation should *not*
703    be decorated with @overload.  For example:
704
705      @overload
706      def utf8(value: None) -> None: ...
707      @overload
708      def utf8(value: bytes) -> bytes: ...
709      @overload
710      def utf8(value: str) -> bytes: ...
711      def utf8(value):
712          # implementation goes here
713    """
714    return _overload_dummy
715
716
717# This is not a real generic class.  Don't use outside annotations.
718if hasattr(typing, 'Type'):
719    Type = typing.Type
720else:
721    # Internal type variable used for Type[].
722    CT_co = typing.TypeVar('CT_co', covariant=True, bound=type)
723
724    class Type(typing.Generic[CT_co], extra=type):
725        """A special construct usable to annotate class objects.
726
727        For example, suppose we have the following classes::
728
729          class User: ...  # Abstract base for User classes
730          class BasicUser(User): ...
731          class ProUser(User): ...
732          class TeamUser(User): ...
733
734        And a function that takes a class argument that's a subclass of
735        User and returns an instance of the corresponding class::
736
737          U = TypeVar('U', bound=User)
738          def new_user(user_class: Type[U]) -> U:
739              user = user_class()
740              # (Here we could write the user object to a database)
741              return user
742          joe = new_user(BasicUser)
743
744        At this point the type checker knows that joe has type BasicUser.
745        """
746
747        __slots__ = ()
748
749
750# Various ABCs mimicking those in collections.abc.
751# A few are simply re-exported for completeness.
752
753def _define_guard(type_name):
754    """
755    Returns True if the given type isn't defined in typing but
756    is defined in collections_abc.
757
758    Adds the type to __all__ if the collection is found in either
759    typing or collection_abc.
760    """
761    if hasattr(typing, type_name):
762        __all__.append(type_name)
763        globals()[type_name] = getattr(typing, type_name)
764        return False
765    elif hasattr(collections_abc, type_name):
766        __all__.append(type_name)
767        return True
768    else:
769        return False
770
771
772class _ExtensionsGenericMeta(GenericMeta):
773    def __subclasscheck__(self, subclass):
774        """This mimics a more modern GenericMeta.__subclasscheck__() logic
775        (that does not have problems with recursion) to work around interactions
776        between collections, typing, and typing_extensions on older
777        versions of Python, see https://github.com/python/typing/issues/501.
778        """
779        if sys.version_info[:3] >= (3, 5, 3) or sys.version_info[:3] < (3, 5, 0):
780            if self.__origin__ is not None:
781                if sys._getframe(1).f_globals['__name__'] not in ['abc', 'functools']:
782                    raise TypeError("Parameterized generics cannot be used with class "
783                                    "or instance checks")
784                return False
785        if not self.__extra__:
786            return super().__subclasscheck__(subclass)
787        res = self.__extra__.__subclasshook__(subclass)
788        if res is not NotImplemented:
789            return res
790        if self.__extra__ in subclass.__mro__:
791            return True
792        for scls in self.__extra__.__subclasses__():
793            if isinstance(scls, GenericMeta):
794                continue
795            if issubclass(subclass, scls):
796                return True
797        return False
798
799
800if _define_guard('Awaitable'):
801    class Awaitable(typing.Generic[T_co], metaclass=_ExtensionsGenericMeta,
802                    extra=collections_abc.Awaitable):
803        __slots__ = ()
804
805
806if _define_guard('Coroutine'):
807    class Coroutine(Awaitable[V_co], typing.Generic[T_co, T_contra, V_co],
808                    metaclass=_ExtensionsGenericMeta,
809                    extra=collections_abc.Coroutine):
810        __slots__ = ()
811
812
813if _define_guard('AsyncIterable'):
814    class AsyncIterable(typing.Generic[T_co],
815                        metaclass=_ExtensionsGenericMeta,
816                        extra=collections_abc.AsyncIterable):
817        __slots__ = ()
818
819
820if _define_guard('AsyncIterator'):
821    class AsyncIterator(AsyncIterable[T_co],
822                        metaclass=_ExtensionsGenericMeta,
823                        extra=collections_abc.AsyncIterator):
824        __slots__ = ()
825
826
827if hasattr(typing, 'Deque'):
828    Deque = typing.Deque
829elif _geqv_defined:
830    class Deque(collections.deque, typing.MutableSequence[T],
831                metaclass=_ExtensionsGenericMeta,
832                extra=collections.deque):
833        __slots__ = ()
834
835        def __new__(cls, *args, **kwds):
836            if _geqv(cls, Deque):
837                return collections.deque(*args, **kwds)
838            return _generic_new(collections.deque, cls, *args, **kwds)
839else:
840    class Deque(collections.deque, typing.MutableSequence[T],
841                metaclass=_ExtensionsGenericMeta,
842                extra=collections.deque):
843        __slots__ = ()
844
845        def __new__(cls, *args, **kwds):
846            if cls._gorg is Deque:
847                return collections.deque(*args, **kwds)
848            return _generic_new(collections.deque, cls, *args, **kwds)
849
850
851if hasattr(typing, 'ContextManager'):
852    ContextManager = typing.ContextManager
853elif hasattr(contextlib, 'AbstractContextManager'):
854    class ContextManager(typing.Generic[T_co],
855                         metaclass=_ExtensionsGenericMeta,
856                         extra=contextlib.AbstractContextManager):
857        __slots__ = ()
858else:
859    class ContextManager(typing.Generic[T_co]):
860        __slots__ = ()
861
862        def __enter__(self):
863            return self
864
865        @abc.abstractmethod
866        def __exit__(self, exc_type, exc_value, traceback):
867            return None
868
869        @classmethod
870        def __subclasshook__(cls, C):
871            if cls is ContextManager:
872                # In Python 3.6+, it is possible to set a method to None to
873                # explicitly indicate that the class does not implement an ABC
874                # (https://bugs.python.org/issue25958), but we do not support
875                # that pattern here because this fallback class is only used
876                # in Python 3.5 and earlier.
877                if (any("__enter__" in B.__dict__ for B in C.__mro__) and
878                    any("__exit__" in B.__dict__ for B in C.__mro__)):
879                    return True
880            return NotImplemented
881
882
883if hasattr(typing, 'AsyncContextManager'):
884    AsyncContextManager = typing.AsyncContextManager
885    __all__.append('AsyncContextManager')
886elif hasattr(contextlib, 'AbstractAsyncContextManager'):
887    class AsyncContextManager(typing.Generic[T_co],
888                              metaclass=_ExtensionsGenericMeta,
889                              extra=contextlib.AbstractAsyncContextManager):
890        __slots__ = ()
891
892    __all__.append('AsyncContextManager')
893elif sys.version_info[:2] >= (3, 5):
894    exec("""
895class AsyncContextManager(typing.Generic[T_co]):
896    __slots__ = ()
897
898    async def __aenter__(self):
899        return self
900
901    @abc.abstractmethod
902    async def __aexit__(self, exc_type, exc_value, traceback):
903        return None
904
905    @classmethod
906    def __subclasshook__(cls, C):
907        if cls is AsyncContextManager:
908            return _check_methods_in_mro(C, "__aenter__", "__aexit__")
909        return NotImplemented
910
911__all__.append('AsyncContextManager')
912""")
913
914
915if hasattr(typing, 'DefaultDict'):
916    DefaultDict = typing.DefaultDict
917elif _geqv_defined:
918    class DefaultDict(collections.defaultdict, typing.MutableMapping[KT, VT],
919                      metaclass=_ExtensionsGenericMeta,
920                      extra=collections.defaultdict):
921
922        __slots__ = ()
923
924        def __new__(cls, *args, **kwds):
925            if _geqv(cls, DefaultDict):
926                return collections.defaultdict(*args, **kwds)
927            return _generic_new(collections.defaultdict, cls, *args, **kwds)
928else:
929    class DefaultDict(collections.defaultdict, typing.MutableMapping[KT, VT],
930                      metaclass=_ExtensionsGenericMeta,
931                      extra=collections.defaultdict):
932
933        __slots__ = ()
934
935        def __new__(cls, *args, **kwds):
936            if cls._gorg is DefaultDict:
937                return collections.defaultdict(*args, **kwds)
938            return _generic_new(collections.defaultdict, cls, *args, **kwds)
939
940
941if hasattr(typing, 'Counter'):
942    Counter = typing.Counter
943elif (3, 5, 0) <= sys.version_info[:3] <= (3, 5, 1):
944    assert _geqv_defined
945    _TInt = typing.TypeVar('_TInt')
946
947    class _CounterMeta(typing.GenericMeta):
948        """Metaclass for Counter"""
949        def __getitem__(self, item):
950            return super().__getitem__((item, int))
951
952    class Counter(collections.Counter,
953                  typing.Dict[T, int],
954                  metaclass=_CounterMeta,
955                  extra=collections.Counter):
956
957        __slots__ = ()
958
959        def __new__(cls, *args, **kwds):
960            if _geqv(cls, Counter):
961                return collections.Counter(*args, **kwds)
962            return _generic_new(collections.Counter, cls, *args, **kwds)
963
964elif _geqv_defined:
965    class Counter(collections.Counter,
966                  typing.Dict[T, int],
967                  metaclass=_ExtensionsGenericMeta, extra=collections.Counter):
968
969        __slots__ = ()
970
971        def __new__(cls, *args, **kwds):
972            if _geqv(cls, Counter):
973                return collections.Counter(*args, **kwds)
974            return _generic_new(collections.Counter, cls, *args, **kwds)
975
976else:
977    class Counter(collections.Counter,
978                  typing.Dict[T, int],
979                  metaclass=_ExtensionsGenericMeta, extra=collections.Counter):
980
981        __slots__ = ()
982
983        def __new__(cls, *args, **kwds):
984            if cls._gorg is Counter:
985                return collections.Counter(*args, **kwds)
986            return _generic_new(collections.Counter, cls, *args, **kwds)
987
988
989if hasattr(typing, 'ChainMap'):
990    ChainMap = typing.ChainMap
991    __all__.append('ChainMap')
992elif hasattr(collections, 'ChainMap'):
993    # ChainMap only exists in 3.3+
994    if _geqv_defined:
995        class ChainMap(collections.ChainMap, typing.MutableMapping[KT, VT],
996                       metaclass=_ExtensionsGenericMeta,
997                       extra=collections.ChainMap):
998
999            __slots__ = ()
1000
1001            def __new__(cls, *args, **kwds):
1002                if _geqv(cls, ChainMap):
1003                    return collections.ChainMap(*args, **kwds)
1004                return _generic_new(collections.ChainMap, cls, *args, **kwds)
1005    else:
1006        class ChainMap(collections.ChainMap, typing.MutableMapping[KT, VT],
1007                       metaclass=_ExtensionsGenericMeta,
1008                       extra=collections.ChainMap):
1009
1010            __slots__ = ()
1011
1012            def __new__(cls, *args, **kwds):
1013                if cls._gorg is ChainMap:
1014                    return collections.ChainMap(*args, **kwds)
1015                return _generic_new(collections.ChainMap, cls, *args, **kwds)
1016
1017    __all__.append('ChainMap')
1018
1019
1020if _define_guard('AsyncGenerator'):
1021    class AsyncGenerator(AsyncIterator[T_co], typing.Generic[T_co, T_contra],
1022                         metaclass=_ExtensionsGenericMeta,
1023                         extra=collections_abc.AsyncGenerator):
1024        __slots__ = ()
1025
1026
1027if hasattr(typing, 'NewType'):
1028    NewType = typing.NewType
1029else:
1030    def NewType(name, tp):
1031        """NewType creates simple unique types with almost zero
1032        runtime overhead. NewType(name, tp) is considered a subtype of tp
1033        by static type checkers. At runtime, NewType(name, tp) returns
1034        a dummy function that simply returns its argument. Usage::
1035
1036            UserId = NewType('UserId', int)
1037
1038            def name_by_id(user_id: UserId) -> str:
1039                ...
1040
1041            UserId('user')          # Fails type check
1042
1043            name_by_id(42)          # Fails type check
1044            name_by_id(UserId(42))  # OK
1045
1046            num = UserId(5) + 1     # type: int
1047        """
1048
1049        def new_type(x):
1050            return x
1051
1052        new_type.__name__ = name
1053        new_type.__supertype__ = tp
1054        return new_type
1055
1056
1057if hasattr(typing, 'Text'):
1058    Text = typing.Text
1059else:
1060    Text = str
1061
1062
1063if hasattr(typing, 'TYPE_CHECKING'):
1064    TYPE_CHECKING = typing.TYPE_CHECKING
1065else:
1066    # Constant that's True when type checking, but False here.
1067    TYPE_CHECKING = False
1068
1069
1070def _gorg(cls):
1071    """This function exists for compatibility with old typing versions."""
1072    assert isinstance(cls, GenericMeta)
1073    if hasattr(cls, '_gorg'):
1074        return cls._gorg
1075    while cls.__origin__ is not None:
1076        cls = cls.__origin__
1077    return cls
1078
1079
1080if OLD_GENERICS:
1081    def _next_in_mro(cls):  # noqa
1082        """This function exists for compatibility with old typing versions."""
1083        next_in_mro = object
1084        for i, c in enumerate(cls.__mro__[:-1]):
1085            if isinstance(c, GenericMeta) and _gorg(c) is Generic:
1086                next_in_mro = cls.__mro__[i + 1]
1087        return next_in_mro
1088
1089
1090_PROTO_WHITELIST = ['Callable', 'Awaitable',
1091                    'Iterable', 'Iterator', 'AsyncIterable', 'AsyncIterator',
1092                    'Hashable', 'Sized', 'Container', 'Collection', 'Reversible',
1093                    'ContextManager', 'AsyncContextManager']
1094
1095
1096def _get_protocol_attrs(cls):
1097    attrs = set()
1098    for base in cls.__mro__[:-1]:  # without object
1099        if base.__name__ in ('Protocol', 'Generic'):
1100            continue
1101        annotations = getattr(base, '__annotations__', {})
1102        for attr in list(base.__dict__.keys()) + list(annotations.keys()):
1103            if (not attr.startswith('_abc_') and attr not in (
1104                    '__abstractmethods__', '__annotations__', '__weakref__',
1105                    '_is_protocol', '_is_runtime_protocol', '__dict__',
1106                    '__args__', '__slots__',
1107                    '__next_in_mro__', '__parameters__', '__origin__',
1108                    '__orig_bases__', '__extra__', '__tree_hash__',
1109                    '__doc__', '__subclasshook__', '__init__', '__new__',
1110                    '__module__', '_MutableMapping__marker', '_gorg')):
1111                attrs.add(attr)
1112    return attrs
1113
1114
1115def _is_callable_members_only(cls):
1116    return all(callable(getattr(cls, attr, None)) for attr in _get_protocol_attrs(cls))
1117
1118
1119if hasattr(typing, 'Protocol'):
1120    Protocol = typing.Protocol
1121elif HAVE_PROTOCOLS and not PEP_560:
1122    class _ProtocolMeta(GenericMeta):
1123        """Internal metaclass for Protocol.
1124
1125        This exists so Protocol classes can be generic without deriving
1126        from Generic.
1127        """
1128        if not OLD_GENERICS:
1129            def __new__(cls, name, bases, namespace,
1130                        tvars=None, args=None, origin=None, extra=None, orig_bases=None):
1131                # This is just a version copied from GenericMeta.__new__ that
1132                # includes "Protocol" special treatment. (Comments removed for brevity.)
1133                assert extra is None  # Protocols should not have extra
1134                if tvars is not None:
1135                    assert origin is not None
1136                    assert all(isinstance(t, TypeVar) for t in tvars), tvars
1137                else:
1138                    tvars = _type_vars(bases)
1139                    gvars = None
1140                    for base in bases:
1141                        if base is Generic:
1142                            raise TypeError("Cannot inherit from plain Generic")
1143                        if (isinstance(base, GenericMeta) and
1144                                base.__origin__ in (Generic, Protocol)):
1145                            if gvars is not None:
1146                                raise TypeError(
1147                                    "Cannot inherit from Generic[...] or"
1148                                    " Protocol[...] multiple times.")
1149                            gvars = base.__parameters__
1150                    if gvars is None:
1151                        gvars = tvars
1152                    else:
1153                        tvarset = set(tvars)
1154                        gvarset = set(gvars)
1155                        if not tvarset <= gvarset:
1156                            raise TypeError(
1157                                "Some type variables (%s) "
1158                                "are not listed in %s[%s]" %
1159                                (", ".join(str(t) for t in tvars if t not in gvarset),
1160                                 "Generic" if any(b.__origin__ is Generic
1161                                                  for b in bases) else "Protocol",
1162                                 ", ".join(str(g) for g in gvars)))
1163                        tvars = gvars
1164
1165                initial_bases = bases
1166                if (extra is not None and type(extra) is abc.ABCMeta and
1167                        extra not in bases):
1168                    bases = (extra,) + bases
1169                bases = tuple(_gorg(b) if isinstance(b, GenericMeta) else b
1170                              for b in bases)
1171                if any(isinstance(b, GenericMeta) and b is not Generic for b in bases):
1172                    bases = tuple(b for b in bases if b is not Generic)
1173                namespace.update({'__origin__': origin, '__extra__': extra})
1174                self = super(GenericMeta, cls).__new__(cls, name, bases, namespace,
1175                                                       _root=True)
1176                super(GenericMeta, self).__setattr__('_gorg',
1177                                                     self if not origin else
1178                                                     _gorg(origin))
1179                self.__parameters__ = tvars
1180                self.__args__ = tuple(... if a is _TypingEllipsis else
1181                                      () if a is _TypingEmpty else
1182                                      a for a in args) if args else None
1183                self.__next_in_mro__ = _next_in_mro(self)
1184                if orig_bases is None:
1185                    self.__orig_bases__ = initial_bases
1186                elif origin is not None:
1187                    self._abc_registry = origin._abc_registry
1188                    self._abc_cache = origin._abc_cache
1189                if hasattr(self, '_subs_tree'):
1190                    self.__tree_hash__ = (hash(self._subs_tree()) if origin else
1191                                          super(GenericMeta, self).__hash__())
1192                return self
1193
1194        def __init__(cls, *args, **kwargs):
1195            super().__init__(*args, **kwargs)
1196            if not cls.__dict__.get('_is_protocol', None):
1197                cls._is_protocol = any(b is Protocol or
1198                                       isinstance(b, _ProtocolMeta) and
1199                                       b.__origin__ is Protocol
1200                                       for b in cls.__bases__)
1201            if cls._is_protocol:
1202                for base in cls.__mro__[1:]:
1203                    if not (base in (object, Generic) or
1204                            base.__module__ == 'collections.abc' and
1205                            base.__name__ in _PROTO_WHITELIST or
1206                            isinstance(base, TypingMeta) and base._is_protocol or
1207                            isinstance(base, GenericMeta) and
1208                            base.__origin__ is Generic):
1209                        raise TypeError('Protocols can only inherit from other'
1210                                        ' protocols, got %r' % base)
1211
1212                def _no_init(self, *args, **kwargs):
1213                    if type(self)._is_protocol:
1214                        raise TypeError('Protocols cannot be instantiated')
1215                cls.__init__ = _no_init
1216
1217            def _proto_hook(other):
1218                if not cls.__dict__.get('_is_protocol', None):
1219                    return NotImplemented
1220                if not isinstance(other, type):
1221                    # Same error as for issubclass(1, int)
1222                    raise TypeError('issubclass() arg 1 must be a class')
1223                for attr in _get_protocol_attrs(cls):
1224                    for base in other.__mro__:
1225                        if attr in base.__dict__:
1226                            if base.__dict__[attr] is None:
1227                                return NotImplemented
1228                            break
1229                        annotations = getattr(base, '__annotations__', {})
1230                        if (isinstance(annotations, typing.Mapping) and
1231                                attr in annotations and
1232                                isinstance(other, _ProtocolMeta) and
1233                                other._is_protocol):
1234                            break
1235                    else:
1236                        return NotImplemented
1237                return True
1238            if '__subclasshook__' not in cls.__dict__:
1239                cls.__subclasshook__ = _proto_hook
1240
1241        def __instancecheck__(self, instance):
1242            # We need this method for situations where attributes are
1243            # assigned in __init__.
1244            if ((not getattr(self, '_is_protocol', False) or
1245                    _is_callable_members_only(self)) and
1246                    issubclass(instance.__class__, self)):
1247                return True
1248            if self._is_protocol:
1249                if all(hasattr(instance, attr) and
1250                        (not callable(getattr(self, attr, None)) or
1251                         getattr(instance, attr) is not None)
1252                        for attr in _get_protocol_attrs(self)):
1253                    return True
1254            return super(GenericMeta, self).__instancecheck__(instance)
1255
1256        def __subclasscheck__(self, cls):
1257            if self.__origin__ is not None:
1258                if sys._getframe(1).f_globals['__name__'] not in ['abc', 'functools']:
1259                    raise TypeError("Parameterized generics cannot be used with class "
1260                                    "or instance checks")
1261                return False
1262            if (self.__dict__.get('_is_protocol', None) and
1263                    not self.__dict__.get('_is_runtime_protocol', None)):
1264                if sys._getframe(1).f_globals['__name__'] in ['abc',
1265                                                              'functools',
1266                                                              'typing']:
1267                    return False
1268                raise TypeError("Instance and class checks can only be used with"
1269                                " @runtime protocols")
1270            if (self.__dict__.get('_is_runtime_protocol', None) and
1271                    not _is_callable_members_only(self)):
1272                if sys._getframe(1).f_globals['__name__'] in ['abc',
1273                                                              'functools',
1274                                                              'typing']:
1275                    return super(GenericMeta, self).__subclasscheck__(cls)
1276                raise TypeError("Protocols with non-method members"
1277                                " don't support issubclass()")
1278            return super(GenericMeta, self).__subclasscheck__(cls)
1279
1280        if not OLD_GENERICS:
1281            @_tp_cache
1282            def __getitem__(self, params):
1283                # We also need to copy this from GenericMeta.__getitem__ to get
1284                # special treatment of "Protocol". (Comments removed for brevity.)
1285                if not isinstance(params, tuple):
1286                    params = (params,)
1287                if not params and _gorg(self) is not Tuple:
1288                    raise TypeError(
1289                        "Parameter list to %s[...] cannot be empty" % self.__qualname__)
1290                msg = "Parameters to generic types must be types."
1291                params = tuple(_type_check(p, msg) for p in params)
1292                if self in (Generic, Protocol):
1293                    if not all(isinstance(p, TypeVar) for p in params):
1294                        raise TypeError(
1295                            "Parameters to %r[...] must all be type variables" % self)
1296                    if len(set(params)) != len(params):
1297                        raise TypeError(
1298                            "Parameters to %r[...] must all be unique" % self)
1299                    tvars = params
1300                    args = params
1301                elif self in (Tuple, Callable):
1302                    tvars = _type_vars(params)
1303                    args = params
1304                elif self.__origin__ in (Generic, Protocol):
1305                    raise TypeError("Cannot subscript already-subscripted %s" %
1306                                    repr(self))
1307                else:
1308                    _check_generic(self, params)
1309                    tvars = _type_vars(params)
1310                    args = params
1311
1312                prepend = (self,) if self.__origin__ is None else ()
1313                return self.__class__(self.__name__,
1314                                      prepend + self.__bases__,
1315                                      _no_slots_copy(self.__dict__),
1316                                      tvars=tvars,
1317                                      args=args,
1318                                      origin=self,
1319                                      extra=self.__extra__,
1320                                      orig_bases=self.__orig_bases__)
1321
1322    class Protocol(metaclass=_ProtocolMeta):
1323        """Base class for protocol classes. Protocol classes are defined as::
1324
1325          class Proto(Protocol):
1326              def meth(self) -> int:
1327                  ...
1328
1329        Such classes are primarily used with static type checkers that recognize
1330        structural subtyping (static duck-typing), for example::
1331
1332          class C:
1333              def meth(self) -> int:
1334                  return 0
1335
1336          def func(x: Proto) -> int:
1337              return x.meth()
1338
1339          func(C())  # Passes static type check
1340
1341        See PEP 544 for details. Protocol classes decorated with
1342        @typing_extensions.runtime act as simple-minded runtime protocol that checks
1343        only the presence of given attributes, ignoring their type signatures.
1344
1345        Protocol classes can be generic, they are defined as::
1346
1347          class GenProto({bases}):
1348              def meth(self) -> T:
1349                  ...
1350        """
1351        __slots__ = ()
1352        _is_protocol = True
1353
1354        def __new__(cls, *args, **kwds):
1355            if _gorg(cls) is Protocol:
1356                raise TypeError("Type Protocol cannot be instantiated; "
1357                                "it can be used only as a base class")
1358            if OLD_GENERICS:
1359                return _generic_new(_next_in_mro(cls), cls, *args, **kwds)
1360            return _generic_new(cls.__next_in_mro__, cls, *args, **kwds)
1361    if Protocol.__doc__ is not None:
1362        Protocol.__doc__ = Protocol.__doc__.format(bases="Protocol, Generic[T]" if
1363                                                   OLD_GENERICS else "Protocol[T]")
1364
1365
1366elif PEP_560:
1367    from typing import _type_check, _GenericAlias, _collect_type_vars  # noqa
1368
1369    class _ProtocolMeta(abc.ABCMeta):
1370        # This metaclass is a bit unfortunate and exists only because of the lack
1371        # of __instancehook__.
1372        def __instancecheck__(cls, instance):
1373            # We need this method for situations where attributes are
1374            # assigned in __init__.
1375            if ((not getattr(cls, '_is_protocol', False) or
1376                    _is_callable_members_only(cls)) and
1377                    issubclass(instance.__class__, cls)):
1378                return True
1379            if cls._is_protocol:
1380                if all(hasattr(instance, attr) and
1381                        (not callable(getattr(cls, attr, None)) or
1382                         getattr(instance, attr) is not None)
1383                        for attr in _get_protocol_attrs(cls)):
1384                    return True
1385            return super().__instancecheck__(instance)
1386
1387    class Protocol(metaclass=_ProtocolMeta):
1388        # There is quite a lot of overlapping code with typing.Generic.
1389        # Unfortunately it is hard to avoid this while these live in two different
1390        # modules. The duplicated code will be removed when Protocol is moved to typing.
1391        """Base class for protocol classes. Protocol classes are defined as::
1392
1393            class Proto(Protocol):
1394                def meth(self) -> int:
1395                    ...
1396
1397        Such classes are primarily used with static type checkers that recognize
1398        structural subtyping (static duck-typing), for example::
1399
1400            class C:
1401                def meth(self) -> int:
1402                    return 0
1403
1404            def func(x: Proto) -> int:
1405                return x.meth()
1406
1407            func(C())  # Passes static type check
1408
1409        See PEP 544 for details. Protocol classes decorated with
1410        @typing_extensions.runtime act as simple-minded runtime protocol that checks
1411        only the presence of given attributes, ignoring their type signatures.
1412
1413        Protocol classes can be generic, they are defined as::
1414
1415            class GenProto(Protocol[T]):
1416                def meth(self) -> T:
1417                    ...
1418        """
1419        __slots__ = ()
1420        _is_protocol = True
1421
1422        def __new__(cls, *args, **kwds):
1423            if cls is Protocol:
1424                raise TypeError("Type Protocol cannot be instantiated; "
1425                                "it can only be used as a base class")
1426            return super().__new__(cls)
1427
1428        @_tp_cache
1429        def __class_getitem__(cls, params):
1430            if not isinstance(params, tuple):
1431                params = (params,)
1432            if not params and cls is not Tuple:
1433                raise TypeError(
1434                    "Parameter list to {}[...] cannot be empty".format(cls.__qualname__))
1435            msg = "Parameters to generic types must be types."
1436            params = tuple(_type_check(p, msg) for p in params)
1437            if cls is Protocol:
1438                # Generic can only be subscripted with unique type variables.
1439                if not all(isinstance(p, TypeVar) for p in params):
1440                    i = 0
1441                    while isinstance(params[i], TypeVar):
1442                        i += 1
1443                    raise TypeError(
1444                        "Parameters to Protocol[...] must all be type variables."
1445                        " Parameter {} is {}".format(i + 1, params[i]))
1446                if len(set(params)) != len(params):
1447                    raise TypeError(
1448                        "Parameters to Protocol[...] must all be unique")
1449            else:
1450                # Subscripting a regular Generic subclass.
1451                _check_generic(cls, params)
1452            return _GenericAlias(cls, params)
1453
1454        def __init_subclass__(cls, *args, **kwargs):
1455            tvars = []
1456            if '__orig_bases__' in cls.__dict__:
1457                error = Generic in cls.__orig_bases__
1458            else:
1459                error = Generic in cls.__bases__
1460            if error:
1461                raise TypeError("Cannot inherit from plain Generic")
1462            if '__orig_bases__' in cls.__dict__:
1463                tvars = _collect_type_vars(cls.__orig_bases__)
1464                # Look for Generic[T1, ..., Tn] or Protocol[T1, ..., Tn].
1465                # If found, tvars must be a subset of it.
1466                # If not found, tvars is it.
1467                # Also check for and reject plain Generic,
1468                # and reject multiple Generic[...] and/or Protocol[...].
1469                gvars = None
1470                for base in cls.__orig_bases__:
1471                    if (isinstance(base, _GenericAlias) and
1472                            base.__origin__ in (Generic, Protocol)):
1473                        # for error messages
1474                        the_base = 'Generic' if base.__origin__ is Generic else 'Protocol'
1475                        if gvars is not None:
1476                            raise TypeError(
1477                                "Cannot inherit from Generic[...]"
1478                                " and/or Protocol[...] multiple types.")
1479                        gvars = base.__parameters__
1480                if gvars is None:
1481                    gvars = tvars
1482                else:
1483                    tvarset = set(tvars)
1484                    gvarset = set(gvars)
1485                    if not tvarset <= gvarset:
1486                        s_vars = ', '.join(str(t) for t in tvars if t not in gvarset)
1487                        s_args = ', '.join(str(g) for g in gvars)
1488                        raise TypeError("Some type variables ({}) are"
1489                                        " not listed in {}[{}]".format(s_vars,
1490                                                                       the_base, s_args))
1491                    tvars = gvars
1492            cls.__parameters__ = tuple(tvars)
1493
1494            # Determine if this is a protocol or a concrete subclass.
1495            if not cls.__dict__.get('_is_protocol', None):
1496                cls._is_protocol = any(b is Protocol for b in cls.__bases__)
1497
1498            # Set (or override) the protocol subclass hook.
1499            def _proto_hook(other):
1500                if not cls.__dict__.get('_is_protocol', None):
1501                    return NotImplemented
1502                if not getattr(cls, '_is_runtime_protocol', False):
1503                    if sys._getframe(2).f_globals['__name__'] in ['abc', 'functools']:
1504                        return NotImplemented
1505                    raise TypeError("Instance and class checks can only be used with"
1506                                    " @runtime protocols")
1507                if not _is_callable_members_only(cls):
1508                    if sys._getframe(2).f_globals['__name__'] in ['abc', 'functools']:
1509                        return NotImplemented
1510                    raise TypeError("Protocols with non-method members"
1511                                    " don't support issubclass()")
1512                if not isinstance(other, type):
1513                    # Same error as for issubclass(1, int)
1514                    raise TypeError('issubclass() arg 1 must be a class')
1515                for attr in _get_protocol_attrs(cls):
1516                    for base in other.__mro__:
1517                        if attr in base.__dict__:
1518                            if base.__dict__[attr] is None:
1519                                return NotImplemented
1520                            break
1521                        annotations = getattr(base, '__annotations__', {})
1522                        if (isinstance(annotations, typing.Mapping) and
1523                                attr in annotations and
1524                                isinstance(other, _ProtocolMeta) and
1525                                other._is_protocol):
1526                            break
1527                    else:
1528                        return NotImplemented
1529                return True
1530            if '__subclasshook__' not in cls.__dict__:
1531                cls.__subclasshook__ = _proto_hook
1532
1533            # We have nothing more to do for non-protocols.
1534            if not cls._is_protocol:
1535                return
1536
1537            # Check consistency of bases.
1538            for base in cls.__bases__:
1539                if not (base in (object, Generic) or
1540                        base.__module__ == 'collections.abc' and
1541                        base.__name__ in _PROTO_WHITELIST or
1542                        isinstance(base, _ProtocolMeta) and base._is_protocol):
1543                    raise TypeError('Protocols can only inherit from other'
1544                                    ' protocols, got %r' % base)
1545
1546            def _no_init(self, *args, **kwargs):
1547                if type(self)._is_protocol:
1548                    raise TypeError('Protocols cannot be instantiated')
1549            cls.__init__ = _no_init
1550
1551
1552if hasattr(typing, 'runtime_checkable'):
1553    runtime_checkable = typing.runtime_checkable
1554elif HAVE_PROTOCOLS:
1555    def runtime_checkable(cls):
1556        """Mark a protocol class as a runtime protocol, so that it
1557        can be used with isinstance() and issubclass(). Raise TypeError
1558        if applied to a non-protocol class.
1559
1560        This allows a simple-minded structural check very similar to the
1561        one-offs in collections.abc such as Hashable.
1562        """
1563        if not isinstance(cls, _ProtocolMeta) or not cls._is_protocol:
1564            raise TypeError('@runtime_checkable can be only applied to protocol classes,'
1565                            ' got %r' % cls)
1566        cls._is_runtime_protocol = True
1567        return cls
1568
1569
1570if HAVE_PROTOCOLS:
1571    # Exists for backwards compatibility.
1572    runtime = runtime_checkable
1573
1574
1575if hasattr(typing, 'SupportsIndex'):
1576    SupportsIndex = typing.SupportsIndex
1577elif HAVE_PROTOCOLS:
1578    @runtime_checkable
1579    class SupportsIndex(Protocol):
1580        __slots__ = ()
1581
1582        @abc.abstractmethod
1583        def __index__(self) -> int:
1584            pass
1585
1586
1587if sys.version_info[:2] >= (3, 9):
1588    # The standard library TypedDict in Python 3.8 does not store runtime information
1589    # about which (if any) keys are optional.  See https://bugs.python.org/issue38834
1590    TypedDict = typing.TypedDict
1591else:
1592    def _check_fails(cls, other):
1593        try:
1594            if sys._getframe(1).f_globals['__name__'] not in ['abc',
1595                                                              'functools',
1596                                                              'typing']:
1597                # Typed dicts are only for static structural subtyping.
1598                raise TypeError('TypedDict does not support instance and class checks')
1599        except (AttributeError, ValueError):
1600            pass
1601        return False
1602
1603    def _dict_new(*args, **kwargs):
1604        if not args:
1605            raise TypeError('TypedDict.__new__(): not enough arguments')
1606        _, args = args[0], args[1:]  # allow the "cls" keyword be passed
1607        return dict(*args, **kwargs)
1608
1609    _dict_new.__text_signature__ = '($cls, _typename, _fields=None, /, **kwargs)'
1610
1611    def _typeddict_new(*args, total=True, **kwargs):
1612        if not args:
1613            raise TypeError('TypedDict.__new__(): not enough arguments')
1614        _, args = args[0], args[1:]  # allow the "cls" keyword be passed
1615        if args:
1616            typename, args = args[0], args[1:]  # allow the "_typename" keyword be passed
1617        elif '_typename' in kwargs:
1618            typename = kwargs.pop('_typename')
1619            import warnings
1620            warnings.warn("Passing '_typename' as keyword argument is deprecated",
1621                          DeprecationWarning, stacklevel=2)
1622        else:
1623            raise TypeError("TypedDict.__new__() missing 1 required positional "
1624                            "argument: '_typename'")
1625        if args:
1626            try:
1627                fields, = args  # allow the "_fields" keyword be passed
1628            except ValueError:
1629                raise TypeError('TypedDict.__new__() takes from 2 to 3 '
1630                                'positional arguments but {} '
1631                                'were given'.format(len(args) + 2))
1632        elif '_fields' in kwargs and len(kwargs) == 1:
1633            fields = kwargs.pop('_fields')
1634            import warnings
1635            warnings.warn("Passing '_fields' as keyword argument is deprecated",
1636                          DeprecationWarning, stacklevel=2)
1637        else:
1638            fields = None
1639
1640        if fields is None:
1641            fields = kwargs
1642        elif kwargs:
1643            raise TypeError("TypedDict takes either a dict or keyword arguments,"
1644                            " but not both")
1645
1646        ns = {'__annotations__': dict(fields), '__total__': total}
1647        try:
1648            # Setting correct module is necessary to make typed dict classes pickleable.
1649            ns['__module__'] = sys._getframe(1).f_globals.get('__name__', '__main__')
1650        except (AttributeError, ValueError):
1651            pass
1652
1653        return _TypedDictMeta(typename, (), ns)
1654
1655    _typeddict_new.__text_signature__ = ('($cls, _typename, _fields=None,'
1656                                         ' /, *, total=True, **kwargs)')
1657
1658    class _TypedDictMeta(type):
1659        def __new__(cls, name, bases, ns, total=True):
1660            # Create new typed dict class object.
1661            # This method is called directly when TypedDict is subclassed,
1662            # or via _typeddict_new when TypedDict is instantiated. This way
1663            # TypedDict supports all three syntaxes described in its docstring.
1664            # Subclasses and instances of TypedDict return actual dictionaries
1665            # via _dict_new.
1666            ns['__new__'] = _typeddict_new if name == 'TypedDict' else _dict_new
1667            tp_dict = super(_TypedDictMeta, cls).__new__(cls, name, (dict,), ns)
1668
1669            annotations = {}
1670            own_annotations = ns.get('__annotations__', {})
1671            own_annotation_keys = set(own_annotations.keys())
1672            msg = "TypedDict('Name', {f0: t0, f1: t1, ...}); each t must be a type"
1673            own_annotations = {
1674                n: typing._type_check(tp, msg) for n, tp in own_annotations.items()
1675            }
1676            required_keys = set()
1677            optional_keys = set()
1678
1679            for base in bases:
1680                annotations.update(base.__dict__.get('__annotations__', {}))
1681                required_keys.update(base.__dict__.get('__required_keys__', ()))
1682                optional_keys.update(base.__dict__.get('__optional_keys__', ()))
1683
1684            annotations.update(own_annotations)
1685            if total:
1686                required_keys.update(own_annotation_keys)
1687            else:
1688                optional_keys.update(own_annotation_keys)
1689
1690            tp_dict.__annotations__ = annotations
1691            tp_dict.__required_keys__ = frozenset(required_keys)
1692            tp_dict.__optional_keys__ = frozenset(optional_keys)
1693            if not hasattr(tp_dict, '__total__'):
1694                tp_dict.__total__ = total
1695            return tp_dict
1696
1697        __instancecheck__ = __subclasscheck__ = _check_fails
1698
1699    TypedDict = _TypedDictMeta('TypedDict', (dict,), {})
1700    TypedDict.__module__ = __name__
1701    TypedDict.__doc__ = \
1702        """A simple typed name space. At runtime it is equivalent to a plain dict.
1703
1704        TypedDict creates a dictionary type that expects all of its
1705        instances to have a certain set of keys, with each key
1706        associated with a value of a consistent type. This expectation
1707        is not checked at runtime but is only enforced by type checkers.
1708        Usage::
1709
1710            class Point2D(TypedDict):
1711                x: int
1712                y: int
1713                label: str
1714
1715            a: Point2D = {'x': 1, 'y': 2, 'label': 'good'}  # OK
1716            b: Point2D = {'z': 3, 'label': 'bad'}           # Fails type check
1717
1718            assert Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first')
1719
1720        The type info can be accessed via the Point2D.__annotations__ dict, and
1721        the Point2D.__required_keys__ and Point2D.__optional_keys__ frozensets.
1722        TypedDict supports two additional equivalent forms::
1723
1724            Point2D = TypedDict('Point2D', x=int, y=int, label=str)
1725            Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str})
1726
1727        The class syntax is only supported in Python 3.6+, while two other
1728        syntax forms work for Python 2.7 and 3.2+
1729        """
1730
1731
1732# Python 3.9+ has PEP 593 (Annotated and modified get_type_hints)
1733if hasattr(typing, 'Annotated'):
1734    Annotated = typing.Annotated
1735    get_type_hints = typing.get_type_hints
1736    # Not exported and not a public API, but needed for get_origin() and get_args()
1737    # to work.
1738    _AnnotatedAlias = typing._AnnotatedAlias
1739elif PEP_560:
1740    class _AnnotatedAlias(typing._GenericAlias, _root=True):
1741        """Runtime representation of an annotated type.
1742
1743        At its core 'Annotated[t, dec1, dec2, ...]' is an alias for the type 't'
1744        with extra annotations. The alias behaves like a normal typing alias,
1745        instantiating is the same as instantiating the underlying type, binding
1746        it to types is also the same.
1747        """
1748        def __init__(self, origin, metadata):
1749            if isinstance(origin, _AnnotatedAlias):
1750                metadata = origin.__metadata__ + metadata
1751                origin = origin.__origin__
1752            super().__init__(origin, origin)
1753            self.__metadata__ = metadata
1754
1755        def copy_with(self, params):
1756            assert len(params) == 1
1757            new_type = params[0]
1758            return _AnnotatedAlias(new_type, self.__metadata__)
1759
1760        def __repr__(self):
1761            return "typing_extensions.Annotated[{}, {}]".format(
1762                typing._type_repr(self.__origin__),
1763                ", ".join(repr(a) for a in self.__metadata__)
1764            )
1765
1766        def __reduce__(self):
1767            return operator.getitem, (
1768                Annotated, (self.__origin__,) + self.__metadata__
1769            )
1770
1771        def __eq__(self, other):
1772            if not isinstance(other, _AnnotatedAlias):
1773                return NotImplemented
1774            if self.__origin__ != other.__origin__:
1775                return False
1776            return self.__metadata__ == other.__metadata__
1777
1778        def __hash__(self):
1779            return hash((self.__origin__, self.__metadata__))
1780
1781    class Annotated:
1782        """Add context specific metadata to a type.
1783
1784        Example: Annotated[int, runtime_check.Unsigned] indicates to the
1785        hypothetical runtime_check module that this type is an unsigned int.
1786        Every other consumer of this type can ignore this metadata and treat
1787        this type as int.
1788
1789        The first argument to Annotated must be a valid type (and will be in
1790        the __origin__ field), the remaining arguments are kept as a tuple in
1791        the __extra__ field.
1792
1793        Details:
1794
1795        - It's an error to call `Annotated` with less than two arguments.
1796        - Nested Annotated are flattened::
1797
1798            Annotated[Annotated[T, Ann1, Ann2], Ann3] == Annotated[T, Ann1, Ann2, Ann3]
1799
1800        - Instantiating an annotated type is equivalent to instantiating the
1801        underlying type::
1802
1803            Annotated[C, Ann1](5) == C(5)
1804
1805        - Annotated can be used as a generic type alias::
1806
1807            Optimized = Annotated[T, runtime.Optimize()]
1808            Optimized[int] == Annotated[int, runtime.Optimize()]
1809
1810            OptimizedList = Annotated[List[T], runtime.Optimize()]
1811            OptimizedList[int] == Annotated[List[int], runtime.Optimize()]
1812        """
1813
1814        __slots__ = ()
1815
1816        def __new__(cls, *args, **kwargs):
1817            raise TypeError("Type Annotated cannot be instantiated.")
1818
1819        @_tp_cache
1820        def __class_getitem__(cls, params):
1821            if not isinstance(params, tuple) or len(params) < 2:
1822                raise TypeError("Annotated[...] should be used "
1823                                "with at least two arguments (a type and an "
1824                                "annotation).")
1825            msg = "Annotated[t, ...]: t must be a type."
1826            origin = typing._type_check(params[0], msg)
1827            metadata = tuple(params[1:])
1828            return _AnnotatedAlias(origin, metadata)
1829
1830        def __init_subclass__(cls, *args, **kwargs):
1831            raise TypeError(
1832                "Cannot subclass {}.Annotated".format(cls.__module__)
1833            )
1834
1835    def _strip_annotations(t):
1836        """Strips the annotations from a given type.
1837        """
1838        if isinstance(t, _AnnotatedAlias):
1839            return _strip_annotations(t.__origin__)
1840        if isinstance(t, typing._GenericAlias):
1841            stripped_args = tuple(_strip_annotations(a) for a in t.__args__)
1842            if stripped_args == t.__args__:
1843                return t
1844            res = t.copy_with(stripped_args)
1845            res._special = t._special
1846            return res
1847        return t
1848
1849    def get_type_hints(obj, globalns=None, localns=None, include_extras=False):
1850        """Return type hints for an object.
1851
1852        This is often the same as obj.__annotations__, but it handles
1853        forward references encoded as string literals, adds Optional[t] if a
1854        default value equal to None is set and recursively replaces all
1855        'Annotated[T, ...]' with 'T' (unless 'include_extras=True').
1856
1857        The argument may be a module, class, method, or function. The annotations
1858        are returned as a dictionary. For classes, annotations include also
1859        inherited members.
1860
1861        TypeError is raised if the argument is not of a type that can contain
1862        annotations, and an empty dictionary is returned if no annotations are
1863        present.
1864
1865        BEWARE -- the behavior of globalns and localns is counterintuitive
1866        (unless you are familiar with how eval() and exec() work).  The
1867        search order is locals first, then globals.
1868
1869        - If no dict arguments are passed, an attempt is made to use the
1870          globals from obj (or the respective module's globals for classes),
1871          and these are also used as the locals.  If the object does not appear
1872          to have globals, an empty dictionary is used.
1873
1874        - If one dict argument is passed, it is used for both globals and
1875          locals.
1876
1877        - If two dict arguments are passed, they specify globals and
1878          locals, respectively.
1879        """
1880        hint = typing.get_type_hints(obj, globalns=globalns, localns=localns)
1881        if include_extras:
1882            return hint
1883        return {k: _strip_annotations(t) for k, t in hint.items()}
1884
1885elif HAVE_ANNOTATED:
1886
1887    def _is_dunder(name):
1888        """Returns True if name is a __dunder_variable_name__."""
1889        return len(name) > 4 and name.startswith('__') and name.endswith('__')
1890
1891    # Prior to Python 3.7 types did not have `copy_with`. A lot of the equality
1892    # checks, argument expansion etc. are done on the _subs_tre. As a result we
1893    # can't provide a get_type_hints function that strips out annotations.
1894
1895    class AnnotatedMeta(typing.GenericMeta):
1896        """Metaclass for Annotated"""
1897
1898        def __new__(cls, name, bases, namespace, **kwargs):
1899            if any(b is not object for b in bases):
1900                raise TypeError("Cannot subclass " + str(Annotated))
1901            return super().__new__(cls, name, bases, namespace, **kwargs)
1902
1903        @property
1904        def __metadata__(self):
1905            return self._subs_tree()[2]
1906
1907        def _tree_repr(self, tree):
1908            cls, origin, metadata = tree
1909            if not isinstance(origin, tuple):
1910                tp_repr = typing._type_repr(origin)
1911            else:
1912                tp_repr = origin[0]._tree_repr(origin)
1913            metadata_reprs = ", ".join(repr(arg) for arg in metadata)
1914            return '%s[%s, %s]' % (cls, tp_repr, metadata_reprs)
1915
1916        def _subs_tree(self, tvars=None, args=None):  # noqa
1917            if self is Annotated:
1918                return Annotated
1919            res = super()._subs_tree(tvars=tvars, args=args)
1920            # Flatten nested Annotated
1921            if isinstance(res[1], tuple) and res[1][0] is Annotated:
1922                sub_tp = res[1][1]
1923                sub_annot = res[1][2]
1924                return (Annotated, sub_tp, sub_annot + res[2])
1925            return res
1926
1927        def _get_cons(self):
1928            """Return the class used to create instance of this type."""
1929            if self.__origin__ is None:
1930                raise TypeError("Cannot get the underlying type of a "
1931                                "non-specialized Annotated type.")
1932            tree = self._subs_tree()
1933            while isinstance(tree, tuple) and tree[0] is Annotated:
1934                tree = tree[1]
1935            if isinstance(tree, tuple):
1936                return tree[0]
1937            else:
1938                return tree
1939
1940        @_tp_cache
1941        def __getitem__(self, params):
1942            if not isinstance(params, tuple):
1943                params = (params,)
1944            if self.__origin__ is not None:  # specializing an instantiated type
1945                return super().__getitem__(params)
1946            elif not isinstance(params, tuple) or len(params) < 2:
1947                raise TypeError("Annotated[...] should be instantiated "
1948                                "with at least two arguments (a type and an "
1949                                "annotation).")
1950            else:
1951                msg = "Annotated[t, ...]: t must be a type."
1952                tp = typing._type_check(params[0], msg)
1953                metadata = tuple(params[1:])
1954            return self.__class__(
1955                self.__name__,
1956                self.__bases__,
1957                _no_slots_copy(self.__dict__),
1958                tvars=_type_vars((tp,)),
1959                # Metadata is a tuple so it won't be touched by _replace_args et al.
1960                args=(tp, metadata),
1961                origin=self,
1962            )
1963
1964        def __call__(self, *args, **kwargs):
1965            cons = self._get_cons()
1966            result = cons(*args, **kwargs)
1967            try:
1968                result.__orig_class__ = self
1969            except AttributeError:
1970                pass
1971            return result
1972
1973        def __getattr__(self, attr):
1974            # For simplicity we just don't relay all dunder names
1975            if self.__origin__ is not None and not _is_dunder(attr):
1976                return getattr(self._get_cons(), attr)
1977            raise AttributeError(attr)
1978
1979        def __setattr__(self, attr, value):
1980            if _is_dunder(attr) or attr.startswith('_abc_'):
1981                super().__setattr__(attr, value)
1982            elif self.__origin__ is None:
1983                raise AttributeError(attr)
1984            else:
1985                setattr(self._get_cons(), attr, value)
1986
1987        def __instancecheck__(self, obj):
1988            raise TypeError("Annotated cannot be used with isinstance().")
1989
1990        def __subclasscheck__(self, cls):
1991            raise TypeError("Annotated cannot be used with issubclass().")
1992
1993    class Annotated(metaclass=AnnotatedMeta):
1994        """Add context specific metadata to a type.
1995
1996        Example: Annotated[int, runtime_check.Unsigned] indicates to the
1997        hypothetical runtime_check module that this type is an unsigned int.
1998        Every other consumer of this type can ignore this metadata and treat
1999        this type as int.
2000
2001        The first argument to Annotated must be a valid type, the remaining
2002        arguments are kept as a tuple in the __metadata__ field.
2003
2004        Details:
2005
2006        - It's an error to call `Annotated` with less than two arguments.
2007        - Nested Annotated are flattened::
2008
2009            Annotated[Annotated[T, Ann1, Ann2], Ann3] == Annotated[T, Ann1, Ann2, Ann3]
2010
2011        - Instantiating an annotated type is equivalent to instantiating the
2012        underlying type::
2013
2014            Annotated[C, Ann1](5) == C(5)
2015
2016        - Annotated can be used as a generic type alias::
2017
2018            Optimized = Annotated[T, runtime.Optimize()]
2019            Optimized[int] == Annotated[int, runtime.Optimize()]
2020
2021            OptimizedList = Annotated[List[T], runtime.Optimize()]
2022            OptimizedList[int] == Annotated[List[int], runtime.Optimize()]
2023        """
2024
2025# Python 3.8 has get_origin() and get_args() but those implementations aren't
2026# Annotated-aware, so we can't use those, only Python 3.9 versions will do.
2027if sys.version_info[:2] >= (3, 9):
2028    get_origin = typing.get_origin
2029    get_args = typing.get_args
2030elif PEP_560:
2031    from typing import _GenericAlias  # noqa
2032
2033    def get_origin(tp):
2034        """Get the unsubscripted version of a type.
2035
2036        This supports generic types, Callable, Tuple, Union, Literal, Final, ClassVar
2037        and Annotated. Return None for unsupported types. Examples::
2038
2039            get_origin(Literal[42]) is Literal
2040            get_origin(int) is None
2041            get_origin(ClassVar[int]) is ClassVar
2042            get_origin(Generic) is Generic
2043            get_origin(Generic[T]) is Generic
2044            get_origin(Union[T, int]) is Union
2045            get_origin(List[Tuple[T, T]][int]) == list
2046        """
2047        if isinstance(tp, _AnnotatedAlias):
2048            return Annotated
2049        if isinstance(tp, _GenericAlias):
2050            return tp.__origin__
2051        if tp is Generic:
2052            return Generic
2053        return None
2054
2055    def get_args(tp):
2056        """Get type arguments with all substitutions performed.
2057
2058        For unions, basic simplifications used by Union constructor are performed.
2059        Examples::
2060            get_args(Dict[str, int]) == (str, int)
2061            get_args(int) == ()
2062            get_args(Union[int, Union[T, int], str][int]) == (int, str)
2063            get_args(Union[int, Tuple[T, int]][str]) == (int, Tuple[str, int])
2064            get_args(Callable[[], T][int]) == ([], int)
2065        """
2066        if isinstance(tp, _AnnotatedAlias):
2067            return (tp.__origin__,) + tp.__metadata__
2068        if isinstance(tp, _GenericAlias):
2069            res = tp.__args__
2070            if get_origin(tp) is collections.abc.Callable and res[0] is not Ellipsis:
2071                res = (list(res[:-1]), res[-1])
2072            return res
2073        return ()
2074
2075
2076if hasattr(typing, 'TypeAlias'):
2077    TypeAlias = typing.TypeAlias
2078elif sys.version_info[:2] >= (3, 9):
2079    class _TypeAliasForm(typing._SpecialForm, _root=True):
2080        def __repr__(self):
2081            return 'typing_extensions.' + self._name
2082
2083    @_TypeAliasForm
2084    def TypeAlias(self, parameters):
2085        """Special marker indicating that an assignment should
2086        be recognized as a proper type alias definition by type
2087        checkers.
2088
2089        For example::
2090
2091            Predicate: TypeAlias = Callable[..., bool]
2092
2093        It's invalid when used anywhere except as in the example above.
2094        """
2095        raise TypeError("{} is not subscriptable".format(self))
2096
2097elif sys.version_info[:2] >= (3, 7):
2098    class _TypeAliasForm(typing._SpecialForm, _root=True):
2099        def __repr__(self):
2100            return 'typing_extensions.' + self._name
2101
2102    TypeAlias = _TypeAliasForm('TypeAlias',
2103                               doc="""Special marker indicating that an assignment should
2104                               be recognized as a proper type alias definition by type
2105                               checkers.
2106
2107                               For example::
2108
2109                                   Predicate: TypeAlias = Callable[..., bool]
2110
2111                               It's invalid when used anywhere except as in the example
2112                               above.""")
2113
2114elif hasattr(typing, '_FinalTypingBase'):
2115    class _TypeAliasMeta(typing.TypingMeta):
2116        """Metaclass for TypeAlias"""
2117
2118        def __repr__(self):
2119            return 'typing_extensions.TypeAlias'
2120
2121    class _TypeAliasBase(typing._FinalTypingBase, metaclass=_TypeAliasMeta, _root=True):
2122        """Special marker indicating that an assignment should
2123        be recognized as a proper type alias definition by type
2124        checkers.
2125
2126        For example::
2127
2128            Predicate: TypeAlias = Callable[..., bool]
2129
2130        It's invalid when used anywhere except as in the example above.
2131        """
2132        __slots__ = ()
2133
2134        def __instancecheck__(self, obj):
2135            raise TypeError("TypeAlias cannot be used with isinstance().")
2136
2137        def __subclasscheck__(self, cls):
2138            raise TypeError("TypeAlias cannot be used with issubclass().")
2139
2140        def __repr__(self):
2141            return 'typing_extensions.TypeAlias'
2142
2143    TypeAlias = _TypeAliasBase(_root=True)
2144else:
2145    class _TypeAliasMeta(typing.TypingMeta):
2146        """Metaclass for TypeAlias"""
2147
2148        def __instancecheck__(self, obj):
2149            raise TypeError("TypeAlias cannot be used with isinstance().")
2150
2151        def __subclasscheck__(self, cls):
2152            raise TypeError("TypeAlias cannot be used with issubclass().")
2153
2154        def __call__(self, *args, **kwargs):
2155            raise TypeError("Cannot instantiate TypeAlias")
2156
2157    class TypeAlias(metaclass=_TypeAliasMeta, _root=True):
2158        """Special marker indicating that an assignment should
2159        be recognized as a proper type alias definition by type
2160        checkers.
2161
2162        For example::
2163
2164            Predicate: TypeAlias = Callable[..., bool]
2165
2166        It's invalid when used anywhere except as in the example above.
2167        """
2168        __slots__ = ()
2169