Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/typing_extensions.py: 38%
1180 statements
« prev ^ index » next coverage.py v7.3.2, created at 2023-12-12 06:31 +0000
« prev ^ index » next coverage.py v7.3.2, created at 2023-12-12 06:31 +0000
1import abc
2import collections
3import collections.abc
4import functools
5import inspect
6import operator
7import sys
8import types as _types
9import typing
10import warnings
12__all__ = [
13 # Super-special typing primitives.
14 'Any',
15 'ClassVar',
16 'Concatenate',
17 'Final',
18 'LiteralString',
19 'ParamSpec',
20 'ParamSpecArgs',
21 'ParamSpecKwargs',
22 'Self',
23 'Type',
24 'TypeVar',
25 'TypeVarTuple',
26 'Unpack',
28 # ABCs (from collections.abc).
29 'Awaitable',
30 'AsyncIterator',
31 'AsyncIterable',
32 'Coroutine',
33 'AsyncGenerator',
34 'AsyncContextManager',
35 'Buffer',
36 'ChainMap',
38 # Concrete collection types.
39 'ContextManager',
40 'Counter',
41 'Deque',
42 'DefaultDict',
43 'NamedTuple',
44 'OrderedDict',
45 'TypedDict',
47 # Structural checks, a.k.a. protocols.
48 'SupportsAbs',
49 'SupportsBytes',
50 'SupportsComplex',
51 'SupportsFloat',
52 'SupportsIndex',
53 'SupportsInt',
54 'SupportsRound',
56 # One-off things.
57 'Annotated',
58 'assert_never',
59 'assert_type',
60 'clear_overloads',
61 'dataclass_transform',
62 'deprecated',
63 'Doc',
64 'get_overloads',
65 'final',
66 'get_args',
67 'get_origin',
68 'get_original_bases',
69 'get_protocol_members',
70 'get_type_hints',
71 'IntVar',
72 'is_protocol',
73 'is_typeddict',
74 'Literal',
75 'NewType',
76 'overload',
77 'override',
78 'Protocol',
79 'reveal_type',
80 'runtime',
81 'runtime_checkable',
82 'Text',
83 'TypeAlias',
84 'TypeAliasType',
85 'TypeGuard',
86 'TYPE_CHECKING',
87 'Never',
88 'NoReturn',
89 'ReadOnly',
90 'Required',
91 'NotRequired',
93 # Pure aliases, have always been in typing
94 'AbstractSet',
95 'AnyStr',
96 'BinaryIO',
97 'Callable',
98 'Collection',
99 'Container',
100 'Dict',
101 'ForwardRef',
102 'FrozenSet',
103 'Generator',
104 'Generic',
105 'Hashable',
106 'IO',
107 'ItemsView',
108 'Iterable',
109 'Iterator',
110 'KeysView',
111 'List',
112 'Mapping',
113 'MappingView',
114 'Match',
115 'MutableMapping',
116 'MutableSequence',
117 'MutableSet',
118 'Optional',
119 'Pattern',
120 'Reversible',
121 'Sequence',
122 'Set',
123 'Sized',
124 'TextIO',
125 'Tuple',
126 'Union',
127 'ValuesView',
128 'cast',
129 'no_type_check',
130 'no_type_check_decorator',
131]
133# for backward compatibility
134PEP_560 = True
135GenericMeta = type
137# The functions below are modified copies of typing internal helpers.
138# They are needed by _ProtocolMeta and they provide support for PEP 646.
141class _Sentinel:
142 def __repr__(self):
143 return "<sentinel>"
146_marker = _Sentinel()
149def _check_generic(cls, parameters, elen=_marker):
150 """Check correct count for parameters of a generic cls (internal helper).
151 This gives a nice error message in case of count mismatch.
152 """
153 if not elen:
154 raise TypeError(f"{cls} is not a generic class")
155 if elen is _marker:
156 if not hasattr(cls, "__parameters__") or not cls.__parameters__:
157 raise TypeError(f"{cls} is not a generic class")
158 elen = len(cls.__parameters__)
159 alen = len(parameters)
160 if alen != elen:
161 if hasattr(cls, "__parameters__"):
162 parameters = [p for p in cls.__parameters__ if not _is_unpack(p)]
163 num_tv_tuples = sum(isinstance(p, TypeVarTuple) for p in parameters)
164 if (num_tv_tuples > 0) and (alen >= elen - num_tv_tuples):
165 return
166 raise TypeError(f"Too {'many' if alen > elen else 'few'} parameters for {cls};"
167 f" actual {alen}, expected {elen}")
170if sys.version_info >= (3, 10):
171 def _should_collect_from_parameters(t):
172 return isinstance(
173 t, (typing._GenericAlias, _types.GenericAlias, _types.UnionType)
174 )
175elif sys.version_info >= (3, 9):
176 def _should_collect_from_parameters(t):
177 return isinstance(t, (typing._GenericAlias, _types.GenericAlias))
178else:
179 def _should_collect_from_parameters(t):
180 return isinstance(t, typing._GenericAlias) and not t._special
183def _collect_type_vars(types, typevar_types=None):
184 """Collect all type variable contained in types in order of
185 first appearance (lexicographic order). For example::
187 _collect_type_vars((T, List[S, T])) == (T, S)
188 """
189 if typevar_types is None:
190 typevar_types = typing.TypeVar
191 tvars = []
192 for t in types:
193 if (
194 isinstance(t, typevar_types) and
195 t not in tvars and
196 not _is_unpack(t)
197 ):
198 tvars.append(t)
199 if _should_collect_from_parameters(t):
200 tvars.extend([t for t in t.__parameters__ if t not in tvars])
201 return tuple(tvars)
204NoReturn = typing.NoReturn
206# Some unconstrained type variables. These are used by the container types.
207# (These are not for export.)
208T = typing.TypeVar('T') # Any type.
209KT = typing.TypeVar('KT') # Key type.
210VT = typing.TypeVar('VT') # Value type.
211T_co = typing.TypeVar('T_co', covariant=True) # Any type covariant containers.
212T_contra = typing.TypeVar('T_contra', contravariant=True) # Ditto contravariant.
215if sys.version_info >= (3, 11):
216 from typing import Any
217else:
219 class _AnyMeta(type):
220 def __instancecheck__(self, obj):
221 if self is Any:
222 raise TypeError("typing_extensions.Any cannot be used with isinstance()")
223 return super().__instancecheck__(obj)
225 def __repr__(self):
226 if self is Any:
227 return "typing_extensions.Any"
228 return super().__repr__()
230 class Any(metaclass=_AnyMeta):
231 """Special type indicating an unconstrained type.
232 - Any is compatible with every type.
233 - Any assumed to have all methods.
234 - All values assumed to be instances of Any.
235 Note that all the above statements are true from the point of view of
236 static type checkers. At runtime, Any should not be used with instance
237 checks.
238 """
239 def __new__(cls, *args, **kwargs):
240 if cls is Any:
241 raise TypeError("Any cannot be instantiated")
242 return super().__new__(cls, *args, **kwargs)
245ClassVar = typing.ClassVar
248class _ExtensionsSpecialForm(typing._SpecialForm, _root=True):
249 def __repr__(self):
250 return 'typing_extensions.' + self._name
253Final = typing.Final
255if sys.version_info >= (3, 11):
256 final = typing.final
257else:
258 # @final exists in 3.8+, but we backport it for all versions
259 # before 3.11 to keep support for the __final__ attribute.
260 # See https://bugs.python.org/issue46342
261 def final(f):
262 """This decorator can be used to indicate to type checkers that
263 the decorated method cannot be overridden, and decorated class
264 cannot be subclassed. For example:
266 class Base:
267 @final
268 def done(self) -> None:
269 ...
270 class Sub(Base):
271 def done(self) -> None: # Error reported by type checker
272 ...
273 @final
274 class Leaf:
275 ...
276 class Other(Leaf): # Error reported by type checker
277 ...
279 There is no runtime checking of these properties. The decorator
280 sets the ``__final__`` attribute to ``True`` on the decorated object
281 to allow runtime introspection.
282 """
283 try:
284 f.__final__ = True
285 except (AttributeError, TypeError):
286 # Skip the attribute silently if it is not writable.
287 # AttributeError happens if the object has __slots__ or a
288 # read-only property, TypeError if it's a builtin class.
289 pass
290 return f
293def IntVar(name):
294 return typing.TypeVar(name)
297# A Literal bug was fixed in 3.11.0, 3.10.1 and 3.9.8
298if sys.version_info >= (3, 10, 1):
299 Literal = typing.Literal
300else:
301 def _flatten_literal_params(parameters):
302 """An internal helper for Literal creation: flatten Literals among parameters"""
303 params = []
304 for p in parameters:
305 if isinstance(p, _LiteralGenericAlias):
306 params.extend(p.__args__)
307 else:
308 params.append(p)
309 return tuple(params)
311 def _value_and_type_iter(params):
312 for p in params:
313 yield p, type(p)
315 class _LiteralGenericAlias(typing._GenericAlias, _root=True):
316 def __eq__(self, other):
317 if not isinstance(other, _LiteralGenericAlias):
318 return NotImplemented
319 these_args_deduped = set(_value_and_type_iter(self.__args__))
320 other_args_deduped = set(_value_and_type_iter(other.__args__))
321 return these_args_deduped == other_args_deduped
323 def __hash__(self):
324 return hash(frozenset(_value_and_type_iter(self.__args__)))
326 class _LiteralForm(_ExtensionsSpecialForm, _root=True):
327 def __init__(self, doc: str):
328 self._name = 'Literal'
329 self._doc = self.__doc__ = doc
331 def __getitem__(self, parameters):
332 if not isinstance(parameters, tuple):
333 parameters = (parameters,)
335 parameters = _flatten_literal_params(parameters)
337 val_type_pairs = list(_value_and_type_iter(parameters))
338 try:
339 deduped_pairs = set(val_type_pairs)
340 except TypeError:
341 # unhashable parameters
342 pass
343 else:
344 # similar logic to typing._deduplicate on Python 3.9+
345 if len(deduped_pairs) < len(val_type_pairs):
346 new_parameters = []
347 for pair in val_type_pairs:
348 if pair in deduped_pairs:
349 new_parameters.append(pair[0])
350 deduped_pairs.remove(pair)
351 assert not deduped_pairs, deduped_pairs
352 parameters = tuple(new_parameters)
354 return _LiteralGenericAlias(self, parameters)
356 Literal = _LiteralForm(doc="""\
357 A type that can be used to indicate to type checkers
358 that the corresponding value has a value literally equivalent
359 to the provided parameter. For example:
361 var: Literal[4] = 4
363 The type checker understands that 'var' is literally equal to
364 the value 4 and no other value.
366 Literal[...] cannot be subclassed. There is no runtime
367 checking verifying that the parameter is actually a value
368 instead of a type.""")
371_overload_dummy = typing._overload_dummy
374if hasattr(typing, "get_overloads"): # 3.11+
375 overload = typing.overload
376 get_overloads = typing.get_overloads
377 clear_overloads = typing.clear_overloads
378else:
379 # {module: {qualname: {firstlineno: func}}}
380 _overload_registry = collections.defaultdict(
381 functools.partial(collections.defaultdict, dict)
382 )
384 def overload(func):
385 """Decorator for overloaded functions/methods.
387 In a stub file, place two or more stub definitions for the same
388 function in a row, each decorated with @overload. For example:
390 @overload
391 def utf8(value: None) -> None: ...
392 @overload
393 def utf8(value: bytes) -> bytes: ...
394 @overload
395 def utf8(value: str) -> bytes: ...
397 In a non-stub file (i.e. a regular .py file), do the same but
398 follow it with an implementation. The implementation should *not*
399 be decorated with @overload. For example:
401 @overload
402 def utf8(value: None) -> None: ...
403 @overload
404 def utf8(value: bytes) -> bytes: ...
405 @overload
406 def utf8(value: str) -> bytes: ...
407 def utf8(value):
408 # implementation goes here
410 The overloads for a function can be retrieved at runtime using the
411 get_overloads() function.
412 """
413 # classmethod and staticmethod
414 f = getattr(func, "__func__", func)
415 try:
416 _overload_registry[f.__module__][f.__qualname__][
417 f.__code__.co_firstlineno
418 ] = func
419 except AttributeError:
420 # Not a normal function; ignore.
421 pass
422 return _overload_dummy
424 def get_overloads(func):
425 """Return all defined overloads for *func* as a sequence."""
426 # classmethod and staticmethod
427 f = getattr(func, "__func__", func)
428 if f.__module__ not in _overload_registry:
429 return []
430 mod_dict = _overload_registry[f.__module__]
431 if f.__qualname__ not in mod_dict:
432 return []
433 return list(mod_dict[f.__qualname__].values())
435 def clear_overloads():
436 """Clear all overloads in the registry."""
437 _overload_registry.clear()
440# This is not a real generic class. Don't use outside annotations.
441Type = typing.Type
443# Various ABCs mimicking those in collections.abc.
444# A few are simply re-exported for completeness.
445Awaitable = typing.Awaitable
446Coroutine = typing.Coroutine
447AsyncIterable = typing.AsyncIterable
448AsyncIterator = typing.AsyncIterator
449Deque = typing.Deque
450ContextManager = typing.ContextManager
451AsyncContextManager = typing.AsyncContextManager
452DefaultDict = typing.DefaultDict
453OrderedDict = typing.OrderedDict
454Counter = typing.Counter
455ChainMap = typing.ChainMap
456AsyncGenerator = typing.AsyncGenerator
457Text = typing.Text
458TYPE_CHECKING = typing.TYPE_CHECKING
461_PROTO_ALLOWLIST = {
462 'collections.abc': [
463 'Callable', 'Awaitable', 'Iterable', 'Iterator', 'AsyncIterable',
464 'Hashable', 'Sized', 'Container', 'Collection', 'Reversible', 'Buffer',
465 ],
466 'contextlib': ['AbstractContextManager', 'AbstractAsyncContextManager'],
467 'typing_extensions': ['Buffer'],
468}
471_EXCLUDED_ATTRS = {
472 "__abstractmethods__", "__annotations__", "__weakref__", "_is_protocol",
473 "_is_runtime_protocol", "__dict__", "__slots__", "__parameters__",
474 "__orig_bases__", "__module__", "_MutableMapping__marker", "__doc__",
475 "__subclasshook__", "__orig_class__", "__init__", "__new__",
476 "__protocol_attrs__", "__callable_proto_members_only__",
477 "__match_args__",
478}
480if sys.version_info >= (3, 9):
481 _EXCLUDED_ATTRS.add("__class_getitem__")
483if sys.version_info >= (3, 12):
484 _EXCLUDED_ATTRS.add("__type_params__")
486_EXCLUDED_ATTRS = frozenset(_EXCLUDED_ATTRS)
489def _get_protocol_attrs(cls):
490 attrs = set()
491 for base in cls.__mro__[:-1]: # without object
492 if base.__name__ in {'Protocol', 'Generic'}:
493 continue
494 annotations = getattr(base, '__annotations__', {})
495 for attr in (*base.__dict__, *annotations):
496 if (not attr.startswith('_abc_') and attr not in _EXCLUDED_ATTRS):
497 attrs.add(attr)
498 return attrs
501def _caller(depth=2):
502 try:
503 return sys._getframe(depth).f_globals.get('__name__', '__main__')
504 except (AttributeError, ValueError): # For platforms without _getframe()
505 return None
508# `__match_args__` attribute was removed from protocol members in 3.13,
509# we want to backport this change to older Python versions.
510if sys.version_info >= (3, 13):
511 Protocol = typing.Protocol
512else:
513 def _allow_reckless_class_checks(depth=3):
514 """Allow instance and class checks for special stdlib modules.
515 The abc and functools modules indiscriminately call isinstance() and
516 issubclass() on the whole MRO of a user class, which may contain protocols.
517 """
518 return _caller(depth) in {'abc', 'functools', None}
520 def _no_init(self, *args, **kwargs):
521 if type(self)._is_protocol:
522 raise TypeError('Protocols cannot be instantiated')
524 # Inheriting from typing._ProtocolMeta isn't actually desirable,
525 # but is necessary to allow typing.Protocol and typing_extensions.Protocol
526 # to mix without getting TypeErrors about "metaclass conflict"
527 class _ProtocolMeta(type(typing.Protocol)):
528 # This metaclass is somewhat unfortunate,
529 # but is necessary for several reasons...
530 #
531 # NOTE: DO NOT call super() in any methods in this class
532 # That would call the methods on typing._ProtocolMeta on Python 3.8-3.11
533 # and those are slow
534 def __new__(mcls, name, bases, namespace, **kwargs):
535 if name == "Protocol" and len(bases) < 2:
536 pass
537 elif {Protocol, typing.Protocol} & set(bases):
538 for base in bases:
539 if not (
540 base in {object, typing.Generic, Protocol, typing.Protocol}
541 or base.__name__ in _PROTO_ALLOWLIST.get(base.__module__, [])
542 or is_protocol(base)
543 ):
544 raise TypeError(
545 f"Protocols can only inherit from other protocols, "
546 f"got {base!r}"
547 )
548 return abc.ABCMeta.__new__(mcls, name, bases, namespace, **kwargs)
550 def __init__(cls, *args, **kwargs):
551 abc.ABCMeta.__init__(cls, *args, **kwargs)
552 if getattr(cls, "_is_protocol", False):
553 cls.__protocol_attrs__ = _get_protocol_attrs(cls)
554 # PEP 544 prohibits using issubclass()
555 # with protocols that have non-method members.
556 cls.__callable_proto_members_only__ = all(
557 callable(getattr(cls, attr, None)) for attr in cls.__protocol_attrs__
558 )
560 def __subclasscheck__(cls, other):
561 if cls is Protocol:
562 return type.__subclasscheck__(cls, other)
563 if (
564 getattr(cls, '_is_protocol', False)
565 and not _allow_reckless_class_checks()
566 ):
567 if not isinstance(other, type):
568 # Same error message as for issubclass(1, int).
569 raise TypeError('issubclass() arg 1 must be a class')
570 if (
571 not cls.__callable_proto_members_only__
572 and cls.__dict__.get("__subclasshook__") is _proto_hook
573 ):
574 non_method_attrs = sorted(
575 attr for attr in cls.__protocol_attrs__
576 if not callable(getattr(cls, attr, None))
577 )
578 raise TypeError(
579 "Protocols with non-method members don't support issubclass()."
580 f" Non-method members: {str(non_method_attrs)[1:-1]}."
581 )
582 if not getattr(cls, '_is_runtime_protocol', False):
583 raise TypeError(
584 "Instance and class checks can only be used with "
585 "@runtime_checkable protocols"
586 )
587 return abc.ABCMeta.__subclasscheck__(cls, other)
589 def __instancecheck__(cls, instance):
590 # We need this method for situations where attributes are
591 # assigned in __init__.
592 if cls is Protocol:
593 return type.__instancecheck__(cls, instance)
594 if not getattr(cls, "_is_protocol", False):
595 # i.e., it's a concrete subclass of a protocol
596 return abc.ABCMeta.__instancecheck__(cls, instance)
598 if (
599 not getattr(cls, '_is_runtime_protocol', False) and
600 not _allow_reckless_class_checks()
601 ):
602 raise TypeError("Instance and class checks can only be used with"
603 " @runtime_checkable protocols")
605 if abc.ABCMeta.__instancecheck__(cls, instance):
606 return True
608 for attr in cls.__protocol_attrs__:
609 try:
610 val = inspect.getattr_static(instance, attr)
611 except AttributeError:
612 break
613 if val is None and callable(getattr(cls, attr, None)):
614 break
615 else:
616 return True
618 return False
620 def __eq__(cls, other):
621 # Hack so that typing.Generic.__class_getitem__
622 # treats typing_extensions.Protocol
623 # as equivalent to typing.Protocol
624 if abc.ABCMeta.__eq__(cls, other) is True:
625 return True
626 return cls is Protocol and other is typing.Protocol
628 # This has to be defined, or the abc-module cache
629 # complains about classes with this metaclass being unhashable,
630 # if we define only __eq__!
631 def __hash__(cls) -> int:
632 return type.__hash__(cls)
634 @classmethod
635 def _proto_hook(cls, other):
636 if not cls.__dict__.get('_is_protocol', False):
637 return NotImplemented
639 for attr in cls.__protocol_attrs__:
640 for base in other.__mro__:
641 # Check if the members appears in the class dictionary...
642 if attr in base.__dict__:
643 if base.__dict__[attr] is None:
644 return NotImplemented
645 break
647 # ...or in annotations, if it is a sub-protocol.
648 annotations = getattr(base, '__annotations__', {})
649 if (
650 isinstance(annotations, collections.abc.Mapping)
651 and attr in annotations
652 and is_protocol(other)
653 ):
654 break
655 else:
656 return NotImplemented
657 return True
659 class Protocol(typing.Generic, metaclass=_ProtocolMeta):
660 __doc__ = typing.Protocol.__doc__
661 __slots__ = ()
662 _is_protocol = True
663 _is_runtime_protocol = False
665 def __init_subclass__(cls, *args, **kwargs):
666 super().__init_subclass__(*args, **kwargs)
668 # Determine if this is a protocol or a concrete subclass.
669 if not cls.__dict__.get('_is_protocol', False):
670 cls._is_protocol = any(b is Protocol for b in cls.__bases__)
672 # Set (or override) the protocol subclass hook.
673 if '__subclasshook__' not in cls.__dict__:
674 cls.__subclasshook__ = _proto_hook
676 # Prohibit instantiation for protocol classes
677 if cls._is_protocol and cls.__init__ is Protocol.__init__:
678 cls.__init__ = _no_init
681# The "runtime" alias exists for backwards compatibility.
682runtime = runtime_checkable = typing.runtime_checkable
685# Our version of runtime-checkable protocols is faster on Python 3.8-3.11
686if sys.version_info >= (3, 12):
687 SupportsInt = typing.SupportsInt
688 SupportsFloat = typing.SupportsFloat
689 SupportsComplex = typing.SupportsComplex
690 SupportsBytes = typing.SupportsBytes
691 SupportsIndex = typing.SupportsIndex
692 SupportsAbs = typing.SupportsAbs
693 SupportsRound = typing.SupportsRound
694else:
695 @runtime_checkable
696 class SupportsInt(Protocol):
697 """An ABC with one abstract method __int__."""
698 __slots__ = ()
700 @abc.abstractmethod
701 def __int__(self) -> int:
702 pass
704 @runtime_checkable
705 class SupportsFloat(Protocol):
706 """An ABC with one abstract method __float__."""
707 __slots__ = ()
709 @abc.abstractmethod
710 def __float__(self) -> float:
711 pass
713 @runtime_checkable
714 class SupportsComplex(Protocol):
715 """An ABC with one abstract method __complex__."""
716 __slots__ = ()
718 @abc.abstractmethod
719 def __complex__(self) -> complex:
720 pass
722 @runtime_checkable
723 class SupportsBytes(Protocol):
724 """An ABC with one abstract method __bytes__."""
725 __slots__ = ()
727 @abc.abstractmethod
728 def __bytes__(self) -> bytes:
729 pass
731 @runtime_checkable
732 class SupportsIndex(Protocol):
733 __slots__ = ()
735 @abc.abstractmethod
736 def __index__(self) -> int:
737 pass
739 @runtime_checkable
740 class SupportsAbs(Protocol[T_co]):
741 """
742 An ABC with one abstract method __abs__ that is covariant in its return type.
743 """
744 __slots__ = ()
746 @abc.abstractmethod
747 def __abs__(self) -> T_co:
748 pass
750 @runtime_checkable
751 class SupportsRound(Protocol[T_co]):
752 """
753 An ABC with one abstract method __round__ that is covariant in its return type.
754 """
755 __slots__ = ()
757 @abc.abstractmethod
758 def __round__(self, ndigits: int = 0) -> T_co:
759 pass
762def _ensure_subclassable(mro_entries):
763 def inner(func):
764 if sys.implementation.name == "pypy" and sys.version_info < (3, 9):
765 cls_dict = {
766 "__call__": staticmethod(func),
767 "__mro_entries__": staticmethod(mro_entries)
768 }
769 t = type(func.__name__, (), cls_dict)
770 return functools.update_wrapper(t(), func)
771 else:
772 func.__mro_entries__ = mro_entries
773 return func
774 return inner
777if hasattr(typing, "ReadOnly"):
778 # The standard library TypedDict in Python 3.8 does not store runtime information
779 # about which (if any) keys are optional. See https://bugs.python.org/issue38834
780 # The standard library TypedDict in Python 3.9.0/1 does not honour the "total"
781 # keyword with old-style TypedDict(). See https://bugs.python.org/issue42059
782 # The standard library TypedDict below Python 3.11 does not store runtime
783 # information about optional and required keys when using Required or NotRequired.
784 # Generic TypedDicts are also impossible using typing.TypedDict on Python <3.11.
785 # Aaaand on 3.12 we add __orig_bases__ to TypedDict
786 # to enable better runtime introspection.
787 # On 3.13 we deprecate some odd ways of creating TypedDicts.
788 # PEP 705 proposes adding the ReadOnly[] qualifier.
789 TypedDict = typing.TypedDict
790 _TypedDictMeta = typing._TypedDictMeta
791 is_typeddict = typing.is_typeddict
792else:
793 # 3.10.0 and later
794 _TAKES_MODULE = "module" in inspect.signature(typing._type_check).parameters
796 def _get_typeddict_qualifiers(annotation_type):
797 while True:
798 annotation_origin = get_origin(annotation_type)
799 if annotation_origin is Annotated:
800 annotation_args = get_args(annotation_type)
801 if annotation_args:
802 annotation_type = annotation_args[0]
803 else:
804 break
805 elif annotation_origin is Required:
806 yield Required
807 annotation_type, = get_args(annotation_type)
808 elif annotation_origin is NotRequired:
809 yield NotRequired
810 annotation_type, = get_args(annotation_type)
811 elif annotation_origin is ReadOnly:
812 yield ReadOnly
813 annotation_type, = get_args(annotation_type)
814 else:
815 break
817 class _TypedDictMeta(type):
818 def __new__(cls, name, bases, ns, *, total=True):
819 """Create new typed dict class object.
821 This method is called when TypedDict is subclassed,
822 or when TypedDict is instantiated. This way
823 TypedDict supports all three syntax forms described in its docstring.
824 Subclasses and instances of TypedDict return actual dictionaries.
825 """
826 for base in bases:
827 if type(base) is not _TypedDictMeta and base is not typing.Generic:
828 raise TypeError('cannot inherit from both a TypedDict type '
829 'and a non-TypedDict base class')
831 if any(issubclass(b, typing.Generic) for b in bases):
832 generic_base = (typing.Generic,)
833 else:
834 generic_base = ()
836 # typing.py generally doesn't let you inherit from plain Generic, unless
837 # the name of the class happens to be "Protocol"
838 tp_dict = type.__new__(_TypedDictMeta, "Protocol", (*generic_base, dict), ns)
839 tp_dict.__name__ = name
840 if tp_dict.__qualname__ == "Protocol":
841 tp_dict.__qualname__ = name
843 if not hasattr(tp_dict, '__orig_bases__'):
844 tp_dict.__orig_bases__ = bases
846 annotations = {}
847 own_annotations = ns.get('__annotations__', {})
848 msg = "TypedDict('Name', {f0: t0, f1: t1, ...}); each t must be a type"
849 if _TAKES_MODULE:
850 own_annotations = {
851 n: typing._type_check(tp, msg, module=tp_dict.__module__)
852 for n, tp in own_annotations.items()
853 }
854 else:
855 own_annotations = {
856 n: typing._type_check(tp, msg)
857 for n, tp in own_annotations.items()
858 }
859 required_keys = set()
860 optional_keys = set()
861 readonly_keys = set()
862 mutable_keys = set()
864 for base in bases:
865 base_dict = base.__dict__
867 annotations.update(base_dict.get('__annotations__', {}))
868 required_keys.update(base_dict.get('__required_keys__', ()))
869 optional_keys.update(base_dict.get('__optional_keys__', ()))
870 readonly_keys.update(base_dict.get('__readonly_keys__', ()))
871 mutable_keys.update(base_dict.get('__mutable_keys__', ()))
873 annotations.update(own_annotations)
874 for annotation_key, annotation_type in own_annotations.items():
875 qualifiers = set(_get_typeddict_qualifiers(annotation_type))
877 if Required in qualifiers:
878 required_keys.add(annotation_key)
879 elif NotRequired in qualifiers:
880 optional_keys.add(annotation_key)
881 elif total:
882 required_keys.add(annotation_key)
883 else:
884 optional_keys.add(annotation_key)
885 if ReadOnly in qualifiers:
886 if annotation_key in mutable_keys:
887 raise TypeError(
888 f"Cannot override mutable key {annotation_key!r}"
889 " with read-only key"
890 )
891 readonly_keys.add(annotation_key)
892 else:
893 mutable_keys.add(annotation_key)
894 readonly_keys.discard(annotation_key)
896 tp_dict.__annotations__ = annotations
897 tp_dict.__required_keys__ = frozenset(required_keys)
898 tp_dict.__optional_keys__ = frozenset(optional_keys)
899 tp_dict.__readonly_keys__ = frozenset(readonly_keys)
900 tp_dict.__mutable_keys__ = frozenset(mutable_keys)
901 if not hasattr(tp_dict, '__total__'):
902 tp_dict.__total__ = total
903 return tp_dict
905 __call__ = dict # static method
907 def __subclasscheck__(cls, other):
908 # Typed dicts are only for static structural subtyping.
909 raise TypeError('TypedDict does not support instance and class checks')
911 __instancecheck__ = __subclasscheck__
913 _TypedDict = type.__new__(_TypedDictMeta, 'TypedDict', (), {})
915 @_ensure_subclassable(lambda bases: (_TypedDict,))
916 def TypedDict(typename, fields=_marker, /, *, total=True, **kwargs):
917 """A simple typed namespace. At runtime it is equivalent to a plain dict.
919 TypedDict creates a dictionary type such that a type checker will expect all
920 instances to have a certain set of keys, where each key is
921 associated with a value of a consistent type. This expectation
922 is not checked at runtime.
924 Usage::
926 class Point2D(TypedDict):
927 x: int
928 y: int
929 label: str
931 a: Point2D = {'x': 1, 'y': 2, 'label': 'good'} # OK
932 b: Point2D = {'z': 3, 'label': 'bad'} # Fails type check
934 assert Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first')
936 The type info can be accessed via the Point2D.__annotations__ dict, and
937 the Point2D.__required_keys__ and Point2D.__optional_keys__ frozensets.
938 TypedDict supports an additional equivalent form::
940 Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str})
942 By default, all keys must be present in a TypedDict. It is possible
943 to override this by specifying totality::
945 class Point2D(TypedDict, total=False):
946 x: int
947 y: int
949 This means that a Point2D TypedDict can have any of the keys omitted. A type
950 checker is only expected to support a literal False or True as the value of
951 the total argument. True is the default, and makes all items defined in the
952 class body be required.
954 The Required and NotRequired special forms can also be used to mark
955 individual keys as being required or not required::
957 class Point2D(TypedDict):
958 x: int # the "x" key must always be present (Required is the default)
959 y: NotRequired[int] # the "y" key can be omitted
961 See PEP 655 for more details on Required and NotRequired.
962 """
963 if fields is _marker or fields is None:
964 if fields is _marker:
965 deprecated_thing = "Failing to pass a value for the 'fields' parameter"
966 else:
967 deprecated_thing = "Passing `None` as the 'fields' parameter"
969 example = f"`{typename} = TypedDict({typename!r}, {{}})`"
970 deprecation_msg = (
971 f"{deprecated_thing} is deprecated and will be disallowed in "
972 "Python 3.15. To create a TypedDict class with 0 fields "
973 "using the functional syntax, pass an empty dictionary, e.g. "
974 ) + example + "."
975 warnings.warn(deprecation_msg, DeprecationWarning, stacklevel=2)
976 fields = kwargs
977 elif kwargs:
978 raise TypeError("TypedDict takes either a dict or keyword arguments,"
979 " but not both")
980 if kwargs:
981 if sys.version_info >= (3, 13):
982 raise TypeError("TypedDict takes no keyword arguments")
983 warnings.warn(
984 "The kwargs-based syntax for TypedDict definitions is deprecated "
985 "in Python 3.11, will be removed in Python 3.13, and may not be "
986 "understood by third-party type checkers.",
987 DeprecationWarning,
988 stacklevel=2,
989 )
991 ns = {'__annotations__': dict(fields)}
992 module = _caller()
993 if module is not None:
994 # Setting correct module is necessary to make typed dict classes pickleable.
995 ns['__module__'] = module
997 td = _TypedDictMeta(typename, (), ns, total=total)
998 td.__orig_bases__ = (TypedDict,)
999 return td
1001 if hasattr(typing, "_TypedDictMeta"):
1002 _TYPEDDICT_TYPES = (typing._TypedDictMeta, _TypedDictMeta)
1003 else:
1004 _TYPEDDICT_TYPES = (_TypedDictMeta,)
1006 def is_typeddict(tp):
1007 """Check if an annotation is a TypedDict class
1009 For example::
1010 class Film(TypedDict):
1011 title: str
1012 year: int
1014 is_typeddict(Film) # => True
1015 is_typeddict(Union[list, str]) # => False
1016 """
1017 # On 3.8, this would otherwise return True
1018 if hasattr(typing, "TypedDict") and tp is typing.TypedDict:
1019 return False
1020 return isinstance(tp, _TYPEDDICT_TYPES)
1023if hasattr(typing, "assert_type"):
1024 assert_type = typing.assert_type
1026else:
1027 def assert_type(val, typ, /):
1028 """Assert (to the type checker) that the value is of the given type.
1030 When the type checker encounters a call to assert_type(), it
1031 emits an error if the value is not of the specified type::
1033 def greet(name: str) -> None:
1034 assert_type(name, str) # ok
1035 assert_type(name, int) # type checker error
1037 At runtime this returns the first argument unchanged and otherwise
1038 does nothing.
1039 """
1040 return val
1043if hasattr(typing, "Required"): # 3.11+
1044 get_type_hints = typing.get_type_hints
1045else: # <=3.10
1046 # replaces _strip_annotations()
1047 def _strip_extras(t):
1048 """Strips Annotated, Required and NotRequired from a given type."""
1049 if isinstance(t, _AnnotatedAlias):
1050 return _strip_extras(t.__origin__)
1051 if hasattr(t, "__origin__") and t.__origin__ in (Required, NotRequired):
1052 return _strip_extras(t.__args__[0])
1053 if isinstance(t, typing._GenericAlias):
1054 stripped_args = tuple(_strip_extras(a) for a in t.__args__)
1055 if stripped_args == t.__args__:
1056 return t
1057 return t.copy_with(stripped_args)
1058 if hasattr(_types, "GenericAlias") and isinstance(t, _types.GenericAlias):
1059 stripped_args = tuple(_strip_extras(a) for a in t.__args__)
1060 if stripped_args == t.__args__:
1061 return t
1062 return _types.GenericAlias(t.__origin__, stripped_args)
1063 if hasattr(_types, "UnionType") and isinstance(t, _types.UnionType):
1064 stripped_args = tuple(_strip_extras(a) for a in t.__args__)
1065 if stripped_args == t.__args__:
1066 return t
1067 return functools.reduce(operator.or_, stripped_args)
1069 return t
1071 def get_type_hints(obj, globalns=None, localns=None, include_extras=False):
1072 """Return type hints for an object.
1074 This is often the same as obj.__annotations__, but it handles
1075 forward references encoded as string literals, adds Optional[t] if a
1076 default value equal to None is set and recursively replaces all
1077 'Annotated[T, ...]', 'Required[T]' or 'NotRequired[T]' with 'T'
1078 (unless 'include_extras=True').
1080 The argument may be a module, class, method, or function. The annotations
1081 are returned as a dictionary. For classes, annotations include also
1082 inherited members.
1084 TypeError is raised if the argument is not of a type that can contain
1085 annotations, and an empty dictionary is returned if no annotations are
1086 present.
1088 BEWARE -- the behavior of globalns and localns is counterintuitive
1089 (unless you are familiar with how eval() and exec() work). The
1090 search order is locals first, then globals.
1092 - If no dict arguments are passed, an attempt is made to use the
1093 globals from obj (or the respective module's globals for classes),
1094 and these are also used as the locals. If the object does not appear
1095 to have globals, an empty dictionary is used.
1097 - If one dict argument is passed, it is used for both globals and
1098 locals.
1100 - If two dict arguments are passed, they specify globals and
1101 locals, respectively.
1102 """
1103 if hasattr(typing, "Annotated"): # 3.9+
1104 hint = typing.get_type_hints(
1105 obj, globalns=globalns, localns=localns, include_extras=True
1106 )
1107 else: # 3.8
1108 hint = typing.get_type_hints(obj, globalns=globalns, localns=localns)
1109 if include_extras:
1110 return hint
1111 return {k: _strip_extras(t) for k, t in hint.items()}
1114# Python 3.9+ has PEP 593 (Annotated)
1115if hasattr(typing, 'Annotated'):
1116 Annotated = typing.Annotated
1117 # Not exported and not a public API, but needed for get_origin() and get_args()
1118 # to work.
1119 _AnnotatedAlias = typing._AnnotatedAlias
1120# 3.8
1121else:
1122 class _AnnotatedAlias(typing._GenericAlias, _root=True):
1123 """Runtime representation of an annotated type.
1125 At its core 'Annotated[t, dec1, dec2, ...]' is an alias for the type 't'
1126 with extra annotations. The alias behaves like a normal typing alias,
1127 instantiating is the same as instantiating the underlying type, binding
1128 it to types is also the same.
1129 """
1130 def __init__(self, origin, metadata):
1131 if isinstance(origin, _AnnotatedAlias):
1132 metadata = origin.__metadata__ + metadata
1133 origin = origin.__origin__
1134 super().__init__(origin, origin)
1135 self.__metadata__ = metadata
1137 def copy_with(self, params):
1138 assert len(params) == 1
1139 new_type = params[0]
1140 return _AnnotatedAlias(new_type, self.__metadata__)
1142 def __repr__(self):
1143 return (f"typing_extensions.Annotated[{typing._type_repr(self.__origin__)}, "
1144 f"{', '.join(repr(a) for a in self.__metadata__)}]")
1146 def __reduce__(self):
1147 return operator.getitem, (
1148 Annotated, (self.__origin__,) + self.__metadata__
1149 )
1151 def __eq__(self, other):
1152 if not isinstance(other, _AnnotatedAlias):
1153 return NotImplemented
1154 if self.__origin__ != other.__origin__:
1155 return False
1156 return self.__metadata__ == other.__metadata__
1158 def __hash__(self):
1159 return hash((self.__origin__, self.__metadata__))
1161 class Annotated:
1162 """Add context specific metadata to a type.
1164 Example: Annotated[int, runtime_check.Unsigned] indicates to the
1165 hypothetical runtime_check module that this type is an unsigned int.
1166 Every other consumer of this type can ignore this metadata and treat
1167 this type as int.
1169 The first argument to Annotated must be a valid type (and will be in
1170 the __origin__ field), the remaining arguments are kept as a tuple in
1171 the __extra__ field.
1173 Details:
1175 - It's an error to call `Annotated` with less than two arguments.
1176 - Nested Annotated are flattened::
1178 Annotated[Annotated[T, Ann1, Ann2], Ann3] == Annotated[T, Ann1, Ann2, Ann3]
1180 - Instantiating an annotated type is equivalent to instantiating the
1181 underlying type::
1183 Annotated[C, Ann1](5) == C(5)
1185 - Annotated can be used as a generic type alias::
1187 Optimized = Annotated[T, runtime.Optimize()]
1188 Optimized[int] == Annotated[int, runtime.Optimize()]
1190 OptimizedList = Annotated[List[T], runtime.Optimize()]
1191 OptimizedList[int] == Annotated[List[int], runtime.Optimize()]
1192 """
1194 __slots__ = ()
1196 def __new__(cls, *args, **kwargs):
1197 raise TypeError("Type Annotated cannot be instantiated.")
1199 @typing._tp_cache
1200 def __class_getitem__(cls, params):
1201 if not isinstance(params, tuple) or len(params) < 2:
1202 raise TypeError("Annotated[...] should be used "
1203 "with at least two arguments (a type and an "
1204 "annotation).")
1205 allowed_special_forms = (ClassVar, Final)
1206 if get_origin(params[0]) in allowed_special_forms:
1207 origin = params[0]
1208 else:
1209 msg = "Annotated[t, ...]: t must be a type."
1210 origin = typing._type_check(params[0], msg)
1211 metadata = tuple(params[1:])
1212 return _AnnotatedAlias(origin, metadata)
1214 def __init_subclass__(cls, *args, **kwargs):
1215 raise TypeError(
1216 f"Cannot subclass {cls.__module__}.Annotated"
1217 )
1219# Python 3.8 has get_origin() and get_args() but those implementations aren't
1220# Annotated-aware, so we can't use those. Python 3.9's versions don't support
1221# ParamSpecArgs and ParamSpecKwargs, so only Python 3.10's versions will do.
1222if sys.version_info[:2] >= (3, 10):
1223 get_origin = typing.get_origin
1224 get_args = typing.get_args
1225# 3.8-3.9
1226else:
1227 try:
1228 # 3.9+
1229 from typing import _BaseGenericAlias
1230 except ImportError:
1231 _BaseGenericAlias = typing._GenericAlias
1232 try:
1233 # 3.9+
1234 from typing import GenericAlias as _typing_GenericAlias
1235 except ImportError:
1236 _typing_GenericAlias = typing._GenericAlias
1238 def get_origin(tp):
1239 """Get the unsubscripted version of a type.
1241 This supports generic types, Callable, Tuple, Union, Literal, Final, ClassVar
1242 and Annotated. Return None for unsupported types. Examples::
1244 get_origin(Literal[42]) is Literal
1245 get_origin(int) is None
1246 get_origin(ClassVar[int]) is ClassVar
1247 get_origin(Generic) is Generic
1248 get_origin(Generic[T]) is Generic
1249 get_origin(Union[T, int]) is Union
1250 get_origin(List[Tuple[T, T]][int]) == list
1251 get_origin(P.args) is P
1252 """
1253 if isinstance(tp, _AnnotatedAlias):
1254 return Annotated
1255 if isinstance(tp, (typing._GenericAlias, _typing_GenericAlias, _BaseGenericAlias,
1256 ParamSpecArgs, ParamSpecKwargs)):
1257 return tp.__origin__
1258 if tp is typing.Generic:
1259 return typing.Generic
1260 return None
1262 def get_args(tp):
1263 """Get type arguments with all substitutions performed.
1265 For unions, basic simplifications used by Union constructor are performed.
1266 Examples::
1267 get_args(Dict[str, int]) == (str, int)
1268 get_args(int) == ()
1269 get_args(Union[int, Union[T, int], str][int]) == (int, str)
1270 get_args(Union[int, Tuple[T, int]][str]) == (int, Tuple[str, int])
1271 get_args(Callable[[], T][int]) == ([], int)
1272 """
1273 if isinstance(tp, _AnnotatedAlias):
1274 return (tp.__origin__,) + tp.__metadata__
1275 if isinstance(tp, (typing._GenericAlias, _typing_GenericAlias)):
1276 if getattr(tp, "_special", False):
1277 return ()
1278 res = tp.__args__
1279 if get_origin(tp) is collections.abc.Callable and res[0] is not Ellipsis:
1280 res = (list(res[:-1]), res[-1])
1281 return res
1282 return ()
1285# 3.10+
1286if hasattr(typing, 'TypeAlias'):
1287 TypeAlias = typing.TypeAlias
1288# 3.9
1289elif sys.version_info[:2] >= (3, 9):
1290 @_ExtensionsSpecialForm
1291 def TypeAlias(self, parameters):
1292 """Special marker indicating that an assignment should
1293 be recognized as a proper type alias definition by type
1294 checkers.
1296 For example::
1298 Predicate: TypeAlias = Callable[..., bool]
1300 It's invalid when used anywhere except as in the example above.
1301 """
1302 raise TypeError(f"{self} is not subscriptable")
1303# 3.8
1304else:
1305 TypeAlias = _ExtensionsSpecialForm(
1306 'TypeAlias',
1307 doc="""Special marker indicating that an assignment should
1308 be recognized as a proper type alias definition by type
1309 checkers.
1311 For example::
1313 Predicate: TypeAlias = Callable[..., bool]
1315 It's invalid when used anywhere except as in the example
1316 above."""
1317 )
1320def _set_default(type_param, default):
1321 if isinstance(default, (tuple, list)):
1322 type_param.__default__ = tuple((typing._type_check(d, "Default must be a type")
1323 for d in default))
1324 elif default != _marker:
1325 if isinstance(type_param, ParamSpec) and default is ...: # ... not valid <3.11
1326 type_param.__default__ = default
1327 else:
1328 type_param.__default__ = typing._type_check(default, "Default must be a type")
1329 else:
1330 type_param.__default__ = None
1333def _set_module(typevarlike):
1334 # for pickling:
1335 def_mod = _caller(depth=3)
1336 if def_mod != 'typing_extensions':
1337 typevarlike.__module__ = def_mod
1340class _DefaultMixin:
1341 """Mixin for TypeVarLike defaults."""
1343 __slots__ = ()
1344 __init__ = _set_default
1347# Classes using this metaclass must provide a _backported_typevarlike ClassVar
1348class _TypeVarLikeMeta(type):
1349 def __instancecheck__(cls, __instance: Any) -> bool:
1350 return isinstance(__instance, cls._backported_typevarlike)
1353# Add default and infer_variance parameters from PEP 696 and 695
1354class TypeVar(metaclass=_TypeVarLikeMeta):
1355 """Type variable."""
1357 _backported_typevarlike = typing.TypeVar
1359 def __new__(cls, name, *constraints, bound=None,
1360 covariant=False, contravariant=False,
1361 default=_marker, infer_variance=False):
1362 if hasattr(typing, "TypeAliasType"):
1363 # PEP 695 implemented (3.12+), can pass infer_variance to typing.TypeVar
1364 typevar = typing.TypeVar(name, *constraints, bound=bound,
1365 covariant=covariant, contravariant=contravariant,
1366 infer_variance=infer_variance)
1367 else:
1368 typevar = typing.TypeVar(name, *constraints, bound=bound,
1369 covariant=covariant, contravariant=contravariant)
1370 if infer_variance and (covariant or contravariant):
1371 raise ValueError("Variance cannot be specified with infer_variance.")
1372 typevar.__infer_variance__ = infer_variance
1373 _set_default(typevar, default)
1374 _set_module(typevar)
1375 return typevar
1377 def __init_subclass__(cls) -> None:
1378 raise TypeError(f"type '{__name__}.TypeVar' is not an acceptable base type")
1381# Python 3.10+ has PEP 612
1382if hasattr(typing, 'ParamSpecArgs'):
1383 ParamSpecArgs = typing.ParamSpecArgs
1384 ParamSpecKwargs = typing.ParamSpecKwargs
1385# 3.8-3.9
1386else:
1387 class _Immutable:
1388 """Mixin to indicate that object should not be copied."""
1389 __slots__ = ()
1391 def __copy__(self):
1392 return self
1394 def __deepcopy__(self, memo):
1395 return self
1397 class ParamSpecArgs(_Immutable):
1398 """The args for a ParamSpec object.
1400 Given a ParamSpec object P, P.args is an instance of ParamSpecArgs.
1402 ParamSpecArgs objects have a reference back to their ParamSpec:
1404 P.args.__origin__ is P
1406 This type is meant for runtime introspection and has no special meaning to
1407 static type checkers.
1408 """
1409 def __init__(self, origin):
1410 self.__origin__ = origin
1412 def __repr__(self):
1413 return f"{self.__origin__.__name__}.args"
1415 def __eq__(self, other):
1416 if not isinstance(other, ParamSpecArgs):
1417 return NotImplemented
1418 return self.__origin__ == other.__origin__
1420 class ParamSpecKwargs(_Immutable):
1421 """The kwargs for a ParamSpec object.
1423 Given a ParamSpec object P, P.kwargs is an instance of ParamSpecKwargs.
1425 ParamSpecKwargs objects have a reference back to their ParamSpec:
1427 P.kwargs.__origin__ is P
1429 This type is meant for runtime introspection and has no special meaning to
1430 static type checkers.
1431 """
1432 def __init__(self, origin):
1433 self.__origin__ = origin
1435 def __repr__(self):
1436 return f"{self.__origin__.__name__}.kwargs"
1438 def __eq__(self, other):
1439 if not isinstance(other, ParamSpecKwargs):
1440 return NotImplemented
1441 return self.__origin__ == other.__origin__
1443# 3.10+
1444if hasattr(typing, 'ParamSpec'):
1446 # Add default parameter - PEP 696
1447 class ParamSpec(metaclass=_TypeVarLikeMeta):
1448 """Parameter specification."""
1450 _backported_typevarlike = typing.ParamSpec
1452 def __new__(cls, name, *, bound=None,
1453 covariant=False, contravariant=False,
1454 infer_variance=False, default=_marker):
1455 if hasattr(typing, "TypeAliasType"):
1456 # PEP 695 implemented, can pass infer_variance to typing.TypeVar
1457 paramspec = typing.ParamSpec(name, bound=bound,
1458 covariant=covariant,
1459 contravariant=contravariant,
1460 infer_variance=infer_variance)
1461 else:
1462 paramspec = typing.ParamSpec(name, bound=bound,
1463 covariant=covariant,
1464 contravariant=contravariant)
1465 paramspec.__infer_variance__ = infer_variance
1467 _set_default(paramspec, default)
1468 _set_module(paramspec)
1469 return paramspec
1471 def __init_subclass__(cls) -> None:
1472 raise TypeError(f"type '{__name__}.ParamSpec' is not an acceptable base type")
1474# 3.8-3.9
1475else:
1477 # Inherits from list as a workaround for Callable checks in Python < 3.9.2.
1478 class ParamSpec(list, _DefaultMixin):
1479 """Parameter specification variable.
1481 Usage::
1483 P = ParamSpec('P')
1485 Parameter specification variables exist primarily for the benefit of static
1486 type checkers. They are used to forward the parameter types of one
1487 callable to another callable, a pattern commonly found in higher order
1488 functions and decorators. They are only valid when used in ``Concatenate``,
1489 or s the first argument to ``Callable``. In Python 3.10 and higher,
1490 they are also supported in user-defined Generics at runtime.
1491 See class Generic for more information on generic types. An
1492 example for annotating a decorator::
1494 T = TypeVar('T')
1495 P = ParamSpec('P')
1497 def add_logging(f: Callable[P, T]) -> Callable[P, T]:
1498 '''A type-safe decorator to add logging to a function.'''
1499 def inner(*args: P.args, **kwargs: P.kwargs) -> T:
1500 logging.info(f'{f.__name__} was called')
1501 return f(*args, **kwargs)
1502 return inner
1504 @add_logging
1505 def add_two(x: float, y: float) -> float:
1506 '''Add two numbers together.'''
1507 return x + y
1509 Parameter specification variables defined with covariant=True or
1510 contravariant=True can be used to declare covariant or contravariant
1511 generic types. These keyword arguments are valid, but their actual semantics
1512 are yet to be decided. See PEP 612 for details.
1514 Parameter specification variables can be introspected. e.g.:
1516 P.__name__ == 'T'
1517 P.__bound__ == None
1518 P.__covariant__ == False
1519 P.__contravariant__ == False
1521 Note that only parameter specification variables defined in global scope can
1522 be pickled.
1523 """
1525 # Trick Generic __parameters__.
1526 __class__ = typing.TypeVar
1528 @property
1529 def args(self):
1530 return ParamSpecArgs(self)
1532 @property
1533 def kwargs(self):
1534 return ParamSpecKwargs(self)
1536 def __init__(self, name, *, bound=None, covariant=False, contravariant=False,
1537 infer_variance=False, default=_marker):
1538 super().__init__([self])
1539 self.__name__ = name
1540 self.__covariant__ = bool(covariant)
1541 self.__contravariant__ = bool(contravariant)
1542 self.__infer_variance__ = bool(infer_variance)
1543 if bound:
1544 self.__bound__ = typing._type_check(bound, 'Bound must be a type.')
1545 else:
1546 self.__bound__ = None
1547 _DefaultMixin.__init__(self, default)
1549 # for pickling:
1550 def_mod = _caller()
1551 if def_mod != 'typing_extensions':
1552 self.__module__ = def_mod
1554 def __repr__(self):
1555 if self.__infer_variance__:
1556 prefix = ''
1557 elif self.__covariant__:
1558 prefix = '+'
1559 elif self.__contravariant__:
1560 prefix = '-'
1561 else:
1562 prefix = '~'
1563 return prefix + self.__name__
1565 def __hash__(self):
1566 return object.__hash__(self)
1568 def __eq__(self, other):
1569 return self is other
1571 def __reduce__(self):
1572 return self.__name__
1574 # Hack to get typing._type_check to pass.
1575 def __call__(self, *args, **kwargs):
1576 pass
1579# 3.8-3.9
1580if not hasattr(typing, 'Concatenate'):
1581 # Inherits from list as a workaround for Callable checks in Python < 3.9.2.
1582 class _ConcatenateGenericAlias(list):
1584 # Trick Generic into looking into this for __parameters__.
1585 __class__ = typing._GenericAlias
1587 # Flag in 3.8.
1588 _special = False
1590 def __init__(self, origin, args):
1591 super().__init__(args)
1592 self.__origin__ = origin
1593 self.__args__ = args
1595 def __repr__(self):
1596 _type_repr = typing._type_repr
1597 return (f'{_type_repr(self.__origin__)}'
1598 f'[{", ".join(_type_repr(arg) for arg in self.__args__)}]')
1600 def __hash__(self):
1601 return hash((self.__origin__, self.__args__))
1603 # Hack to get typing._type_check to pass in Generic.
1604 def __call__(self, *args, **kwargs):
1605 pass
1607 @property
1608 def __parameters__(self):
1609 return tuple(
1610 tp for tp in self.__args__ if isinstance(tp, (typing.TypeVar, ParamSpec))
1611 )
1614# 3.8-3.9
1615@typing._tp_cache
1616def _concatenate_getitem(self, parameters):
1617 if parameters == ():
1618 raise TypeError("Cannot take a Concatenate of no types.")
1619 if not isinstance(parameters, tuple):
1620 parameters = (parameters,)
1621 if not isinstance(parameters[-1], ParamSpec):
1622 raise TypeError("The last parameter to Concatenate should be a "
1623 "ParamSpec variable.")
1624 msg = "Concatenate[arg, ...]: each arg must be a type."
1625 parameters = tuple(typing._type_check(p, msg) for p in parameters)
1626 return _ConcatenateGenericAlias(self, parameters)
1629# 3.10+
1630if hasattr(typing, 'Concatenate'):
1631 Concatenate = typing.Concatenate
1632 _ConcatenateGenericAlias = typing._ConcatenateGenericAlias # noqa: F811
1633# 3.9
1634elif sys.version_info[:2] >= (3, 9):
1635 @_ExtensionsSpecialForm
1636 def Concatenate(self, parameters):
1637 """Used in conjunction with ``ParamSpec`` and ``Callable`` to represent a
1638 higher order function which adds, removes or transforms parameters of a
1639 callable.
1641 For example::
1643 Callable[Concatenate[int, P], int]
1645 See PEP 612 for detailed information.
1646 """
1647 return _concatenate_getitem(self, parameters)
1648# 3.8
1649else:
1650 class _ConcatenateForm(_ExtensionsSpecialForm, _root=True):
1651 def __getitem__(self, parameters):
1652 return _concatenate_getitem(self, parameters)
1654 Concatenate = _ConcatenateForm(
1655 'Concatenate',
1656 doc="""Used in conjunction with ``ParamSpec`` and ``Callable`` to represent a
1657 higher order function which adds, removes or transforms parameters of a
1658 callable.
1660 For example::
1662 Callable[Concatenate[int, P], int]
1664 See PEP 612 for detailed information.
1665 """)
1667# 3.10+
1668if hasattr(typing, 'TypeGuard'):
1669 TypeGuard = typing.TypeGuard
1670# 3.9
1671elif sys.version_info[:2] >= (3, 9):
1672 @_ExtensionsSpecialForm
1673 def TypeGuard(self, parameters):
1674 """Special typing form used to annotate the return type of a user-defined
1675 type guard function. ``TypeGuard`` only accepts a single type argument.
1676 At runtime, functions marked this way should return a boolean.
1678 ``TypeGuard`` aims to benefit *type narrowing* -- a technique used by static
1679 type checkers to determine a more precise type of an expression within a
1680 program's code flow. Usually type narrowing is done by analyzing
1681 conditional code flow and applying the narrowing to a block of code. The
1682 conditional expression here is sometimes referred to as a "type guard".
1684 Sometimes it would be convenient to use a user-defined boolean function
1685 as a type guard. Such a function should use ``TypeGuard[...]`` as its
1686 return type to alert static type checkers to this intention.
1688 Using ``-> TypeGuard`` tells the static type checker that for a given
1689 function:
1691 1. The return value is a boolean.
1692 2. If the return value is ``True``, the type of its argument
1693 is the type inside ``TypeGuard``.
1695 For example::
1697 def is_str(val: Union[str, float]):
1698 # "isinstance" type guard
1699 if isinstance(val, str):
1700 # Type of ``val`` is narrowed to ``str``
1701 ...
1702 else:
1703 # Else, type of ``val`` is narrowed to ``float``.
1704 ...
1706 Strict type narrowing is not enforced -- ``TypeB`` need not be a narrower
1707 form of ``TypeA`` (it can even be a wider form) and this may lead to
1708 type-unsafe results. The main reason is to allow for things like
1709 narrowing ``List[object]`` to ``List[str]`` even though the latter is not
1710 a subtype of the former, since ``List`` is invariant. The responsibility of
1711 writing type-safe type guards is left to the user.
1713 ``TypeGuard`` also works with type variables. For more information, see
1714 PEP 647 (User-Defined Type Guards).
1715 """
1716 item = typing._type_check(parameters, f'{self} accepts only a single type.')
1717 return typing._GenericAlias(self, (item,))
1718# 3.8
1719else:
1720 class _TypeGuardForm(_ExtensionsSpecialForm, _root=True):
1721 def __getitem__(self, parameters):
1722 item = typing._type_check(parameters,
1723 f'{self._name} accepts only a single type')
1724 return typing._GenericAlias(self, (item,))
1726 TypeGuard = _TypeGuardForm(
1727 'TypeGuard',
1728 doc="""Special typing form used to annotate the return type of a user-defined
1729 type guard function. ``TypeGuard`` only accepts a single type argument.
1730 At runtime, functions marked this way should return a boolean.
1732 ``TypeGuard`` aims to benefit *type narrowing* -- a technique used by static
1733 type checkers to determine a more precise type of an expression within a
1734 program's code flow. Usually type narrowing is done by analyzing
1735 conditional code flow and applying the narrowing to a block of code. The
1736 conditional expression here is sometimes referred to as a "type guard".
1738 Sometimes it would be convenient to use a user-defined boolean function
1739 as a type guard. Such a function should use ``TypeGuard[...]`` as its
1740 return type to alert static type checkers to this intention.
1742 Using ``-> TypeGuard`` tells the static type checker that for a given
1743 function:
1745 1. The return value is a boolean.
1746 2. If the return value is ``True``, the type of its argument
1747 is the type inside ``TypeGuard``.
1749 For example::
1751 def is_str(val: Union[str, float]):
1752 # "isinstance" type guard
1753 if isinstance(val, str):
1754 # Type of ``val`` is narrowed to ``str``
1755 ...
1756 else:
1757 # Else, type of ``val`` is narrowed to ``float``.
1758 ...
1760 Strict type narrowing is not enforced -- ``TypeB`` need not be a narrower
1761 form of ``TypeA`` (it can even be a wider form) and this may lead to
1762 type-unsafe results. The main reason is to allow for things like
1763 narrowing ``List[object]`` to ``List[str]`` even though the latter is not
1764 a subtype of the former, since ``List`` is invariant. The responsibility of
1765 writing type-safe type guards is left to the user.
1767 ``TypeGuard`` also works with type variables. For more information, see
1768 PEP 647 (User-Defined Type Guards).
1769 """)
1772# Vendored from cpython typing._SpecialFrom
1773class _SpecialForm(typing._Final, _root=True):
1774 __slots__ = ('_name', '__doc__', '_getitem')
1776 def __init__(self, getitem):
1777 self._getitem = getitem
1778 self._name = getitem.__name__
1779 self.__doc__ = getitem.__doc__
1781 def __getattr__(self, item):
1782 if item in {'__name__', '__qualname__'}:
1783 return self._name
1785 raise AttributeError(item)
1787 def __mro_entries__(self, bases):
1788 raise TypeError(f"Cannot subclass {self!r}")
1790 def __repr__(self):
1791 return f'typing_extensions.{self._name}'
1793 def __reduce__(self):
1794 return self._name
1796 def __call__(self, *args, **kwds):
1797 raise TypeError(f"Cannot instantiate {self!r}")
1799 def __or__(self, other):
1800 return typing.Union[self, other]
1802 def __ror__(self, other):
1803 return typing.Union[other, self]
1805 def __instancecheck__(self, obj):
1806 raise TypeError(f"{self} cannot be used with isinstance()")
1808 def __subclasscheck__(self, cls):
1809 raise TypeError(f"{self} cannot be used with issubclass()")
1811 @typing._tp_cache
1812 def __getitem__(self, parameters):
1813 return self._getitem(self, parameters)
1816if hasattr(typing, "LiteralString"): # 3.11+
1817 LiteralString = typing.LiteralString
1818else:
1819 @_SpecialForm
1820 def LiteralString(self, params):
1821 """Represents an arbitrary literal string.
1823 Example::
1825 from typing_extensions import LiteralString
1827 def query(sql: LiteralString) -> ...:
1828 ...
1830 query("SELECT * FROM table") # ok
1831 query(f"SELECT * FROM {input()}") # not ok
1833 See PEP 675 for details.
1835 """
1836 raise TypeError(f"{self} is not subscriptable")
1839if hasattr(typing, "Self"): # 3.11+
1840 Self = typing.Self
1841else:
1842 @_SpecialForm
1843 def Self(self, params):
1844 """Used to spell the type of "self" in classes.
1846 Example::
1848 from typing import Self
1850 class ReturnsSelf:
1851 def parse(self, data: bytes) -> Self:
1852 ...
1853 return self
1855 """
1857 raise TypeError(f"{self} is not subscriptable")
1860if hasattr(typing, "Never"): # 3.11+
1861 Never = typing.Never
1862else:
1863 @_SpecialForm
1864 def Never(self, params):
1865 """The bottom type, a type that has no members.
1867 This can be used to define a function that should never be
1868 called, or a function that never returns::
1870 from typing_extensions import Never
1872 def never_call_me(arg: Never) -> None:
1873 pass
1875 def int_or_str(arg: int | str) -> None:
1876 never_call_me(arg) # type checker error
1877 match arg:
1878 case int():
1879 print("It's an int")
1880 case str():
1881 print("It's a str")
1882 case _:
1883 never_call_me(arg) # ok, arg is of type Never
1885 """
1887 raise TypeError(f"{self} is not subscriptable")
1890if hasattr(typing, 'Required'): # 3.11+
1891 Required = typing.Required
1892 NotRequired = typing.NotRequired
1893elif sys.version_info[:2] >= (3, 9): # 3.9-3.10
1894 @_ExtensionsSpecialForm
1895 def Required(self, parameters):
1896 """A special typing construct to mark a key of a total=False TypedDict
1897 as required. For example:
1899 class Movie(TypedDict, total=False):
1900 title: Required[str]
1901 year: int
1903 m = Movie(
1904 title='The Matrix', # typechecker error if key is omitted
1905 year=1999,
1906 )
1908 There is no runtime checking that a required key is actually provided
1909 when instantiating a related TypedDict.
1910 """
1911 item = typing._type_check(parameters, f'{self._name} accepts only a single type.')
1912 return typing._GenericAlias(self, (item,))
1914 @_ExtensionsSpecialForm
1915 def NotRequired(self, parameters):
1916 """A special typing construct to mark a key of a TypedDict as
1917 potentially missing. For example:
1919 class Movie(TypedDict):
1920 title: str
1921 year: NotRequired[int]
1923 m = Movie(
1924 title='The Matrix', # typechecker error if key is omitted
1925 year=1999,
1926 )
1927 """
1928 item = typing._type_check(parameters, f'{self._name} accepts only a single type.')
1929 return typing._GenericAlias(self, (item,))
1931else: # 3.8
1932 class _RequiredForm(_ExtensionsSpecialForm, _root=True):
1933 def __getitem__(self, parameters):
1934 item = typing._type_check(parameters,
1935 f'{self._name} accepts only a single type.')
1936 return typing._GenericAlias(self, (item,))
1938 Required = _RequiredForm(
1939 'Required',
1940 doc="""A special typing construct to mark a key of a total=False TypedDict
1941 as required. For example:
1943 class Movie(TypedDict, total=False):
1944 title: Required[str]
1945 year: int
1947 m = Movie(
1948 title='The Matrix', # typechecker error if key is omitted
1949 year=1999,
1950 )
1952 There is no runtime checking that a required key is actually provided
1953 when instantiating a related TypedDict.
1954 """)
1955 NotRequired = _RequiredForm(
1956 'NotRequired',
1957 doc="""A special typing construct to mark a key of a TypedDict as
1958 potentially missing. For example:
1960 class Movie(TypedDict):
1961 title: str
1962 year: NotRequired[int]
1964 m = Movie(
1965 title='The Matrix', # typechecker error if key is omitted
1966 year=1999,
1967 )
1968 """)
1971if hasattr(typing, 'ReadOnly'):
1972 ReadOnly = typing.ReadOnly
1973elif sys.version_info[:2] >= (3, 9): # 3.9-3.12
1974 @_ExtensionsSpecialForm
1975 def ReadOnly(self, parameters):
1976 """A special typing construct to mark an item of a TypedDict as read-only.
1978 For example:
1980 class Movie(TypedDict):
1981 title: ReadOnly[str]
1982 year: int
1984 def mutate_movie(m: Movie) -> None:
1985 m["year"] = 1992 # allowed
1986 m["title"] = "The Matrix" # typechecker error
1988 There is no runtime checking for this property.
1989 """
1990 item = typing._type_check(parameters, f'{self._name} accepts only a single type.')
1991 return typing._GenericAlias(self, (item,))
1993else: # 3.8
1994 class _ReadOnlyForm(_ExtensionsSpecialForm, _root=True):
1995 def __getitem__(self, parameters):
1996 item = typing._type_check(parameters,
1997 f'{self._name} accepts only a single type.')
1998 return typing._GenericAlias(self, (item,))
2000 ReadOnly = _ReadOnlyForm(
2001 'ReadOnly',
2002 doc="""A special typing construct to mark a key of a TypedDict as read-only.
2004 For example:
2006 class Movie(TypedDict):
2007 title: ReadOnly[str]
2008 year: int
2010 def mutate_movie(m: Movie) -> None:
2011 m["year"] = 1992 # allowed
2012 m["title"] = "The Matrix" # typechecker error
2014 There is no runtime checking for this propery.
2015 """)
2018_UNPACK_DOC = """\
2019Type unpack operator.
2021The type unpack operator takes the child types from some container type,
2022such as `tuple[int, str]` or a `TypeVarTuple`, and 'pulls them out'. For
2023example:
2025 # For some generic class `Foo`:
2026 Foo[Unpack[tuple[int, str]]] # Equivalent to Foo[int, str]
2028 Ts = TypeVarTuple('Ts')
2029 # Specifies that `Bar` is generic in an arbitrary number of types.
2030 # (Think of `Ts` as a tuple of an arbitrary number of individual
2031 # `TypeVar`s, which the `Unpack` is 'pulling out' directly into the
2032 # `Generic[]`.)
2033 class Bar(Generic[Unpack[Ts]]): ...
2034 Bar[int] # Valid
2035 Bar[int, str] # Also valid
2037From Python 3.11, this can also be done using the `*` operator:
2039 Foo[*tuple[int, str]]
2040 class Bar(Generic[*Ts]): ...
2042The operator can also be used along with a `TypedDict` to annotate
2043`**kwargs` in a function signature. For instance:
2045 class Movie(TypedDict):
2046 name: str
2047 year: int
2049 # This function expects two keyword arguments - *name* of type `str` and
2050 # *year* of type `int`.
2051 def foo(**kwargs: Unpack[Movie]): ...
2053Note that there is only some runtime checking of this operator. Not
2054everything the runtime allows may be accepted by static type checkers.
2056For more information, see PEP 646 and PEP 692.
2057"""
2060if sys.version_info >= (3, 12): # PEP 692 changed the repr of Unpack[]
2061 Unpack = typing.Unpack
2063 def _is_unpack(obj):
2064 return get_origin(obj) is Unpack
2066elif sys.version_info[:2] >= (3, 9): # 3.9+
2067 class _UnpackSpecialForm(_ExtensionsSpecialForm, _root=True):
2068 def __init__(self, getitem):
2069 super().__init__(getitem)
2070 self.__doc__ = _UNPACK_DOC
2072 class _UnpackAlias(typing._GenericAlias, _root=True):
2073 __class__ = typing.TypeVar
2075 @_UnpackSpecialForm
2076 def Unpack(self, parameters):
2077 item = typing._type_check(parameters, f'{self._name} accepts only a single type.')
2078 return _UnpackAlias(self, (item,))
2080 def _is_unpack(obj):
2081 return isinstance(obj, _UnpackAlias)
2083else: # 3.8
2084 class _UnpackAlias(typing._GenericAlias, _root=True):
2085 __class__ = typing.TypeVar
2087 class _UnpackForm(_ExtensionsSpecialForm, _root=True):
2088 def __getitem__(self, parameters):
2089 item = typing._type_check(parameters,
2090 f'{self._name} accepts only a single type.')
2091 return _UnpackAlias(self, (item,))
2093 Unpack = _UnpackForm('Unpack', doc=_UNPACK_DOC)
2095 def _is_unpack(obj):
2096 return isinstance(obj, _UnpackAlias)
2099if hasattr(typing, "TypeVarTuple"): # 3.11+
2101 # Add default parameter - PEP 696
2102 class TypeVarTuple(metaclass=_TypeVarLikeMeta):
2103 """Type variable tuple."""
2105 _backported_typevarlike = typing.TypeVarTuple
2107 def __new__(cls, name, *, default=_marker):
2108 tvt = typing.TypeVarTuple(name)
2109 _set_default(tvt, default)
2110 _set_module(tvt)
2111 return tvt
2113 def __init_subclass__(self, *args, **kwds):
2114 raise TypeError("Cannot subclass special typing classes")
2116else: # <=3.10
2117 class TypeVarTuple(_DefaultMixin):
2118 """Type variable tuple.
2120 Usage::
2122 Ts = TypeVarTuple('Ts')
2124 In the same way that a normal type variable is a stand-in for a single
2125 type such as ``int``, a type variable *tuple* is a stand-in for a *tuple*
2126 type such as ``Tuple[int, str]``.
2128 Type variable tuples can be used in ``Generic`` declarations.
2129 Consider the following example::
2131 class Array(Generic[*Ts]): ...
2133 The ``Ts`` type variable tuple here behaves like ``tuple[T1, T2]``,
2134 where ``T1`` and ``T2`` are type variables. To use these type variables
2135 as type parameters of ``Array``, we must *unpack* the type variable tuple using
2136 the star operator: ``*Ts``. The signature of ``Array`` then behaves
2137 as if we had simply written ``class Array(Generic[T1, T2]): ...``.
2138 In contrast to ``Generic[T1, T2]``, however, ``Generic[*Shape]`` allows
2139 us to parameterise the class with an *arbitrary* number of type parameters.
2141 Type variable tuples can be used anywhere a normal ``TypeVar`` can.
2142 This includes class definitions, as shown above, as well as function
2143 signatures and variable annotations::
2145 class Array(Generic[*Ts]):
2147 def __init__(self, shape: Tuple[*Ts]):
2148 self._shape: Tuple[*Ts] = shape
2150 def get_shape(self) -> Tuple[*Ts]:
2151 return self._shape
2153 shape = (Height(480), Width(640))
2154 x: Array[Height, Width] = Array(shape)
2155 y = abs(x) # Inferred type is Array[Height, Width]
2156 z = x + x # ... is Array[Height, Width]
2157 x.get_shape() # ... is tuple[Height, Width]
2159 """
2161 # Trick Generic __parameters__.
2162 __class__ = typing.TypeVar
2164 def __iter__(self):
2165 yield self.__unpacked__
2167 def __init__(self, name, *, default=_marker):
2168 self.__name__ = name
2169 _DefaultMixin.__init__(self, default)
2171 # for pickling:
2172 def_mod = _caller()
2173 if def_mod != 'typing_extensions':
2174 self.__module__ = def_mod
2176 self.__unpacked__ = Unpack[self]
2178 def __repr__(self):
2179 return self.__name__
2181 def __hash__(self):
2182 return object.__hash__(self)
2184 def __eq__(self, other):
2185 return self is other
2187 def __reduce__(self):
2188 return self.__name__
2190 def __init_subclass__(self, *args, **kwds):
2191 if '_root' not in kwds:
2192 raise TypeError("Cannot subclass special typing classes")
2195if hasattr(typing, "reveal_type"): # 3.11+
2196 reveal_type = typing.reveal_type
2197else: # <=3.10
2198 def reveal_type(obj: T, /) -> T:
2199 """Reveal the inferred type of a variable.
2201 When a static type checker encounters a call to ``reveal_type()``,
2202 it will emit the inferred type of the argument::
2204 x: int = 1
2205 reveal_type(x)
2207 Running a static type checker (e.g., ``mypy``) on this example
2208 will produce output similar to 'Revealed type is "builtins.int"'.
2210 At runtime, the function prints the runtime type of the
2211 argument and returns it unchanged.
2213 """
2214 print(f"Runtime type is {type(obj).__name__!r}", file=sys.stderr)
2215 return obj
2218if hasattr(typing, "assert_never"): # 3.11+
2219 assert_never = typing.assert_never
2220else: # <=3.10
2221 def assert_never(arg: Never, /) -> Never:
2222 """Assert to the type checker that a line of code is unreachable.
2224 Example::
2226 def int_or_str(arg: int | str) -> None:
2227 match arg:
2228 case int():
2229 print("It's an int")
2230 case str():
2231 print("It's a str")
2232 case _:
2233 assert_never(arg)
2235 If a type checker finds that a call to assert_never() is
2236 reachable, it will emit an error.
2238 At runtime, this throws an exception when called.
2240 """
2241 raise AssertionError("Expected code to be unreachable")
2244if sys.version_info >= (3, 12): # 3.12+
2245 # dataclass_transform exists in 3.11 but lacks the frozen_default parameter
2246 dataclass_transform = typing.dataclass_transform
2247else: # <=3.11
2248 def dataclass_transform(
2249 *,
2250 eq_default: bool = True,
2251 order_default: bool = False,
2252 kw_only_default: bool = False,
2253 frozen_default: bool = False,
2254 field_specifiers: typing.Tuple[
2255 typing.Union[typing.Type[typing.Any], typing.Callable[..., typing.Any]],
2256 ...
2257 ] = (),
2258 **kwargs: typing.Any,
2259 ) -> typing.Callable[[T], T]:
2260 """Decorator that marks a function, class, or metaclass as providing
2261 dataclass-like behavior.
2263 Example:
2265 from typing_extensions import dataclass_transform
2267 _T = TypeVar("_T")
2269 # Used on a decorator function
2270 @dataclass_transform()
2271 def create_model(cls: type[_T]) -> type[_T]:
2272 ...
2273 return cls
2275 @create_model
2276 class CustomerModel:
2277 id: int
2278 name: str
2280 # Used on a base class
2281 @dataclass_transform()
2282 class ModelBase: ...
2284 class CustomerModel(ModelBase):
2285 id: int
2286 name: str
2288 # Used on a metaclass
2289 @dataclass_transform()
2290 class ModelMeta(type): ...
2292 class ModelBase(metaclass=ModelMeta): ...
2294 class CustomerModel(ModelBase):
2295 id: int
2296 name: str
2298 Each of the ``CustomerModel`` classes defined in this example will now
2299 behave similarly to a dataclass created with the ``@dataclasses.dataclass``
2300 decorator. For example, the type checker will synthesize an ``__init__``
2301 method.
2303 The arguments to this decorator can be used to customize this behavior:
2304 - ``eq_default`` indicates whether the ``eq`` parameter is assumed to be
2305 True or False if it is omitted by the caller.
2306 - ``order_default`` indicates whether the ``order`` parameter is
2307 assumed to be True or False if it is omitted by the caller.
2308 - ``kw_only_default`` indicates whether the ``kw_only`` parameter is
2309 assumed to be True or False if it is omitted by the caller.
2310 - ``frozen_default`` indicates whether the ``frozen`` parameter is
2311 assumed to be True or False if it is omitted by the caller.
2312 - ``field_specifiers`` specifies a static list of supported classes
2313 or functions that describe fields, similar to ``dataclasses.field()``.
2315 At runtime, this decorator records its arguments in the
2316 ``__dataclass_transform__`` attribute on the decorated object.
2318 See PEP 681 for details.
2320 """
2321 def decorator(cls_or_fn):
2322 cls_or_fn.__dataclass_transform__ = {
2323 "eq_default": eq_default,
2324 "order_default": order_default,
2325 "kw_only_default": kw_only_default,
2326 "frozen_default": frozen_default,
2327 "field_specifiers": field_specifiers,
2328 "kwargs": kwargs,
2329 }
2330 return cls_or_fn
2331 return decorator
2334if hasattr(typing, "override"): # 3.12+
2335 override = typing.override
2336else: # <=3.11
2337 _F = typing.TypeVar("_F", bound=typing.Callable[..., typing.Any])
2339 def override(arg: _F, /) -> _F:
2340 """Indicate that a method is intended to override a method in a base class.
2342 Usage:
2344 class Base:
2345 def method(self) -> None:
2346 pass
2348 class Child(Base):
2349 @override
2350 def method(self) -> None:
2351 super().method()
2353 When this decorator is applied to a method, the type checker will
2354 validate that it overrides a method with the same name on a base class.
2355 This helps prevent bugs that may occur when a base class is changed
2356 without an equivalent change to a child class.
2358 There is no runtime checking of these properties. The decorator
2359 sets the ``__override__`` attribute to ``True`` on the decorated object
2360 to allow runtime introspection.
2362 See PEP 698 for details.
2364 """
2365 try:
2366 arg.__override__ = True
2367 except (AttributeError, TypeError):
2368 # Skip the attribute silently if it is not writable.
2369 # AttributeError happens if the object has __slots__ or a
2370 # read-only property, TypeError if it's a builtin class.
2371 pass
2372 return arg
2375if hasattr(warnings, "deprecated"):
2376 deprecated = warnings.deprecated
2377else:
2378 _T = typing.TypeVar("_T")
2380 class deprecated:
2381 """Indicate that a class, function or overload is deprecated.
2383 When this decorator is applied to an object, the type checker
2384 will generate a diagnostic on usage of the deprecated object.
2386 Usage:
2388 @deprecated("Use B instead")
2389 class A:
2390 pass
2392 @deprecated("Use g instead")
2393 def f():
2394 pass
2396 @overload
2397 @deprecated("int support is deprecated")
2398 def g(x: int) -> int: ...
2399 @overload
2400 def g(x: str) -> int: ...
2402 The warning specified by *category* will be emitted at runtime
2403 on use of deprecated objects. For functions, that happens on calls;
2404 for classes, on instantiation and on creation of subclasses.
2405 If the *category* is ``None``, no warning is emitted at runtime.
2406 The *stacklevel* determines where the
2407 warning is emitted. If it is ``1`` (the default), the warning
2408 is emitted at the direct caller of the deprecated object; if it
2409 is higher, it is emitted further up the stack.
2410 Static type checker behavior is not affected by the *category*
2411 and *stacklevel* arguments.
2413 The deprecation message passed to the decorator is saved in the
2414 ``__deprecated__`` attribute on the decorated object.
2415 If applied to an overload, the decorator
2416 must be after the ``@overload`` decorator for the attribute to
2417 exist on the overload as returned by ``get_overloads()``.
2419 See PEP 702 for details.
2421 """
2422 def __init__(
2423 self,
2424 message: str,
2425 /,
2426 *,
2427 category: typing.Optional[typing.Type[Warning]] = DeprecationWarning,
2428 stacklevel: int = 1,
2429 ) -> None:
2430 if not isinstance(message, str):
2431 raise TypeError(
2432 "Expected an object of type str for 'message', not "
2433 f"{type(message).__name__!r}"
2434 )
2435 self.message = message
2436 self.category = category
2437 self.stacklevel = stacklevel
2439 def __call__(self, arg: _T, /) -> _T:
2440 # Make sure the inner functions created below don't
2441 # retain a reference to self.
2442 msg = self.message
2443 category = self.category
2444 stacklevel = self.stacklevel
2445 if category is None:
2446 arg.__deprecated__ = msg
2447 return arg
2448 elif isinstance(arg, type):
2449 import functools
2450 from types import MethodType
2452 original_new = arg.__new__
2454 @functools.wraps(original_new)
2455 def __new__(cls, *args, **kwargs):
2456 if cls is arg:
2457 warnings.warn(msg, category=category, stacklevel=stacklevel + 1)
2458 if original_new is not object.__new__:
2459 return original_new(cls, *args, **kwargs)
2460 # Mirrors a similar check in object.__new__.
2461 elif cls.__init__ is object.__init__ and (args or kwargs):
2462 raise TypeError(f"{cls.__name__}() takes no arguments")
2463 else:
2464 return original_new(cls)
2466 arg.__new__ = staticmethod(__new__)
2468 original_init_subclass = arg.__init_subclass__
2469 # We need slightly different behavior if __init_subclass__
2470 # is a bound method (likely if it was implemented in Python)
2471 if isinstance(original_init_subclass, MethodType):
2472 original_init_subclass = original_init_subclass.__func__
2474 @functools.wraps(original_init_subclass)
2475 def __init_subclass__(*args, **kwargs):
2476 warnings.warn(msg, category=category, stacklevel=stacklevel + 1)
2477 return original_init_subclass(*args, **kwargs)
2479 arg.__init_subclass__ = classmethod(__init_subclass__)
2480 # Or otherwise, which likely means it's a builtin such as
2481 # object's implementation of __init_subclass__.
2482 else:
2483 @functools.wraps(original_init_subclass)
2484 def __init_subclass__(*args, **kwargs):
2485 warnings.warn(msg, category=category, stacklevel=stacklevel + 1)
2486 return original_init_subclass(*args, **kwargs)
2488 arg.__init_subclass__ = __init_subclass__
2490 arg.__deprecated__ = __new__.__deprecated__ = msg
2491 __init_subclass__.__deprecated__ = msg
2492 return arg
2493 elif callable(arg):
2494 import functools
2496 @functools.wraps(arg)
2497 def wrapper(*args, **kwargs):
2498 warnings.warn(msg, category=category, stacklevel=stacklevel + 1)
2499 return arg(*args, **kwargs)
2501 arg.__deprecated__ = wrapper.__deprecated__ = msg
2502 return wrapper
2503 else:
2504 raise TypeError(
2505 "@deprecated decorator with non-None category must be applied to "
2506 f"a class or callable, not {arg!r}"
2507 )
2510# We have to do some monkey patching to deal with the dual nature of
2511# Unpack/TypeVarTuple:
2512# - We want Unpack to be a kind of TypeVar so it gets accepted in
2513# Generic[Unpack[Ts]]
2514# - We want it to *not* be treated as a TypeVar for the purposes of
2515# counting generic parameters, so that when we subscript a generic,
2516# the runtime doesn't try to substitute the Unpack with the subscripted type.
2517if not hasattr(typing, "TypeVarTuple"):
2518 typing._collect_type_vars = _collect_type_vars
2519 typing._check_generic = _check_generic
2522# Backport typing.NamedTuple as it exists in Python 3.13.
2523# In 3.11, the ability to define generic `NamedTuple`s was supported.
2524# This was explicitly disallowed in 3.9-3.10, and only half-worked in <=3.8.
2525# On 3.12, we added __orig_bases__ to call-based NamedTuples
2526# On 3.13, we deprecated kwargs-based NamedTuples
2527if sys.version_info >= (3, 13):
2528 NamedTuple = typing.NamedTuple
2529else:
2530 def _make_nmtuple(name, types, module, defaults=()):
2531 fields = [n for n, t in types]
2532 annotations = {n: typing._type_check(t, f"field {n} annotation must be a type")
2533 for n, t in types}
2534 nm_tpl = collections.namedtuple(name, fields,
2535 defaults=defaults, module=module)
2536 nm_tpl.__annotations__ = nm_tpl.__new__.__annotations__ = annotations
2537 # The `_field_types` attribute was removed in 3.9;
2538 # in earlier versions, it is the same as the `__annotations__` attribute
2539 if sys.version_info < (3, 9):
2540 nm_tpl._field_types = annotations
2541 return nm_tpl
2543 _prohibited_namedtuple_fields = typing._prohibited
2544 _special_namedtuple_fields = frozenset({'__module__', '__name__', '__annotations__'})
2546 class _NamedTupleMeta(type):
2547 def __new__(cls, typename, bases, ns):
2548 assert _NamedTuple in bases
2549 for base in bases:
2550 if base is not _NamedTuple and base is not typing.Generic:
2551 raise TypeError(
2552 'can only inherit from a NamedTuple type and Generic')
2553 bases = tuple(tuple if base is _NamedTuple else base for base in bases)
2554 types = ns.get('__annotations__', {})
2555 default_names = []
2556 for field_name in types:
2557 if field_name in ns:
2558 default_names.append(field_name)
2559 elif default_names:
2560 raise TypeError(f"Non-default namedtuple field {field_name} "
2561 f"cannot follow default field"
2562 f"{'s' if len(default_names) > 1 else ''} "
2563 f"{', '.join(default_names)}")
2564 nm_tpl = _make_nmtuple(
2565 typename, types.items(),
2566 defaults=[ns[n] for n in default_names],
2567 module=ns['__module__']
2568 )
2569 nm_tpl.__bases__ = bases
2570 if typing.Generic in bases:
2571 if hasattr(typing, '_generic_class_getitem'): # 3.12+
2572 nm_tpl.__class_getitem__ = classmethod(typing._generic_class_getitem)
2573 else:
2574 class_getitem = typing.Generic.__class_getitem__.__func__
2575 nm_tpl.__class_getitem__ = classmethod(class_getitem)
2576 # update from user namespace without overriding special namedtuple attributes
2577 for key, val in ns.items():
2578 if key in _prohibited_namedtuple_fields:
2579 raise AttributeError("Cannot overwrite NamedTuple attribute " + key)
2580 elif key not in _special_namedtuple_fields:
2581 if key not in nm_tpl._fields:
2582 setattr(nm_tpl, key, ns[key])
2583 try:
2584 set_name = type(val).__set_name__
2585 except AttributeError:
2586 pass
2587 else:
2588 try:
2589 set_name(val, nm_tpl, key)
2590 except BaseException as e:
2591 msg = (
2592 f"Error calling __set_name__ on {type(val).__name__!r} "
2593 f"instance {key!r} in {typename!r}"
2594 )
2595 # BaseException.add_note() existed on py311,
2596 # but the __set_name__ machinery didn't start
2597 # using add_note() until py312.
2598 # Making sure exceptions are raised in the same way
2599 # as in "normal" classes seems most important here.
2600 if sys.version_info >= (3, 12):
2601 e.add_note(msg)
2602 raise
2603 else:
2604 raise RuntimeError(msg) from e
2606 if typing.Generic in bases:
2607 nm_tpl.__init_subclass__()
2608 return nm_tpl
2610 _NamedTuple = type.__new__(_NamedTupleMeta, 'NamedTuple', (), {})
2612 def _namedtuple_mro_entries(bases):
2613 assert NamedTuple in bases
2614 return (_NamedTuple,)
2616 @_ensure_subclassable(_namedtuple_mro_entries)
2617 def NamedTuple(typename, fields=_marker, /, **kwargs):
2618 """Typed version of namedtuple.
2620 Usage::
2622 class Employee(NamedTuple):
2623 name: str
2624 id: int
2626 This is equivalent to::
2628 Employee = collections.namedtuple('Employee', ['name', 'id'])
2630 The resulting class has an extra __annotations__ attribute, giving a
2631 dict that maps field names to types. (The field names are also in
2632 the _fields attribute, which is part of the namedtuple API.)
2633 An alternative equivalent functional syntax is also accepted::
2635 Employee = NamedTuple('Employee', [('name', str), ('id', int)])
2636 """
2637 if fields is _marker:
2638 if kwargs:
2639 deprecated_thing = "Creating NamedTuple classes using keyword arguments"
2640 deprecation_msg = (
2641 "{name} is deprecated and will be disallowed in Python {remove}. "
2642 "Use the class-based or functional syntax instead."
2643 )
2644 else:
2645 deprecated_thing = "Failing to pass a value for the 'fields' parameter"
2646 example = f"`{typename} = NamedTuple({typename!r}, [])`"
2647 deprecation_msg = (
2648 "{name} is deprecated and will be disallowed in Python {remove}. "
2649 "To create a NamedTuple class with 0 fields "
2650 "using the functional syntax, "
2651 "pass an empty list, e.g. "
2652 ) + example + "."
2653 elif fields is None:
2654 if kwargs:
2655 raise TypeError(
2656 "Cannot pass `None` as the 'fields' parameter "
2657 "and also specify fields using keyword arguments"
2658 )
2659 else:
2660 deprecated_thing = "Passing `None` as the 'fields' parameter"
2661 example = f"`{typename} = NamedTuple({typename!r}, [])`"
2662 deprecation_msg = (
2663 "{name} is deprecated and will be disallowed in Python {remove}. "
2664 "To create a NamedTuple class with 0 fields "
2665 "using the functional syntax, "
2666 "pass an empty list, e.g. "
2667 ) + example + "."
2668 elif kwargs:
2669 raise TypeError("Either list of fields or keywords"
2670 " can be provided to NamedTuple, not both")
2671 if fields is _marker or fields is None:
2672 warnings.warn(
2673 deprecation_msg.format(name=deprecated_thing, remove="3.15"),
2674 DeprecationWarning,
2675 stacklevel=2,
2676 )
2677 fields = kwargs.items()
2678 nt = _make_nmtuple(typename, fields, module=_caller())
2679 nt.__orig_bases__ = (NamedTuple,)
2680 return nt
2683if hasattr(collections.abc, "Buffer"):
2684 Buffer = collections.abc.Buffer
2685else:
2686 class Buffer(abc.ABC):
2687 """Base class for classes that implement the buffer protocol.
2689 The buffer protocol allows Python objects to expose a low-level
2690 memory buffer interface. Before Python 3.12, it is not possible
2691 to implement the buffer protocol in pure Python code, or even
2692 to check whether a class implements the buffer protocol. In
2693 Python 3.12 and higher, the ``__buffer__`` method allows access
2694 to the buffer protocol from Python code, and the
2695 ``collections.abc.Buffer`` ABC allows checking whether a class
2696 implements the buffer protocol.
2698 To indicate support for the buffer protocol in earlier versions,
2699 inherit from this ABC, either in a stub file or at runtime,
2700 or use ABC registration. This ABC provides no methods, because
2701 there is no Python-accessible methods shared by pre-3.12 buffer
2702 classes. It is useful primarily for static checks.
2704 """
2706 # As a courtesy, register the most common stdlib buffer classes.
2707 Buffer.register(memoryview)
2708 Buffer.register(bytearray)
2709 Buffer.register(bytes)
2712# Backport of types.get_original_bases, available on 3.12+ in CPython
2713if hasattr(_types, "get_original_bases"):
2714 get_original_bases = _types.get_original_bases
2715else:
2716 def get_original_bases(cls, /):
2717 """Return the class's "original" bases prior to modification by `__mro_entries__`.
2719 Examples::
2721 from typing import TypeVar, Generic
2722 from typing_extensions import NamedTuple, TypedDict
2724 T = TypeVar("T")
2725 class Foo(Generic[T]): ...
2726 class Bar(Foo[int], float): ...
2727 class Baz(list[str]): ...
2728 Eggs = NamedTuple("Eggs", [("a", int), ("b", str)])
2729 Spam = TypedDict("Spam", {"a": int, "b": str})
2731 assert get_original_bases(Bar) == (Foo[int], float)
2732 assert get_original_bases(Baz) == (list[str],)
2733 assert get_original_bases(Eggs) == (NamedTuple,)
2734 assert get_original_bases(Spam) == (TypedDict,)
2735 assert get_original_bases(int) == (object,)
2736 """
2737 try:
2738 return cls.__dict__.get("__orig_bases__", cls.__bases__)
2739 except AttributeError:
2740 raise TypeError(
2741 f'Expected an instance of type, not {type(cls).__name__!r}'
2742 ) from None
2745# NewType is a class on Python 3.10+, making it pickleable
2746# The error message for subclassing instances of NewType was improved on 3.11+
2747if sys.version_info >= (3, 11):
2748 NewType = typing.NewType
2749else:
2750 class NewType:
2751 """NewType creates simple unique types with almost zero
2752 runtime overhead. NewType(name, tp) is considered a subtype of tp
2753 by static type checkers. At runtime, NewType(name, tp) returns
2754 a dummy callable that simply returns its argument. Usage::
2755 UserId = NewType('UserId', int)
2756 def name_by_id(user_id: UserId) -> str:
2757 ...
2758 UserId('user') # Fails type check
2759 name_by_id(42) # Fails type check
2760 name_by_id(UserId(42)) # OK
2761 num = UserId(5) + 1 # type: int
2762 """
2764 def __call__(self, obj, /):
2765 return obj
2767 def __init__(self, name, tp):
2768 self.__qualname__ = name
2769 if '.' in name:
2770 name = name.rpartition('.')[-1]
2771 self.__name__ = name
2772 self.__supertype__ = tp
2773 def_mod = _caller()
2774 if def_mod != 'typing_extensions':
2775 self.__module__ = def_mod
2777 def __mro_entries__(self, bases):
2778 # We defined __mro_entries__ to get a better error message
2779 # if a user attempts to subclass a NewType instance. bpo-46170
2780 supercls_name = self.__name__
2782 class Dummy:
2783 def __init_subclass__(cls):
2784 subcls_name = cls.__name__
2785 raise TypeError(
2786 f"Cannot subclass an instance of NewType. "
2787 f"Perhaps you were looking for: "
2788 f"`{subcls_name} = NewType({subcls_name!r}, {supercls_name})`"
2789 )
2791 return (Dummy,)
2793 def __repr__(self):
2794 return f'{self.__module__}.{self.__qualname__}'
2796 def __reduce__(self):
2797 return self.__qualname__
2799 if sys.version_info >= (3, 10):
2800 # PEP 604 methods
2801 # It doesn't make sense to have these methods on Python <3.10
2803 def __or__(self, other):
2804 return typing.Union[self, other]
2806 def __ror__(self, other):
2807 return typing.Union[other, self]
2810if hasattr(typing, "TypeAliasType"):
2811 TypeAliasType = typing.TypeAliasType
2812else:
2813 def _is_unionable(obj):
2814 """Corresponds to is_unionable() in unionobject.c in CPython."""
2815 return obj is None or isinstance(obj, (
2816 type,
2817 _types.GenericAlias,
2818 _types.UnionType,
2819 TypeAliasType,
2820 ))
2822 class TypeAliasType:
2823 """Create named, parameterized type aliases.
2825 This provides a backport of the new `type` statement in Python 3.12:
2827 type ListOrSet[T] = list[T] | set[T]
2829 is equivalent to:
2831 T = TypeVar("T")
2832 ListOrSet = TypeAliasType("ListOrSet", list[T] | set[T], type_params=(T,))
2834 The name ListOrSet can then be used as an alias for the type it refers to.
2836 The type_params argument should contain all the type parameters used
2837 in the value of the type alias. If the alias is not generic, this
2838 argument is omitted.
2840 Static type checkers should only support type aliases declared using
2841 TypeAliasType that follow these rules:
2843 - The first argument (the name) must be a string literal.
2844 - The TypeAliasType instance must be immediately assigned to a variable
2845 of the same name. (For example, 'X = TypeAliasType("Y", int)' is invalid,
2846 as is 'X, Y = TypeAliasType("X", int), TypeAliasType("Y", int)').
2848 """
2850 def __init__(self, name: str, value, *, type_params=()):
2851 if not isinstance(name, str):
2852 raise TypeError("TypeAliasType name must be a string")
2853 self.__value__ = value
2854 self.__type_params__ = type_params
2856 parameters = []
2857 for type_param in type_params:
2858 if isinstance(type_param, TypeVarTuple):
2859 parameters.extend(type_param)
2860 else:
2861 parameters.append(type_param)
2862 self.__parameters__ = tuple(parameters)
2863 def_mod = _caller()
2864 if def_mod != 'typing_extensions':
2865 self.__module__ = def_mod
2866 # Setting this attribute closes the TypeAliasType from further modification
2867 self.__name__ = name
2869 def __setattr__(self, name: str, value: object, /) -> None:
2870 if hasattr(self, "__name__"):
2871 self._raise_attribute_error(name)
2872 super().__setattr__(name, value)
2874 def __delattr__(self, name: str, /) -> Never:
2875 self._raise_attribute_error(name)
2877 def _raise_attribute_error(self, name: str) -> Never:
2878 # Match the Python 3.12 error messages exactly
2879 if name == "__name__":
2880 raise AttributeError("readonly attribute")
2881 elif name in {"__value__", "__type_params__", "__parameters__", "__module__"}:
2882 raise AttributeError(
2883 f"attribute '{name}' of 'typing.TypeAliasType' objects "
2884 "is not writable"
2885 )
2886 else:
2887 raise AttributeError(
2888 f"'typing.TypeAliasType' object has no attribute '{name}'"
2889 )
2891 def __repr__(self) -> str:
2892 return self.__name__
2894 def __getitem__(self, parameters):
2895 if not isinstance(parameters, tuple):
2896 parameters = (parameters,)
2897 parameters = [
2898 typing._type_check(
2899 item, f'Subscripting {self.__name__} requires a type.'
2900 )
2901 for item in parameters
2902 ]
2903 return typing._GenericAlias(self, tuple(parameters))
2905 def __reduce__(self):
2906 return self.__name__
2908 def __init_subclass__(cls, *args, **kwargs):
2909 raise TypeError(
2910 "type 'typing_extensions.TypeAliasType' is not an acceptable base type"
2911 )
2913 # The presence of this method convinces typing._type_check
2914 # that TypeAliasTypes are types.
2915 def __call__(self):
2916 raise TypeError("Type alias is not callable")
2918 if sys.version_info >= (3, 10):
2919 def __or__(self, right):
2920 # For forward compatibility with 3.12, reject Unions
2921 # that are not accepted by the built-in Union.
2922 if not _is_unionable(right):
2923 return NotImplemented
2924 return typing.Union[self, right]
2926 def __ror__(self, left):
2927 if not _is_unionable(left):
2928 return NotImplemented
2929 return typing.Union[left, self]
2932if hasattr(typing, "is_protocol"):
2933 is_protocol = typing.is_protocol
2934 get_protocol_members = typing.get_protocol_members
2935else:
2936 def is_protocol(tp: type, /) -> bool:
2937 """Return True if the given type is a Protocol.
2939 Example::
2941 >>> from typing_extensions import Protocol, is_protocol
2942 >>> class P(Protocol):
2943 ... def a(self) -> str: ...
2944 ... b: int
2945 >>> is_protocol(P)
2946 True
2947 >>> is_protocol(int)
2948 False
2949 """
2950 return (
2951 isinstance(tp, type)
2952 and getattr(tp, '_is_protocol', False)
2953 and tp is not Protocol
2954 and tp is not typing.Protocol
2955 )
2957 def get_protocol_members(tp: type, /) -> typing.FrozenSet[str]:
2958 """Return the set of members defined in a Protocol.
2960 Example::
2962 >>> from typing_extensions import Protocol, get_protocol_members
2963 >>> class P(Protocol):
2964 ... def a(self) -> str: ...
2965 ... b: int
2966 >>> get_protocol_members(P)
2967 frozenset({'a', 'b'})
2969 Raise a TypeError for arguments that are not Protocols.
2970 """
2971 if not is_protocol(tp):
2972 raise TypeError(f'{tp!r} is not a Protocol')
2973 if hasattr(tp, '__protocol_attrs__'):
2974 return frozenset(tp.__protocol_attrs__)
2975 return frozenset(_get_protocol_attrs(tp))
2978if hasattr(typing, "Doc"):
2979 Doc = typing.Doc
2980else:
2981 class Doc:
2982 """Define the documentation of a type annotation using ``Annotated``, to be
2983 used in class attributes, function and method parameters, return values,
2984 and variables.
2986 The value should be a positional-only string literal to allow static tools
2987 like editors and documentation generators to use it.
2989 This complements docstrings.
2991 The string value passed is available in the attribute ``documentation``.
2993 Example::
2995 >>> from typing_extensions import Annotated, Doc
2996 >>> def hi(to: Annotated[str, Doc("Who to say hi to")]) -> None: ...
2997 """
2998 def __init__(self, documentation: str, /) -> None:
2999 self.documentation = documentation
3001 def __repr__(self) -> str:
3002 return f"Doc({self.documentation!r})"
3004 def __hash__(self) -> int:
3005 return hash(self.documentation)
3007 def __eq__(self, other: object) -> bool:
3008 if not isinstance(other, Doc):
3009 return NotImplemented
3010 return self.documentation == other.documentation
3013# Aliases for items that have always been in typing.
3014# Explicitly assign these (rather than using `from typing import *` at the top),
3015# so that we get a CI error if one of these is deleted from typing.py
3016# in a future version of Python
3017AbstractSet = typing.AbstractSet
3018AnyStr = typing.AnyStr
3019BinaryIO = typing.BinaryIO
3020Callable = typing.Callable
3021Collection = typing.Collection
3022Container = typing.Container
3023Dict = typing.Dict
3024ForwardRef = typing.ForwardRef
3025FrozenSet = typing.FrozenSet
3026Generator = typing.Generator
3027Generic = typing.Generic
3028Hashable = typing.Hashable
3029IO = typing.IO
3030ItemsView = typing.ItemsView
3031Iterable = typing.Iterable
3032Iterator = typing.Iterator
3033KeysView = typing.KeysView
3034List = typing.List
3035Mapping = typing.Mapping
3036MappingView = typing.MappingView
3037Match = typing.Match
3038MutableMapping = typing.MutableMapping
3039MutableSequence = typing.MutableSequence
3040MutableSet = typing.MutableSet
3041Optional = typing.Optional
3042Pattern = typing.Pattern
3043Reversible = typing.Reversible
3044Sequence = typing.Sequence
3045Set = typing.Set
3046Sized = typing.Sized
3047TextIO = typing.TextIO
3048Tuple = typing.Tuple
3049Union = typing.Union
3050ValuesView = typing.ValuesView
3051cast = typing.cast
3052no_type_check = typing.no_type_check
3053no_type_check_decorator = typing.no_type_check_decorator