• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1import abc
2import collections
3import collections.abc
4import operator
5import sys
6import types as _types
7import typing
8
9
10# Please keep __all__ alphabetized within each category.
11__all__ = [
12    # Super-special typing primitives.
13    'ClassVar',
14    'Concatenate',
15    'Final',
16    'LiteralString',
17    'ParamSpec',
18    'Self',
19    'Type',
20    'TypeVarTuple',
21    'Unpack',
22
23    # ABCs (from collections.abc).
24    'Awaitable',
25    'AsyncIterator',
26    'AsyncIterable',
27    'Coroutine',
28    'AsyncGenerator',
29    'AsyncContextManager',
30    'ChainMap',
31
32    # Concrete collection types.
33    'ContextManager',
34    'Counter',
35    'Deque',
36    'DefaultDict',
37    'OrderedDict',
38    'TypedDict',
39
40    # Structural checks, a.k.a. protocols.
41    'SupportsIndex',
42
43    # One-off things.
44    'Annotated',
45    'assert_never',
46    'dataclass_transform',
47    'final',
48    'get_args',
49    'get_origin',
50    'get_type_hints',
51    'IntVar',
52    'is_typeddict',
53    'Literal',
54    'NewType',
55    'overload',
56    'Protocol',
57    'reveal_type',
58    'runtime',
59    'runtime_checkable',
60    'Text',
61    'TypeAlias',
62    'TypeGuard',
63    'TYPE_CHECKING',
64    'Never',
65    'NoReturn',
66    'Required',
67    'NotRequired',
68]
69
70# for backward compatibility
71PEP_560 = True
72GenericMeta = type
73
74# The functions below are modified copies of typing internal helpers.
75# They are needed by _ProtocolMeta and they provide support for PEP 646.
76
77_marker = object()
78
79
80def _check_generic(cls, parameters, elen=_marker):
81    """Check correct count for parameters of a generic cls (internal helper).
82    This gives a nice error message in case of count mismatch.
83    """
84    if not elen:
85        raise TypeError(f"{cls} is not a generic class")
86    if elen is _marker:
87        if not hasattr(cls, "__parameters__") or not cls.__parameters__:
88            raise TypeError(f"{cls} is not a generic class")
89        elen = len(cls.__parameters__)
90    alen = len(parameters)
91    if alen != elen:
92        if hasattr(cls, "__parameters__"):
93            parameters = [p for p in cls.__parameters__ if not _is_unpack(p)]
94            num_tv_tuples = sum(isinstance(p, TypeVarTuple) for p in parameters)
95            if (num_tv_tuples > 0) and (alen >= elen - num_tv_tuples):
96                return
97        raise TypeError(f"Too {'many' if alen > elen else 'few'} parameters for {cls};"
98                        f" actual {alen}, expected {elen}")
99
100
101if sys.version_info >= (3, 10):
102    def _should_collect_from_parameters(t):
103        return isinstance(
104            t, (typing._GenericAlias, _types.GenericAlias, _types.UnionType)
105        )
106elif sys.version_info >= (3, 9):
107    def _should_collect_from_parameters(t):
108        return isinstance(t, (typing._GenericAlias, _types.GenericAlias))
109else:
110    def _should_collect_from_parameters(t):
111        return isinstance(t, typing._GenericAlias) and not t._special
112
113
114def _collect_type_vars(types, typevar_types=None):
115    """Collect all type variable contained in types in order of
116    first appearance (lexicographic order). For example::
117
118        _collect_type_vars((T, List[S, T])) == (T, S)
119    """
120    if typevar_types is None:
121        typevar_types = typing.TypeVar
122    tvars = []
123    for t in types:
124        if (
125            isinstance(t, typevar_types) and
126            t not in tvars and
127            not _is_unpack(t)
128        ):
129            tvars.append(t)
130        if _should_collect_from_parameters(t):
131            tvars.extend([t for t in t.__parameters__ if t not in tvars])
132    return tuple(tvars)
133
134
135NoReturn = typing.NoReturn
136
137# Some unconstrained type variables.  These are used by the container types.
138# (These are not for export.)
139T = typing.TypeVar('T')  # Any type.
140KT = typing.TypeVar('KT')  # Key type.
141VT = typing.TypeVar('VT')  # Value type.
142T_co = typing.TypeVar('T_co', covariant=True)  # Any type covariant containers.
143T_contra = typing.TypeVar('T_contra', contravariant=True)  # Ditto contravariant.
144
145ClassVar = typing.ClassVar
146
147# On older versions of typing there is an internal class named "Final".
148# 3.8+
149if hasattr(typing, 'Final') and sys.version_info[:2] >= (3, 7):
150    Final = typing.Final
151# 3.7
152else:
153    class _FinalForm(typing._SpecialForm, _root=True):
154
155        def __repr__(self):
156            return 'typing_extensions.' + self._name
157
158        def __getitem__(self, parameters):
159            item = typing._type_check(parameters,
160                                      f'{self._name} accepts only single type')
161            return typing._GenericAlias(self, (item,))
162
163    Final = _FinalForm('Final',
164                       doc="""A special typing construct to indicate that a name
165                       cannot be re-assigned or overridden in a subclass.
166                       For example:
167
168                           MAX_SIZE: Final = 9000
169                           MAX_SIZE += 1  # Error reported by type checker
170
171                           class Connection:
172                               TIMEOUT: Final[int] = 10
173                           class FastConnector(Connection):
174                               TIMEOUT = 1  # Error reported by type checker
175
176                       There is no runtime checking of these properties.""")
177
178if sys.version_info >= (3, 11):
179    final = typing.final
180else:
181    # @final exists in 3.8+, but we backport it for all versions
182    # before 3.11 to keep support for the __final__ attribute.
183    # See https://bugs.python.org/issue46342
184    def final(f):
185        """This decorator can be used to indicate to type checkers that
186        the decorated method cannot be overridden, and decorated class
187        cannot be subclassed. For example:
188
189            class Base:
190                @final
191                def done(self) -> None:
192                    ...
193            class Sub(Base):
194                def done(self) -> None:  # Error reported by type checker
195                    ...
196            @final
197            class Leaf:
198                ...
199            class Other(Leaf):  # Error reported by type checker
200                ...
201
202        There is no runtime checking of these properties. The decorator
203        sets the ``__final__`` attribute to ``True`` on the decorated object
204        to allow runtime introspection.
205        """
206        try:
207            f.__final__ = True
208        except (AttributeError, TypeError):
209            # Skip the attribute silently if it is not writable.
210            # AttributeError happens if the object has __slots__ or a
211            # read-only property, TypeError if it's a builtin class.
212            pass
213        return f
214
215
216def IntVar(name):
217    return typing.TypeVar(name)
218
219
220# 3.8+:
221if hasattr(typing, 'Literal'):
222    Literal = typing.Literal
223# 3.7:
224else:
225    class _LiteralForm(typing._SpecialForm, _root=True):
226
227        def __repr__(self):
228            return 'typing_extensions.' + self._name
229
230        def __getitem__(self, parameters):
231            return typing._GenericAlias(self, parameters)
232
233    Literal = _LiteralForm('Literal',
234                           doc="""A type that can be used to indicate to type checkers
235                           that the corresponding value has a value literally equivalent
236                           to the provided parameter. For example:
237
238                               var: Literal[4] = 4
239
240                           The type checker understands that 'var' is literally equal to
241                           the value 4 and no other value.
242
243                           Literal[...] cannot be subclassed. There is no runtime
244                           checking verifying that the parameter is actually a value
245                           instead of a type.""")
246
247
248_overload_dummy = typing._overload_dummy  # noqa
249overload = typing.overload
250
251
252# This is not a real generic class.  Don't use outside annotations.
253Type = typing.Type
254
255# Various ABCs mimicking those in collections.abc.
256# A few are simply re-exported for completeness.
257
258
259Awaitable = typing.Awaitable
260Coroutine = typing.Coroutine
261AsyncIterable = typing.AsyncIterable
262AsyncIterator = typing.AsyncIterator
263Deque = typing.Deque
264ContextManager = typing.ContextManager
265AsyncContextManager = typing.AsyncContextManager
266DefaultDict = typing.DefaultDict
267
268# 3.7.2+
269if hasattr(typing, 'OrderedDict'):
270    OrderedDict = typing.OrderedDict
271# 3.7.0-3.7.2
272else:
273    OrderedDict = typing._alias(collections.OrderedDict, (KT, VT))
274
275Counter = typing.Counter
276ChainMap = typing.ChainMap
277AsyncGenerator = typing.AsyncGenerator
278NewType = typing.NewType
279Text = typing.Text
280TYPE_CHECKING = typing.TYPE_CHECKING
281
282
283_PROTO_WHITELIST = ['Callable', 'Awaitable',
284                    'Iterable', 'Iterator', 'AsyncIterable', 'AsyncIterator',
285                    'Hashable', 'Sized', 'Container', 'Collection', 'Reversible',
286                    'ContextManager', 'AsyncContextManager']
287
288
289def _get_protocol_attrs(cls):
290    attrs = set()
291    for base in cls.__mro__[:-1]:  # without object
292        if base.__name__ in ('Protocol', 'Generic'):
293            continue
294        annotations = getattr(base, '__annotations__', {})
295        for attr in list(base.__dict__.keys()) + list(annotations.keys()):
296            if (not attr.startswith('_abc_') and attr not in (
297                    '__abstractmethods__', '__annotations__', '__weakref__',
298                    '_is_protocol', '_is_runtime_protocol', '__dict__',
299                    '__args__', '__slots__',
300                    '__next_in_mro__', '__parameters__', '__origin__',
301                    '__orig_bases__', '__extra__', '__tree_hash__',
302                    '__doc__', '__subclasshook__', '__init__', '__new__',
303                    '__module__', '_MutableMapping__marker', '_gorg')):
304                attrs.add(attr)
305    return attrs
306
307
308def _is_callable_members_only(cls):
309    return all(callable(getattr(cls, attr, None)) for attr in _get_protocol_attrs(cls))
310
311
312# 3.8+
313if hasattr(typing, 'Protocol'):
314    Protocol = typing.Protocol
315# 3.7
316else:
317
318    def _no_init(self, *args, **kwargs):
319        if type(self)._is_protocol:
320            raise TypeError('Protocols cannot be instantiated')
321
322    class _ProtocolMeta(abc.ABCMeta):
323        # This metaclass is a bit unfortunate and exists only because of the lack
324        # of __instancehook__.
325        def __instancecheck__(cls, instance):
326            # We need this method for situations where attributes are
327            # assigned in __init__.
328            if ((not getattr(cls, '_is_protocol', False) or
329                 _is_callable_members_only(cls)) and
330                    issubclass(instance.__class__, cls)):
331                return True
332            if cls._is_protocol:
333                if all(hasattr(instance, attr) and
334                       (not callable(getattr(cls, attr, None)) or
335                        getattr(instance, attr) is not None)
336                       for attr in _get_protocol_attrs(cls)):
337                    return True
338            return super().__instancecheck__(instance)
339
340    class Protocol(metaclass=_ProtocolMeta):
341        # There is quite a lot of overlapping code with typing.Generic.
342        # Unfortunately it is hard to avoid this while these live in two different
343        # modules. The duplicated code will be removed when Protocol is moved to typing.
344        """Base class for protocol classes. Protocol classes are defined as::
345
346            class Proto(Protocol):
347                def meth(self) -> int:
348                    ...
349
350        Such classes are primarily used with static type checkers that recognize
351        structural subtyping (static duck-typing), for example::
352
353            class C:
354                def meth(self) -> int:
355                    return 0
356
357            def func(x: Proto) -> int:
358                return x.meth()
359
360            func(C())  # Passes static type check
361
362        See PEP 544 for details. Protocol classes decorated with
363        @typing_extensions.runtime act as simple-minded runtime protocol that checks
364        only the presence of given attributes, ignoring their type signatures.
365
366        Protocol classes can be generic, they are defined as::
367
368            class GenProto(Protocol[T]):
369                def meth(self) -> T:
370                    ...
371        """
372        __slots__ = ()
373        _is_protocol = True
374
375        def __new__(cls, *args, **kwds):
376            if cls is Protocol:
377                raise TypeError("Type Protocol cannot be instantiated; "
378                                "it can only be used as a base class")
379            return super().__new__(cls)
380
381        @typing._tp_cache
382        def __class_getitem__(cls, params):
383            if not isinstance(params, tuple):
384                params = (params,)
385            if not params and cls is not typing.Tuple:
386                raise TypeError(
387                    f"Parameter list to {cls.__qualname__}[...] cannot be empty")
388            msg = "Parameters to generic types must be types."
389            params = tuple(typing._type_check(p, msg) for p in params)  # noqa
390            if cls is Protocol:
391                # Generic can only be subscripted with unique type variables.
392                if not all(isinstance(p, typing.TypeVar) for p in params):
393                    i = 0
394                    while isinstance(params[i], typing.TypeVar):
395                        i += 1
396                    raise TypeError(
397                        "Parameters to Protocol[...] must all be type variables."
398                        f" Parameter {i + 1} is {params[i]}")
399                if len(set(params)) != len(params):
400                    raise TypeError(
401                        "Parameters to Protocol[...] must all be unique")
402            else:
403                # Subscripting a regular Generic subclass.
404                _check_generic(cls, params, len(cls.__parameters__))
405            return typing._GenericAlias(cls, params)
406
407        def __init_subclass__(cls, *args, **kwargs):
408            tvars = []
409            if '__orig_bases__' in cls.__dict__:
410                error = typing.Generic in cls.__orig_bases__
411            else:
412                error = typing.Generic in cls.__bases__
413            if error:
414                raise TypeError("Cannot inherit from plain Generic")
415            if '__orig_bases__' in cls.__dict__:
416                tvars = typing._collect_type_vars(cls.__orig_bases__)
417                # Look for Generic[T1, ..., Tn] or Protocol[T1, ..., Tn].
418                # If found, tvars must be a subset of it.
419                # If not found, tvars is it.
420                # Also check for and reject plain Generic,
421                # and reject multiple Generic[...] and/or Protocol[...].
422                gvars = None
423                for base in cls.__orig_bases__:
424                    if (isinstance(base, typing._GenericAlias) and
425                            base.__origin__ in (typing.Generic, Protocol)):
426                        # for error messages
427                        the_base = base.__origin__.__name__
428                        if gvars is not None:
429                            raise TypeError(
430                                "Cannot inherit from Generic[...]"
431                                " and/or Protocol[...] multiple types.")
432                        gvars = base.__parameters__
433                if gvars is None:
434                    gvars = tvars
435                else:
436                    tvarset = set(tvars)
437                    gvarset = set(gvars)
438                    if not tvarset <= gvarset:
439                        s_vars = ', '.join(str(t) for t in tvars if t not in gvarset)
440                        s_args = ', '.join(str(g) for g in gvars)
441                        raise TypeError(f"Some type variables ({s_vars}) are"
442                                        f" not listed in {the_base}[{s_args}]")
443                    tvars = gvars
444            cls.__parameters__ = tuple(tvars)
445
446            # Determine if this is a protocol or a concrete subclass.
447            if not cls.__dict__.get('_is_protocol', None):
448                cls._is_protocol = any(b is Protocol for b in cls.__bases__)
449
450            # Set (or override) the protocol subclass hook.
451            def _proto_hook(other):
452                if not cls.__dict__.get('_is_protocol', None):
453                    return NotImplemented
454                if not getattr(cls, '_is_runtime_protocol', False):
455                    if sys._getframe(2).f_globals['__name__'] in ['abc', 'functools']:
456                        return NotImplemented
457                    raise TypeError("Instance and class checks can only be used with"
458                                    " @runtime protocols")
459                if not _is_callable_members_only(cls):
460                    if sys._getframe(2).f_globals['__name__'] in ['abc', 'functools']:
461                        return NotImplemented
462                    raise TypeError("Protocols with non-method members"
463                                    " don't support issubclass()")
464                if not isinstance(other, type):
465                    # Same error as for issubclass(1, int)
466                    raise TypeError('issubclass() arg 1 must be a class')
467                for attr in _get_protocol_attrs(cls):
468                    for base in other.__mro__:
469                        if attr in base.__dict__:
470                            if base.__dict__[attr] is None:
471                                return NotImplemented
472                            break
473                        annotations = getattr(base, '__annotations__', {})
474                        if (isinstance(annotations, typing.Mapping) and
475                                attr in annotations and
476                                isinstance(other, _ProtocolMeta) and
477                                other._is_protocol):
478                            break
479                    else:
480                        return NotImplemented
481                return True
482            if '__subclasshook__' not in cls.__dict__:
483                cls.__subclasshook__ = _proto_hook
484
485            # We have nothing more to do for non-protocols.
486            if not cls._is_protocol:
487                return
488
489            # Check consistency of bases.
490            for base in cls.__bases__:
491                if not (base in (object, typing.Generic) or
492                        base.__module__ == 'collections.abc' and
493                        base.__name__ in _PROTO_WHITELIST or
494                        isinstance(base, _ProtocolMeta) and base._is_protocol):
495                    raise TypeError('Protocols can only inherit from other'
496                                    f' protocols, got {repr(base)}')
497            cls.__init__ = _no_init
498
499
500# 3.8+
501if hasattr(typing, 'runtime_checkable'):
502    runtime_checkable = typing.runtime_checkable
503# 3.7
504else:
505    def runtime_checkable(cls):
506        """Mark a protocol class as a runtime protocol, so that it
507        can be used with isinstance() and issubclass(). Raise TypeError
508        if applied to a non-protocol class.
509
510        This allows a simple-minded structural check very similar to the
511        one-offs in collections.abc such as Hashable.
512        """
513        if not isinstance(cls, _ProtocolMeta) or not cls._is_protocol:
514            raise TypeError('@runtime_checkable can be only applied to protocol classes,'
515                            f' got {cls!r}')
516        cls._is_runtime_protocol = True
517        return cls
518
519
520# Exists for backwards compatibility.
521runtime = runtime_checkable
522
523
524# 3.8+
525if hasattr(typing, 'SupportsIndex'):
526    SupportsIndex = typing.SupportsIndex
527# 3.7
528else:
529    @runtime_checkable
530    class SupportsIndex(Protocol):
531        __slots__ = ()
532
533        @abc.abstractmethod
534        def __index__(self) -> int:
535            pass
536
537
538if hasattr(typing, "Required"):
539    # The standard library TypedDict in Python 3.8 does not store runtime information
540    # about which (if any) keys are optional.  See https://bugs.python.org/issue38834
541    # The standard library TypedDict in Python 3.9.0/1 does not honour the "total"
542    # keyword with old-style TypedDict().  See https://bugs.python.org/issue42059
543    # The standard library TypedDict below Python 3.11 does not store runtime
544    # information about optional and required keys when using Required or NotRequired.
545    TypedDict = typing.TypedDict
546    _TypedDictMeta = typing._TypedDictMeta
547    is_typeddict = typing.is_typeddict
548else:
549    def _check_fails(cls, other):
550        try:
551            if sys._getframe(1).f_globals['__name__'] not in ['abc',
552                                                              'functools',
553                                                              'typing']:
554                # Typed dicts are only for static structural subtyping.
555                raise TypeError('TypedDict does not support instance and class checks')
556        except (AttributeError, ValueError):
557            pass
558        return False
559
560    def _dict_new(*args, **kwargs):
561        if not args:
562            raise TypeError('TypedDict.__new__(): not enough arguments')
563        _, args = args[0], args[1:]  # allow the "cls" keyword be passed
564        return dict(*args, **kwargs)
565
566    _dict_new.__text_signature__ = '($cls, _typename, _fields=None, /, **kwargs)'
567
568    def _typeddict_new(*args, total=True, **kwargs):
569        if not args:
570            raise TypeError('TypedDict.__new__(): not enough arguments')
571        _, args = args[0], args[1:]  # allow the "cls" keyword be passed
572        if args:
573            typename, args = args[0], args[1:]  # allow the "_typename" keyword be passed
574        elif '_typename' in kwargs:
575            typename = kwargs.pop('_typename')
576            import warnings
577            warnings.warn("Passing '_typename' as keyword argument is deprecated",
578                          DeprecationWarning, stacklevel=2)
579        else:
580            raise TypeError("TypedDict.__new__() missing 1 required positional "
581                            "argument: '_typename'")
582        if args:
583            try:
584                fields, = args  # allow the "_fields" keyword be passed
585            except ValueError:
586                raise TypeError('TypedDict.__new__() takes from 2 to 3 '
587                                f'positional arguments but {len(args) + 2} '
588                                'were given')
589        elif '_fields' in kwargs and len(kwargs) == 1:
590            fields = kwargs.pop('_fields')
591            import warnings
592            warnings.warn("Passing '_fields' as keyword argument is deprecated",
593                          DeprecationWarning, stacklevel=2)
594        else:
595            fields = None
596
597        if fields is None:
598            fields = kwargs
599        elif kwargs:
600            raise TypeError("TypedDict takes either a dict or keyword arguments,"
601                            " but not both")
602
603        ns = {'__annotations__': dict(fields)}
604        try:
605            # Setting correct module is necessary to make typed dict classes pickleable.
606            ns['__module__'] = sys._getframe(1).f_globals.get('__name__', '__main__')
607        except (AttributeError, ValueError):
608            pass
609
610        return _TypedDictMeta(typename, (), ns, total=total)
611
612    _typeddict_new.__text_signature__ = ('($cls, _typename, _fields=None,'
613                                         ' /, *, total=True, **kwargs)')
614
615    class _TypedDictMeta(type):
616        def __init__(cls, name, bases, ns, total=True):
617            super().__init__(name, bases, ns)
618
619        def __new__(cls, name, bases, ns, total=True):
620            # Create new typed dict class object.
621            # This method is called directly when TypedDict is subclassed,
622            # or via _typeddict_new when TypedDict is instantiated. This way
623            # TypedDict supports all three syntaxes described in its docstring.
624            # Subclasses and instances of TypedDict return actual dictionaries
625            # via _dict_new.
626            ns['__new__'] = _typeddict_new if name == 'TypedDict' else _dict_new
627            tp_dict = super().__new__(cls, name, (dict,), ns)
628
629            annotations = {}
630            own_annotations = ns.get('__annotations__', {})
631            msg = "TypedDict('Name', {f0: t0, f1: t1, ...}); each t must be a type"
632            own_annotations = {
633                n: typing._type_check(tp, msg) for n, tp in own_annotations.items()
634            }
635            required_keys = set()
636            optional_keys = set()
637
638            for base in bases:
639                annotations.update(base.__dict__.get('__annotations__', {}))
640                required_keys.update(base.__dict__.get('__required_keys__', ()))
641                optional_keys.update(base.__dict__.get('__optional_keys__', ()))
642
643            annotations.update(own_annotations)
644            for annotation_key, annotation_type in own_annotations.items():
645                annotation_origin = get_origin(annotation_type)
646                if annotation_origin is Annotated:
647                    annotation_args = get_args(annotation_type)
648                    if annotation_args:
649                        annotation_type = annotation_args[0]
650                        annotation_origin = get_origin(annotation_type)
651
652                if annotation_origin is Required:
653                    required_keys.add(annotation_key)
654                elif annotation_origin is NotRequired:
655                    optional_keys.add(annotation_key)
656                elif total:
657                    required_keys.add(annotation_key)
658                else:
659                    optional_keys.add(annotation_key)
660
661            tp_dict.__annotations__ = annotations
662            tp_dict.__required_keys__ = frozenset(required_keys)
663            tp_dict.__optional_keys__ = frozenset(optional_keys)
664            if not hasattr(tp_dict, '__total__'):
665                tp_dict.__total__ = total
666            return tp_dict
667
668        __instancecheck__ = __subclasscheck__ = _check_fails
669
670    TypedDict = _TypedDictMeta('TypedDict', (dict,), {})
671    TypedDict.__module__ = __name__
672    TypedDict.__doc__ = \
673        """A simple typed name space. At runtime it is equivalent to a plain dict.
674
675        TypedDict creates a dictionary type that expects all of its
676        instances to have a certain set of keys, with each key
677        associated with a value of a consistent type. This expectation
678        is not checked at runtime but is only enforced by type checkers.
679        Usage::
680
681            class Point2D(TypedDict):
682                x: int
683                y: int
684                label: str
685
686            a: Point2D = {'x': 1, 'y': 2, 'label': 'good'}  # OK
687            b: Point2D = {'z': 3, 'label': 'bad'}           # Fails type check
688
689            assert Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first')
690
691        The type info can be accessed via the Point2D.__annotations__ dict, and
692        the Point2D.__required_keys__ and Point2D.__optional_keys__ frozensets.
693        TypedDict supports two additional equivalent forms::
694
695            Point2D = TypedDict('Point2D', x=int, y=int, label=str)
696            Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str})
697
698        The class syntax is only supported in Python 3.6+, while two other
699        syntax forms work for Python 2.7 and 3.2+
700        """
701
702    if hasattr(typing, "_TypedDictMeta"):
703        _TYPEDDICT_TYPES = (typing._TypedDictMeta, _TypedDictMeta)
704    else:
705        _TYPEDDICT_TYPES = (_TypedDictMeta,)
706
707    def is_typeddict(tp):
708        """Check if an annotation is a TypedDict class
709
710        For example::
711            class Film(TypedDict):
712                title: str
713                year: int
714
715            is_typeddict(Film)  # => True
716            is_typeddict(Union[list, str])  # => False
717        """
718        return isinstance(tp, tuple(_TYPEDDICT_TYPES))
719
720
721if hasattr(typing, "assert_type"):
722    assert_type = typing.assert_type
723
724else:
725    def assert_type(__val, __typ):
726        """Assert (to the type checker) that the value is of the given type.
727
728        When the type checker encounters a call to assert_type(), it
729        emits an error if the value is not of the specified type::
730
731            def greet(name: str) -> None:
732                assert_type(name, str)  # ok
733                assert_type(name, int)  # type checker error
734
735        At runtime this returns the first argument unchanged and otherwise
736        does nothing.
737        """
738        return __val
739
740
741if hasattr(typing, "Required"):
742    get_type_hints = typing.get_type_hints
743else:
744    import functools
745    import types
746
747    # replaces _strip_annotations()
748    def _strip_extras(t):
749        """Strips Annotated, Required and NotRequired from a given type."""
750        if isinstance(t, _AnnotatedAlias):
751            return _strip_extras(t.__origin__)
752        if hasattr(t, "__origin__") and t.__origin__ in (Required, NotRequired):
753            return _strip_extras(t.__args__[0])
754        if isinstance(t, typing._GenericAlias):
755            stripped_args = tuple(_strip_extras(a) for a in t.__args__)
756            if stripped_args == t.__args__:
757                return t
758            return t.copy_with(stripped_args)
759        if hasattr(types, "GenericAlias") and isinstance(t, types.GenericAlias):
760            stripped_args = tuple(_strip_extras(a) for a in t.__args__)
761            if stripped_args == t.__args__:
762                return t
763            return types.GenericAlias(t.__origin__, stripped_args)
764        if hasattr(types, "UnionType") and isinstance(t, types.UnionType):
765            stripped_args = tuple(_strip_extras(a) for a in t.__args__)
766            if stripped_args == t.__args__:
767                return t
768            return functools.reduce(operator.or_, stripped_args)
769
770        return t
771
772    def get_type_hints(obj, globalns=None, localns=None, include_extras=False):
773        """Return type hints for an object.
774
775        This is often the same as obj.__annotations__, but it handles
776        forward references encoded as string literals, adds Optional[t] if a
777        default value equal to None is set and recursively replaces all
778        'Annotated[T, ...]', 'Required[T]' or 'NotRequired[T]' with 'T'
779        (unless 'include_extras=True').
780
781        The argument may be a module, class, method, or function. The annotations
782        are returned as a dictionary. For classes, annotations include also
783        inherited members.
784
785        TypeError is raised if the argument is not of a type that can contain
786        annotations, and an empty dictionary is returned if no annotations are
787        present.
788
789        BEWARE -- the behavior of globalns and localns is counterintuitive
790        (unless you are familiar with how eval() and exec() work).  The
791        search order is locals first, then globals.
792
793        - If no dict arguments are passed, an attempt is made to use the
794          globals from obj (or the respective module's globals for classes),
795          and these are also used as the locals.  If the object does not appear
796          to have globals, an empty dictionary is used.
797
798        - If one dict argument is passed, it is used for both globals and
799          locals.
800
801        - If two dict arguments are passed, they specify globals and
802          locals, respectively.
803        """
804        if hasattr(typing, "Annotated"):
805            hint = typing.get_type_hints(
806                obj, globalns=globalns, localns=localns, include_extras=True
807            )
808        else:
809            hint = typing.get_type_hints(obj, globalns=globalns, localns=localns)
810        if include_extras:
811            return hint
812        return {k: _strip_extras(t) for k, t in hint.items()}
813
814
815# Python 3.9+ has PEP 593 (Annotated)
816if hasattr(typing, 'Annotated'):
817    Annotated = typing.Annotated
818    # Not exported and not a public API, but needed for get_origin() and get_args()
819    # to work.
820    _AnnotatedAlias = typing._AnnotatedAlias
821# 3.7-3.8
822else:
823    class _AnnotatedAlias(typing._GenericAlias, _root=True):
824        """Runtime representation of an annotated type.
825
826        At its core 'Annotated[t, dec1, dec2, ...]' is an alias for the type 't'
827        with extra annotations. The alias behaves like a normal typing alias,
828        instantiating is the same as instantiating the underlying type, binding
829        it to types is also the same.
830        """
831        def __init__(self, origin, metadata):
832            if isinstance(origin, _AnnotatedAlias):
833                metadata = origin.__metadata__ + metadata
834                origin = origin.__origin__
835            super().__init__(origin, origin)
836            self.__metadata__ = metadata
837
838        def copy_with(self, params):
839            assert len(params) == 1
840            new_type = params[0]
841            return _AnnotatedAlias(new_type, self.__metadata__)
842
843        def __repr__(self):
844            return (f"typing_extensions.Annotated[{typing._type_repr(self.__origin__)}, "
845                    f"{', '.join(repr(a) for a in self.__metadata__)}]")
846
847        def __reduce__(self):
848            return operator.getitem, (
849                Annotated, (self.__origin__,) + self.__metadata__
850            )
851
852        def __eq__(self, other):
853            if not isinstance(other, _AnnotatedAlias):
854                return NotImplemented
855            if self.__origin__ != other.__origin__:
856                return False
857            return self.__metadata__ == other.__metadata__
858
859        def __hash__(self):
860            return hash((self.__origin__, self.__metadata__))
861
862    class Annotated:
863        """Add context specific metadata to a type.
864
865        Example: Annotated[int, runtime_check.Unsigned] indicates to the
866        hypothetical runtime_check module that this type is an unsigned int.
867        Every other consumer of this type can ignore this metadata and treat
868        this type as int.
869
870        The first argument to Annotated must be a valid type (and will be in
871        the __origin__ field), the remaining arguments are kept as a tuple in
872        the __extra__ field.
873
874        Details:
875
876        - It's an error to call `Annotated` with less than two arguments.
877        - Nested Annotated are flattened::
878
879            Annotated[Annotated[T, Ann1, Ann2], Ann3] == Annotated[T, Ann1, Ann2, Ann3]
880
881        - Instantiating an annotated type is equivalent to instantiating the
882        underlying type::
883
884            Annotated[C, Ann1](5) == C(5)
885
886        - Annotated can be used as a generic type alias::
887
888            Optimized = Annotated[T, runtime.Optimize()]
889            Optimized[int] == Annotated[int, runtime.Optimize()]
890
891            OptimizedList = Annotated[List[T], runtime.Optimize()]
892            OptimizedList[int] == Annotated[List[int], runtime.Optimize()]
893        """
894
895        __slots__ = ()
896
897        def __new__(cls, *args, **kwargs):
898            raise TypeError("Type Annotated cannot be instantiated.")
899
900        @typing._tp_cache
901        def __class_getitem__(cls, params):
902            if not isinstance(params, tuple) or len(params) < 2:
903                raise TypeError("Annotated[...] should be used "
904                                "with at least two arguments (a type and an "
905                                "annotation).")
906            allowed_special_forms = (ClassVar, Final)
907            if get_origin(params[0]) in allowed_special_forms:
908                origin = params[0]
909            else:
910                msg = "Annotated[t, ...]: t must be a type."
911                origin = typing._type_check(params[0], msg)
912            metadata = tuple(params[1:])
913            return _AnnotatedAlias(origin, metadata)
914
915        def __init_subclass__(cls, *args, **kwargs):
916            raise TypeError(
917                f"Cannot subclass {cls.__module__}.Annotated"
918            )
919
920# Python 3.8 has get_origin() and get_args() but those implementations aren't
921# Annotated-aware, so we can't use those. Python 3.9's versions don't support
922# ParamSpecArgs and ParamSpecKwargs, so only Python 3.10's versions will do.
923if sys.version_info[:2] >= (3, 10):
924    get_origin = typing.get_origin
925    get_args = typing.get_args
926# 3.7-3.9
927else:
928    try:
929        # 3.9+
930        from typing import _BaseGenericAlias
931    except ImportError:
932        _BaseGenericAlias = typing._GenericAlias
933    try:
934        # 3.9+
935        from typing import GenericAlias
936    except ImportError:
937        GenericAlias = typing._GenericAlias
938
939    def get_origin(tp):
940        """Get the unsubscripted version of a type.
941
942        This supports generic types, Callable, Tuple, Union, Literal, Final, ClassVar
943        and Annotated. Return None for unsupported types. Examples::
944
945            get_origin(Literal[42]) is Literal
946            get_origin(int) is None
947            get_origin(ClassVar[int]) is ClassVar
948            get_origin(Generic) is Generic
949            get_origin(Generic[T]) is Generic
950            get_origin(Union[T, int]) is Union
951            get_origin(List[Tuple[T, T]][int]) == list
952            get_origin(P.args) is P
953        """
954        if isinstance(tp, _AnnotatedAlias):
955            return Annotated
956        if isinstance(tp, (typing._GenericAlias, GenericAlias, _BaseGenericAlias,
957                           ParamSpecArgs, ParamSpecKwargs)):
958            return tp.__origin__
959        if tp is typing.Generic:
960            return typing.Generic
961        return None
962
963    def get_args(tp):
964        """Get type arguments with all substitutions performed.
965
966        For unions, basic simplifications used by Union constructor are performed.
967        Examples::
968            get_args(Dict[str, int]) == (str, int)
969            get_args(int) == ()
970            get_args(Union[int, Union[T, int], str][int]) == (int, str)
971            get_args(Union[int, Tuple[T, int]][str]) == (int, Tuple[str, int])
972            get_args(Callable[[], T][int]) == ([], int)
973        """
974        if isinstance(tp, _AnnotatedAlias):
975            return (tp.__origin__,) + tp.__metadata__
976        if isinstance(tp, (typing._GenericAlias, GenericAlias)):
977            if getattr(tp, "_special", False):
978                return ()
979            res = tp.__args__
980            if get_origin(tp) is collections.abc.Callable and res[0] is not Ellipsis:
981                res = (list(res[:-1]), res[-1])
982            return res
983        return ()
984
985
986# 3.10+
987if hasattr(typing, 'TypeAlias'):
988    TypeAlias = typing.TypeAlias
989# 3.9
990elif sys.version_info[:2] >= (3, 9):
991    class _TypeAliasForm(typing._SpecialForm, _root=True):
992        def __repr__(self):
993            return 'typing_extensions.' + self._name
994
995    @_TypeAliasForm
996    def TypeAlias(self, parameters):
997        """Special marker indicating that an assignment should
998        be recognized as a proper type alias definition by type
999        checkers.
1000
1001        For example::
1002
1003            Predicate: TypeAlias = Callable[..., bool]
1004
1005        It's invalid when used anywhere except as in the example above.
1006        """
1007        raise TypeError(f"{self} is not subscriptable")
1008# 3.7-3.8
1009else:
1010    class _TypeAliasForm(typing._SpecialForm, _root=True):
1011        def __repr__(self):
1012            return 'typing_extensions.' + self._name
1013
1014    TypeAlias = _TypeAliasForm('TypeAlias',
1015                               doc="""Special marker indicating that an assignment should
1016                               be recognized as a proper type alias definition by type
1017                               checkers.
1018
1019                               For example::
1020
1021                                   Predicate: TypeAlias = Callable[..., bool]
1022
1023                               It's invalid when used anywhere except as in the example
1024                               above.""")
1025
1026
1027# Python 3.10+ has PEP 612
1028if hasattr(typing, 'ParamSpecArgs'):
1029    ParamSpecArgs = typing.ParamSpecArgs
1030    ParamSpecKwargs = typing.ParamSpecKwargs
1031# 3.7-3.9
1032else:
1033    class _Immutable:
1034        """Mixin to indicate that object should not be copied."""
1035        __slots__ = ()
1036
1037        def __copy__(self):
1038            return self
1039
1040        def __deepcopy__(self, memo):
1041            return self
1042
1043    class ParamSpecArgs(_Immutable):
1044        """The args for a ParamSpec object.
1045
1046        Given a ParamSpec object P, P.args is an instance of ParamSpecArgs.
1047
1048        ParamSpecArgs objects have a reference back to their ParamSpec:
1049
1050        P.args.__origin__ is P
1051
1052        This type is meant for runtime introspection and has no special meaning to
1053        static type checkers.
1054        """
1055        def __init__(self, origin):
1056            self.__origin__ = origin
1057
1058        def __repr__(self):
1059            return f"{self.__origin__.__name__}.args"
1060
1061        def __eq__(self, other):
1062            if not isinstance(other, ParamSpecArgs):
1063                return NotImplemented
1064            return self.__origin__ == other.__origin__
1065
1066    class ParamSpecKwargs(_Immutable):
1067        """The kwargs for a ParamSpec object.
1068
1069        Given a ParamSpec object P, P.kwargs is an instance of ParamSpecKwargs.
1070
1071        ParamSpecKwargs objects have a reference back to their ParamSpec:
1072
1073        P.kwargs.__origin__ is P
1074
1075        This type is meant for runtime introspection and has no special meaning to
1076        static type checkers.
1077        """
1078        def __init__(self, origin):
1079            self.__origin__ = origin
1080
1081        def __repr__(self):
1082            return f"{self.__origin__.__name__}.kwargs"
1083
1084        def __eq__(self, other):
1085            if not isinstance(other, ParamSpecKwargs):
1086                return NotImplemented
1087            return self.__origin__ == other.__origin__
1088
1089# 3.10+
1090if hasattr(typing, 'ParamSpec'):
1091    ParamSpec = typing.ParamSpec
1092# 3.7-3.9
1093else:
1094
1095    # Inherits from list as a workaround for Callable checks in Python < 3.9.2.
1096    class ParamSpec(list):
1097        """Parameter specification variable.
1098
1099        Usage::
1100
1101           P = ParamSpec('P')
1102
1103        Parameter specification variables exist primarily for the benefit of static
1104        type checkers.  They are used to forward the parameter types of one
1105        callable to another callable, a pattern commonly found in higher order
1106        functions and decorators.  They are only valid when used in ``Concatenate``,
1107        or s the first argument to ``Callable``. In Python 3.10 and higher,
1108        they are also supported in user-defined Generics at runtime.
1109        See class Generic for more information on generic types.  An
1110        example for annotating a decorator::
1111
1112           T = TypeVar('T')
1113           P = ParamSpec('P')
1114
1115           def add_logging(f: Callable[P, T]) -> Callable[P, T]:
1116               '''A type-safe decorator to add logging to a function.'''
1117               def inner(*args: P.args, **kwargs: P.kwargs) -> T:
1118                   logging.info(f'{f.__name__} was called')
1119                   return f(*args, **kwargs)
1120               return inner
1121
1122           @add_logging
1123           def add_two(x: float, y: float) -> float:
1124               '''Add two numbers together.'''
1125               return x + y
1126
1127        Parameter specification variables defined with covariant=True or
1128        contravariant=True can be used to declare covariant or contravariant
1129        generic types.  These keyword arguments are valid, but their actual semantics
1130        are yet to be decided.  See PEP 612 for details.
1131
1132        Parameter specification variables can be introspected. e.g.:
1133
1134           P.__name__ == 'T'
1135           P.__bound__ == None
1136           P.__covariant__ == False
1137           P.__contravariant__ == False
1138
1139        Note that only parameter specification variables defined in global scope can
1140        be pickled.
1141        """
1142
1143        # Trick Generic __parameters__.
1144        __class__ = typing.TypeVar
1145
1146        @property
1147        def args(self):
1148            return ParamSpecArgs(self)
1149
1150        @property
1151        def kwargs(self):
1152            return ParamSpecKwargs(self)
1153
1154        def __init__(self, name, *, bound=None, covariant=False, contravariant=False):
1155            super().__init__([self])
1156            self.__name__ = name
1157            self.__covariant__ = bool(covariant)
1158            self.__contravariant__ = bool(contravariant)
1159            if bound:
1160                self.__bound__ = typing._type_check(bound, 'Bound must be a type.')
1161            else:
1162                self.__bound__ = None
1163
1164            # for pickling:
1165            try:
1166                def_mod = sys._getframe(1).f_globals.get('__name__', '__main__')
1167            except (AttributeError, ValueError):
1168                def_mod = None
1169            if def_mod != 'typing_extensions':
1170                self.__module__ = def_mod
1171
1172        def __repr__(self):
1173            if self.__covariant__:
1174                prefix = '+'
1175            elif self.__contravariant__:
1176                prefix = '-'
1177            else:
1178                prefix = '~'
1179            return prefix + self.__name__
1180
1181        def __hash__(self):
1182            return object.__hash__(self)
1183
1184        def __eq__(self, other):
1185            return self is other
1186
1187        def __reduce__(self):
1188            return self.__name__
1189
1190        # Hack to get typing._type_check to pass.
1191        def __call__(self, *args, **kwargs):
1192            pass
1193
1194
1195# 3.7-3.9
1196if not hasattr(typing, 'Concatenate'):
1197    # Inherits from list as a workaround for Callable checks in Python < 3.9.2.
1198    class _ConcatenateGenericAlias(list):
1199
1200        # Trick Generic into looking into this for __parameters__.
1201        __class__ = typing._GenericAlias
1202
1203        # Flag in 3.8.
1204        _special = False
1205
1206        def __init__(self, origin, args):
1207            super().__init__(args)
1208            self.__origin__ = origin
1209            self.__args__ = args
1210
1211        def __repr__(self):
1212            _type_repr = typing._type_repr
1213            return (f'{_type_repr(self.__origin__)}'
1214                    f'[{", ".join(_type_repr(arg) for arg in self.__args__)}]')
1215
1216        def __hash__(self):
1217            return hash((self.__origin__, self.__args__))
1218
1219        # Hack to get typing._type_check to pass in Generic.
1220        def __call__(self, *args, **kwargs):
1221            pass
1222
1223        @property
1224        def __parameters__(self):
1225            return tuple(
1226                tp for tp in self.__args__ if isinstance(tp, (typing.TypeVar, ParamSpec))
1227            )
1228
1229
1230# 3.7-3.9
1231@typing._tp_cache
1232def _concatenate_getitem(self, parameters):
1233    if parameters == ():
1234        raise TypeError("Cannot take a Concatenate of no types.")
1235    if not isinstance(parameters, tuple):
1236        parameters = (parameters,)
1237    if not isinstance(parameters[-1], ParamSpec):
1238        raise TypeError("The last parameter to Concatenate should be a "
1239                        "ParamSpec variable.")
1240    msg = "Concatenate[arg, ...]: each arg must be a type."
1241    parameters = tuple(typing._type_check(p, msg) for p in parameters)
1242    return _ConcatenateGenericAlias(self, parameters)
1243
1244
1245# 3.10+
1246if hasattr(typing, 'Concatenate'):
1247    Concatenate = typing.Concatenate
1248    _ConcatenateGenericAlias = typing._ConcatenateGenericAlias # noqa
1249# 3.9
1250elif sys.version_info[:2] >= (3, 9):
1251    @_TypeAliasForm
1252    def Concatenate(self, parameters):
1253        """Used in conjunction with ``ParamSpec`` and ``Callable`` to represent a
1254        higher order function which adds, removes or transforms parameters of a
1255        callable.
1256
1257        For example::
1258
1259           Callable[Concatenate[int, P], int]
1260
1261        See PEP 612 for detailed information.
1262        """
1263        return _concatenate_getitem(self, parameters)
1264# 3.7-8
1265else:
1266    class _ConcatenateForm(typing._SpecialForm, _root=True):
1267        def __repr__(self):
1268            return 'typing_extensions.' + self._name
1269
1270        def __getitem__(self, parameters):
1271            return _concatenate_getitem(self, parameters)
1272
1273    Concatenate = _ConcatenateForm(
1274        'Concatenate',
1275        doc="""Used in conjunction with ``ParamSpec`` and ``Callable`` to represent a
1276        higher order function which adds, removes or transforms parameters of a
1277        callable.
1278
1279        For example::
1280
1281           Callable[Concatenate[int, P], int]
1282
1283        See PEP 612 for detailed information.
1284        """)
1285
1286# 3.10+
1287if hasattr(typing, 'TypeGuard'):
1288    TypeGuard = typing.TypeGuard
1289# 3.9
1290elif sys.version_info[:2] >= (3, 9):
1291    class _TypeGuardForm(typing._SpecialForm, _root=True):
1292        def __repr__(self):
1293            return 'typing_extensions.' + self._name
1294
1295    @_TypeGuardForm
1296    def TypeGuard(self, parameters):
1297        """Special typing form used to annotate the return type of a user-defined
1298        type guard function.  ``TypeGuard`` only accepts a single type argument.
1299        At runtime, functions marked this way should return a boolean.
1300
1301        ``TypeGuard`` aims to benefit *type narrowing* -- a technique used by static
1302        type checkers to determine a more precise type of an expression within a
1303        program's code flow.  Usually type narrowing is done by analyzing
1304        conditional code flow and applying the narrowing to a block of code.  The
1305        conditional expression here is sometimes referred to as a "type guard".
1306
1307        Sometimes it would be convenient to use a user-defined boolean function
1308        as a type guard.  Such a function should use ``TypeGuard[...]`` as its
1309        return type to alert static type checkers to this intention.
1310
1311        Using  ``-> TypeGuard`` tells the static type checker that for a given
1312        function:
1313
1314        1. The return value is a boolean.
1315        2. If the return value is ``True``, the type of its argument
1316        is the type inside ``TypeGuard``.
1317
1318        For example::
1319
1320            def is_str(val: Union[str, float]):
1321                # "isinstance" type guard
1322                if isinstance(val, str):
1323                    # Type of ``val`` is narrowed to ``str``
1324                    ...
1325                else:
1326                    # Else, type of ``val`` is narrowed to ``float``.
1327                    ...
1328
1329        Strict type narrowing is not enforced -- ``TypeB`` need not be a narrower
1330        form of ``TypeA`` (it can even be a wider form) and this may lead to
1331        type-unsafe results.  The main reason is to allow for things like
1332        narrowing ``List[object]`` to ``List[str]`` even though the latter is not
1333        a subtype of the former, since ``List`` is invariant.  The responsibility of
1334        writing type-safe type guards is left to the user.
1335
1336        ``TypeGuard`` also works with type variables.  For more information, see
1337        PEP 647 (User-Defined Type Guards).
1338        """
1339        item = typing._type_check(parameters, f'{self} accepts only single type.')
1340        return typing._GenericAlias(self, (item,))
1341# 3.7-3.8
1342else:
1343    class _TypeGuardForm(typing._SpecialForm, _root=True):
1344
1345        def __repr__(self):
1346            return 'typing_extensions.' + self._name
1347
1348        def __getitem__(self, parameters):
1349            item = typing._type_check(parameters,
1350                                      f'{self._name} accepts only a single type')
1351            return typing._GenericAlias(self, (item,))
1352
1353    TypeGuard = _TypeGuardForm(
1354        'TypeGuard',
1355        doc="""Special typing form used to annotate the return type of a user-defined
1356        type guard function.  ``TypeGuard`` only accepts a single type argument.
1357        At runtime, functions marked this way should return a boolean.
1358
1359        ``TypeGuard`` aims to benefit *type narrowing* -- a technique used by static
1360        type checkers to determine a more precise type of an expression within a
1361        program's code flow.  Usually type narrowing is done by analyzing
1362        conditional code flow and applying the narrowing to a block of code.  The
1363        conditional expression here is sometimes referred to as a "type guard".
1364
1365        Sometimes it would be convenient to use a user-defined boolean function
1366        as a type guard.  Such a function should use ``TypeGuard[...]`` as its
1367        return type to alert static type checkers to this intention.
1368
1369        Using  ``-> TypeGuard`` tells the static type checker that for a given
1370        function:
1371
1372        1. The return value is a boolean.
1373        2. If the return value is ``True``, the type of its argument
1374        is the type inside ``TypeGuard``.
1375
1376        For example::
1377
1378            def is_str(val: Union[str, float]):
1379                # "isinstance" type guard
1380                if isinstance(val, str):
1381                    # Type of ``val`` is narrowed to ``str``
1382                    ...
1383                else:
1384                    # Else, type of ``val`` is narrowed to ``float``.
1385                    ...
1386
1387        Strict type narrowing is not enforced -- ``TypeB`` need not be a narrower
1388        form of ``TypeA`` (it can even be a wider form) and this may lead to
1389        type-unsafe results.  The main reason is to allow for things like
1390        narrowing ``List[object]`` to ``List[str]`` even though the latter is not
1391        a subtype of the former, since ``List`` is invariant.  The responsibility of
1392        writing type-safe type guards is left to the user.
1393
1394        ``TypeGuard`` also works with type variables.  For more information, see
1395        PEP 647 (User-Defined Type Guards).
1396        """)
1397
1398
1399# Vendored from cpython typing._SpecialFrom
1400class _SpecialForm(typing._Final, _root=True):
1401    __slots__ = ('_name', '__doc__', '_getitem')
1402
1403    def __init__(self, getitem):
1404        self._getitem = getitem
1405        self._name = getitem.__name__
1406        self.__doc__ = getitem.__doc__
1407
1408    def __getattr__(self, item):
1409        if item in {'__name__', '__qualname__'}:
1410            return self._name
1411
1412        raise AttributeError(item)
1413
1414    def __mro_entries__(self, bases):
1415        raise TypeError(f"Cannot subclass {self!r}")
1416
1417    def __repr__(self):
1418        return f'typing_extensions.{self._name}'
1419
1420    def __reduce__(self):
1421        return self._name
1422
1423    def __call__(self, *args, **kwds):
1424        raise TypeError(f"Cannot instantiate {self!r}")
1425
1426    def __or__(self, other):
1427        return typing.Union[self, other]
1428
1429    def __ror__(self, other):
1430        return typing.Union[other, self]
1431
1432    def __instancecheck__(self, obj):
1433        raise TypeError(f"{self} cannot be used with isinstance()")
1434
1435    def __subclasscheck__(self, cls):
1436        raise TypeError(f"{self} cannot be used with issubclass()")
1437
1438    @typing._tp_cache
1439    def __getitem__(self, parameters):
1440        return self._getitem(self, parameters)
1441
1442
1443if hasattr(typing, "LiteralString"):
1444    LiteralString = typing.LiteralString
1445else:
1446    @_SpecialForm
1447    def LiteralString(self, params):
1448        """Represents an arbitrary literal string.
1449
1450        Example::
1451
1452          from typing_extensions import LiteralString
1453
1454          def query(sql: LiteralString) -> ...:
1455              ...
1456
1457          query("SELECT * FROM table")  # ok
1458          query(f"SELECT * FROM {input()}")  # not ok
1459
1460        See PEP 675 for details.
1461
1462        """
1463        raise TypeError(f"{self} is not subscriptable")
1464
1465
1466if hasattr(typing, "Self"):
1467    Self = typing.Self
1468else:
1469    @_SpecialForm
1470    def Self(self, params):
1471        """Used to spell the type of "self" in classes.
1472
1473        Example::
1474
1475          from typing import Self
1476
1477          class ReturnsSelf:
1478              def parse(self, data: bytes) -> Self:
1479                  ...
1480                  return self
1481
1482        """
1483
1484        raise TypeError(f"{self} is not subscriptable")
1485
1486
1487if hasattr(typing, "Never"):
1488    Never = typing.Never
1489else:
1490    @_SpecialForm
1491    def Never(self, params):
1492        """The bottom type, a type that has no members.
1493
1494        This can be used to define a function that should never be
1495        called, or a function that never returns::
1496
1497            from typing_extensions import Never
1498
1499            def never_call_me(arg: Never) -> None:
1500                pass
1501
1502            def int_or_str(arg: int | str) -> None:
1503                never_call_me(arg)  # type checker error
1504                match arg:
1505                    case int():
1506                        print("It's an int")
1507                    case str():
1508                        print("It's a str")
1509                    case _:
1510                        never_call_me(arg)  # ok, arg is of type Never
1511
1512        """
1513
1514        raise TypeError(f"{self} is not subscriptable")
1515
1516
1517if hasattr(typing, 'Required'):
1518    Required = typing.Required
1519    NotRequired = typing.NotRequired
1520elif sys.version_info[:2] >= (3, 9):
1521    class _ExtensionsSpecialForm(typing._SpecialForm, _root=True):
1522        def __repr__(self):
1523            return 'typing_extensions.' + self._name
1524
1525    @_ExtensionsSpecialForm
1526    def Required(self, parameters):
1527        """A special typing construct to mark a key of a total=False TypedDict
1528        as required. For example:
1529
1530            class Movie(TypedDict, total=False):
1531                title: Required[str]
1532                year: int
1533
1534            m = Movie(
1535                title='The Matrix',  # typechecker error if key is omitted
1536                year=1999,
1537            )
1538
1539        There is no runtime checking that a required key is actually provided
1540        when instantiating a related TypedDict.
1541        """
1542        item = typing._type_check(parameters, f'{self._name} accepts only single type')
1543        return typing._GenericAlias(self, (item,))
1544
1545    @_ExtensionsSpecialForm
1546    def NotRequired(self, parameters):
1547        """A special typing construct to mark a key of a TypedDict as
1548        potentially missing. For example:
1549
1550            class Movie(TypedDict):
1551                title: str
1552                year: NotRequired[int]
1553
1554            m = Movie(
1555                title='The Matrix',  # typechecker error if key is omitted
1556                year=1999,
1557            )
1558        """
1559        item = typing._type_check(parameters, f'{self._name} accepts only single type')
1560        return typing._GenericAlias(self, (item,))
1561
1562else:
1563    class _RequiredForm(typing._SpecialForm, _root=True):
1564        def __repr__(self):
1565            return 'typing_extensions.' + self._name
1566
1567        def __getitem__(self, parameters):
1568            item = typing._type_check(parameters,
1569                                      '{} accepts only single type'.format(self._name))
1570            return typing._GenericAlias(self, (item,))
1571
1572    Required = _RequiredForm(
1573        'Required',
1574        doc="""A special typing construct to mark a key of a total=False TypedDict
1575        as required. For example:
1576
1577            class Movie(TypedDict, total=False):
1578                title: Required[str]
1579                year: int
1580
1581            m = Movie(
1582                title='The Matrix',  # typechecker error if key is omitted
1583                year=1999,
1584            )
1585
1586        There is no runtime checking that a required key is actually provided
1587        when instantiating a related TypedDict.
1588        """)
1589    NotRequired = _RequiredForm(
1590        'NotRequired',
1591        doc="""A special typing construct to mark a key of a TypedDict as
1592        potentially missing. For example:
1593
1594            class Movie(TypedDict):
1595                title: str
1596                year: NotRequired[int]
1597
1598            m = Movie(
1599                title='The Matrix',  # typechecker error if key is omitted
1600                year=1999,
1601            )
1602        """)
1603
1604
1605if sys.version_info[:2] >= (3, 9):
1606    class _UnpackSpecialForm(typing._SpecialForm, _root=True):
1607        def __repr__(self):
1608            return 'typing_extensions.' + self._name
1609
1610    class _UnpackAlias(typing._GenericAlias, _root=True):
1611        __class__ = typing.TypeVar
1612
1613    @_UnpackSpecialForm
1614    def Unpack(self, parameters):
1615        """A special typing construct to unpack a variadic type. For example:
1616
1617            Shape = TypeVarTuple('Shape')
1618            Batch = NewType('Batch', int)
1619
1620            def add_batch_axis(
1621                x: Array[Unpack[Shape]]
1622            ) -> Array[Batch, Unpack[Shape]]: ...
1623
1624        """
1625        item = typing._type_check(parameters, f'{self._name} accepts only single type')
1626        return _UnpackAlias(self, (item,))
1627
1628    def _is_unpack(obj):
1629        return isinstance(obj, _UnpackAlias)
1630
1631else:
1632    class _UnpackAlias(typing._GenericAlias, _root=True):
1633        __class__ = typing.TypeVar
1634
1635    class _UnpackForm(typing._SpecialForm, _root=True):
1636        def __repr__(self):
1637            return 'typing_extensions.' + self._name
1638
1639        def __getitem__(self, parameters):
1640            item = typing._type_check(parameters,
1641                                      f'{self._name} accepts only single type')
1642            return _UnpackAlias(self, (item,))
1643
1644    Unpack = _UnpackForm(
1645        'Unpack',
1646        doc="""A special typing construct to unpack a variadic type. For example:
1647
1648            Shape = TypeVarTuple('Shape')
1649            Batch = NewType('Batch', int)
1650
1651            def add_batch_axis(
1652                x: Array[Unpack[Shape]]
1653            ) -> Array[Batch, Unpack[Shape]]: ...
1654
1655        """)
1656
1657    def _is_unpack(obj):
1658        return isinstance(obj, _UnpackAlias)
1659
1660
1661class TypeVarTuple:
1662    """Type variable tuple.
1663
1664    Usage::
1665
1666        Ts = TypeVarTuple('Ts')
1667
1668    In the same way that a normal type variable is a stand-in for a single
1669    type such as ``int``, a type variable *tuple* is a stand-in for a *tuple* type such as
1670    ``Tuple[int, str]``.
1671
1672    Type variable tuples can be used in ``Generic`` declarations.
1673    Consider the following example::
1674
1675        class Array(Generic[*Ts]): ...
1676
1677    The ``Ts`` type variable tuple here behaves like ``tuple[T1, T2]``,
1678    where ``T1`` and ``T2`` are type variables. To use these type variables
1679    as type parameters of ``Array``, we must *unpack* the type variable tuple using
1680    the star operator: ``*Ts``. The signature of ``Array`` then behaves
1681    as if we had simply written ``class Array(Generic[T1, T2]): ...``.
1682    In contrast to ``Generic[T1, T2]``, however, ``Generic[*Shape]`` allows
1683    us to parameterise the class with an *arbitrary* number of type parameters.
1684
1685    Type variable tuples can be used anywhere a normal ``TypeVar`` can.
1686    This includes class definitions, as shown above, as well as function
1687    signatures and variable annotations::
1688
1689        class Array(Generic[*Ts]):
1690
1691            def __init__(self, shape: Tuple[*Ts]):
1692                self._shape: Tuple[*Ts] = shape
1693
1694            def get_shape(self) -> Tuple[*Ts]:
1695                return self._shape
1696
1697        shape = (Height(480), Width(640))
1698        x: Array[Height, Width] = Array(shape)
1699        y = abs(x)  # Inferred type is Array[Height, Width]
1700        z = x + x   #        ...    is Array[Height, Width]
1701        x.get_shape()  #     ...    is tuple[Height, Width]
1702
1703    """
1704
1705    # Trick Generic __parameters__.
1706    __class__ = typing.TypeVar
1707
1708    def __iter__(self):
1709        yield self.__unpacked__
1710
1711    def __init__(self, name):
1712        self.__name__ = name
1713
1714        # for pickling:
1715        try:
1716            def_mod = sys._getframe(1).f_globals.get('__name__', '__main__')
1717        except (AttributeError, ValueError):
1718            def_mod = None
1719        if def_mod != 'typing_extensions':
1720            self.__module__ = def_mod
1721
1722        self.__unpacked__ = Unpack[self]
1723
1724    def __repr__(self):
1725        return self.__name__
1726
1727    def __hash__(self):
1728        return object.__hash__(self)
1729
1730    def __eq__(self, other):
1731        return self is other
1732
1733    def __reduce__(self):
1734        return self.__name__
1735
1736    def __init_subclass__(self, *args, **kwds):
1737        if '_root' not in kwds:
1738            raise TypeError("Cannot subclass special typing classes")
1739
1740
1741if hasattr(typing, "reveal_type"):
1742    reveal_type = typing.reveal_type
1743else:
1744    def reveal_type(__obj: T) -> T:
1745        """Reveal the inferred type of a variable.
1746
1747        When a static type checker encounters a call to ``reveal_type()``,
1748        it will emit the inferred type of the argument::
1749
1750            x: int = 1
1751            reveal_type(x)
1752
1753        Running a static type checker (e.g., ``mypy``) on this example
1754        will produce output similar to 'Revealed type is "builtins.int"'.
1755
1756        At runtime, the function prints the runtime type of the
1757        argument and returns it unchanged.
1758
1759        """
1760        print(f"Runtime type is {type(__obj).__name__!r}", file=sys.stderr)
1761        return __obj
1762
1763
1764if hasattr(typing, "assert_never"):
1765    assert_never = typing.assert_never
1766else:
1767    def assert_never(__arg: Never) -> Never:
1768        """Assert to the type checker that a line of code is unreachable.
1769
1770        Example::
1771
1772            def int_or_str(arg: int | str) -> None:
1773                match arg:
1774                    case int():
1775                        print("It's an int")
1776                    case str():
1777                        print("It's a str")
1778                    case _:
1779                        assert_never(arg)
1780
1781        If a type checker finds that a call to assert_never() is
1782        reachable, it will emit an error.
1783
1784        At runtime, this throws an exception when called.
1785
1786        """
1787        raise AssertionError("Expected code to be unreachable")
1788
1789
1790if hasattr(typing, 'dataclass_transform'):
1791    dataclass_transform = typing.dataclass_transform
1792else:
1793    def dataclass_transform(
1794        *,
1795        eq_default: bool = True,
1796        order_default: bool = False,
1797        kw_only_default: bool = False,
1798        field_descriptors: typing.Tuple[
1799            typing.Union[typing.Type[typing.Any], typing.Callable[..., typing.Any]],
1800            ...
1801        ] = (),
1802    ) -> typing.Callable[[T], T]:
1803        """Decorator that marks a function, class, or metaclass as providing
1804        dataclass-like behavior.
1805
1806        Example:
1807
1808            from typing_extensions import dataclass_transform
1809
1810            _T = TypeVar("_T")
1811
1812            # Used on a decorator function
1813            @dataclass_transform()
1814            def create_model(cls: type[_T]) -> type[_T]:
1815                ...
1816                return cls
1817
1818            @create_model
1819            class CustomerModel:
1820                id: int
1821                name: str
1822
1823            # Used on a base class
1824            @dataclass_transform()
1825            class ModelBase: ...
1826
1827            class CustomerModel(ModelBase):
1828                id: int
1829                name: str
1830
1831            # Used on a metaclass
1832            @dataclass_transform()
1833            class ModelMeta(type): ...
1834
1835            class ModelBase(metaclass=ModelMeta): ...
1836
1837            class CustomerModel(ModelBase):
1838                id: int
1839                name: str
1840
1841        Each of the ``CustomerModel`` classes defined in this example will now
1842        behave similarly to a dataclass created with the ``@dataclasses.dataclass``
1843        decorator. For example, the type checker will synthesize an ``__init__``
1844        method.
1845
1846        The arguments to this decorator can be used to customize this behavior:
1847        - ``eq_default`` indicates whether the ``eq`` parameter is assumed to be
1848          True or False if it is omitted by the caller.
1849        - ``order_default`` indicates whether the ``order`` parameter is
1850          assumed to be True or False if it is omitted by the caller.
1851        - ``kw_only_default`` indicates whether the ``kw_only`` parameter is
1852          assumed to be True or False if it is omitted by the caller.
1853        - ``field_descriptors`` specifies a static list of supported classes
1854          or functions, that describe fields, similar to ``dataclasses.field()``.
1855
1856        At runtime, this decorator records its arguments in the
1857        ``__dataclass_transform__`` attribute on the decorated object.
1858
1859        See PEP 681 for details.
1860
1861        """
1862        def decorator(cls_or_fn):
1863            cls_or_fn.__dataclass_transform__ = {
1864                "eq_default": eq_default,
1865                "order_default": order_default,
1866                "kw_only_default": kw_only_default,
1867                "field_descriptors": field_descriptors,
1868            }
1869            return cls_or_fn
1870        return decorator
1871
1872
1873# We have to do some monkey patching to deal with the dual nature of
1874# Unpack/TypeVarTuple:
1875# - We want Unpack to be a kind of TypeVar so it gets accepted in
1876#   Generic[Unpack[Ts]]
1877# - We want it to *not* be treated as a TypeVar for the purposes of
1878#   counting generic parameters, so that when we subscript a generic,
1879#   the runtime doesn't try to substitute the Unpack with the subscripted type.
1880if not hasattr(typing, "TypeVarTuple"):
1881    typing._collect_type_vars = _collect_type_vars
1882    typing._check_generic = _check_generic
1883