12 # Super-special typing primitives.
27 # ABCs (from collections.abc).
33 'AsyncContextManager',
36 # Concrete collection types.
45 # Structural checks, a.k.a. protocols.
53 'dataclass_transform',
79 # for backward compatibility
83 # The functions below are modified copies of typing internal helpers.
84 # They are needed by _ProtocolMeta and they provide support for PEP 646.
89 def _check_generic(cls, parameters, elen=_marker):
90 """Check correct count for parameters of a generic cls (internal helper).
91 This gives a nice error message in case of count mismatch.
94 raise TypeError(f"{cls} is not a generic class")
96 if not hasattr(cls, "__parameters__") or not cls.__parameters__:
97 raise TypeError(f"{cls} is not a generic class")
98 elen = len(cls.__parameters__)
99 alen = len(parameters)
101 if hasattr(cls, "__parameters__"):
102 parameters = [p for p in cls.__parameters__ if not _is_unpack(p)]
103 num_tv_tuples = sum(isinstance(p, TypeVarTuple) for p in parameters)
104 if (num_tv_tuples > 0) and (alen >= elen - num_tv_tuples):
106 raise TypeError(f"Too {'many' if alen > elen else 'few'} parameters for {cls};"
107 f" actual {alen}, expected {elen}")
110 if sys.version_info >= (3, 10):
111 def _should_collect_from_parameters(t):
113 t, (typing._GenericAlias, _types.GenericAlias, _types.UnionType)
115 elif sys.version_info >= (3, 9):
116 def _should_collect_from_parameters(t):
117 return isinstance(t, (typing._GenericAlias, _types.GenericAlias))
119 def _should_collect_from_parameters(t):
120 return isinstance(t, typing._GenericAlias) and not t._special
123 def _collect_type_vars(types, typevar_types=None):
124 """Collect all type variable contained in types in order of
125 first appearance (lexicographic order). For example::
127 _collect_type_vars((T, List[S, T])) == (T, S)
129 if typevar_types is None:
130 typevar_types = typing.TypeVar
134 isinstance(t, typevar_types) and
139 if _should_collect_from_parameters(t):
140 tvars.extend([t for t in t.__parameters__ if t not in tvars])
144 NoReturn = typing.NoReturn
146 # Some unconstrained type variables. These are used by the container types.
147 # (These are not for export.)
148 T = typing.TypeVar('T') # Any type.
149 KT = typing.TypeVar('KT') # Key type.
150 VT = typing.TypeVar('VT') # Value type.
151 T_co = typing.TypeVar('T_co', covariant=True) # Any type covariant containers.
152 T_contra = typing.TypeVar('T_contra', contravariant=True) # Ditto contravariant.
155 if sys.version_info >= (3, 11):
156 from typing import Any
159 class _AnyMeta(type):
160 def __instancecheck__(self, obj):
162 raise TypeError("typing_extensions.Any cannot be used with isinstance()")
163 return super().__instancecheck__(obj)
167 return "typing_extensions.Any"
168 return super().__repr__()
170 class Any(metaclass=_AnyMeta):
171 """Special type indicating an unconstrained type.
172 - Any is compatible with every type.
173 - Any assumed to have all methods.
174 - All values assumed to be instances of Any.
175 Note that all the above statements are true from the point of view of
176 static type checkers. At runtime, Any should not be used with instance
179 def __new__(cls, *args, **kwargs):
181 raise TypeError("Any cannot be instantiated")
182 return super().__new__(cls, *args, **kwargs)
185 ClassVar = typing.ClassVar
187 # On older versions of typing there is an internal class named "Final".
189 if hasattr(typing, 'Final') and sys.version_info[:2] >= (3, 7):
193 class _FinalForm(typing._SpecialForm, _root=True):
196 return 'typing_extensions.' + self._name
198 def __getitem__(self, parameters):
199 item = typing._type_check(parameters,
200 f'{self._name} accepts only a single type.')
201 return typing._GenericAlias(self, (item,))
203 Final = _FinalForm('Final',
204 doc="""A special typing construct to indicate that a name
205 cannot be re-assigned or overridden in a subclass.
208 MAX_SIZE: Final = 9000
209 MAX_SIZE += 1 # Error reported by type checker
212 TIMEOUT: Final[int] = 10
213 class FastConnector(Connection):
214 TIMEOUT = 1 # Error reported by type checker
216 There is no runtime checking of these properties.""")
218 if sys.version_info >= (3, 11):
221 # @final exists in 3.8+, but we backport it for all versions
222 # before 3.11 to keep support for the __final__ attribute.
223 # See https://bugs.python.org/issue46342
225 """This decorator can be used to indicate to type checkers that
226 the decorated method cannot be overridden, and decorated class
227 cannot be subclassed. For example:
231 def done(self) -> None:
234 def done(self) -> None: # Error reported by type checker
239 class Other(Leaf): # Error reported by type checker
242 There is no runtime checking of these properties. The decorator
243 sets the ``__final__`` attribute to ``True`` on the decorated object
244 to allow runtime introspection.
248 except (AttributeError, TypeError):
249 # Skip the attribute silently if it is not writable.
250 # AttributeError happens if the object has __slots__ or a
251 # read-only property, TypeError if it's a builtin class.
257 return typing.TypeVar(name)
261 if hasattr(typing, 'Literal'):
262 Literal = typing.Literal
265 class _LiteralForm(typing._SpecialForm, _root=True):
268 return 'typing_extensions.' + self._name
270 def __getitem__(self, parameters):
271 return typing._GenericAlias(self, parameters)
273 Literal = _LiteralForm('Literal',
274 doc="""A type that can be used to indicate to type checkers
275 that the corresponding value has a value literally equivalent
276 to the provided parameter. For example:
280 The type checker understands that 'var' is literally equal to
281 the value 4 and no other value.
283 Literal[...] cannot be subclassed. There is no runtime
284 checking verifying that the parameter is actually a value
285 instead of a type.""")
288 _overload_dummy = typing._overload_dummy # noqa
291 if hasattr(typing, "get_overloads"): # 3.11+
292 overload = typing.overload
293 get_overloads = typing.get_overloads
294 clear_overloads = typing.clear_overloads
296 # {module: {qualname: {firstlineno: func}}}
297 _overload_registry = collections.defaultdict(
298 functools.partial(collections.defaultdict, dict)
302 """Decorator for overloaded functions/methods.
304 In a stub file, place two or more stub definitions for the same
305 function in a row, each decorated with @overload. For example:
308 def utf8(value: None) -> None: ...
310 def utf8(value: bytes) -> bytes: ...
312 def utf8(value: str) -> bytes: ...
314 In a non-stub file (i.e. a regular .py file), do the same but
315 follow it with an implementation. The implementation should *not*
316 be decorated with @overload. For example:
319 def utf8(value: None) -> None: ...
321 def utf8(value: bytes) -> bytes: ...
323 def utf8(value: str) -> bytes: ...
325 # implementation goes here
327 The overloads for a function can be retrieved at runtime using the
328 get_overloads() function.
330 # classmethod and staticmethod
331 f = getattr(func, "__func__", func)
333 _overload_registry[f.__module__][f.__qualname__][
334 f.__code__.co_firstlineno
336 except AttributeError:
337 # Not a normal function; ignore.
339 return _overload_dummy
341 def get_overloads(func):
342 """Return all defined overloads for *func* as a sequence."""
343 # classmethod and staticmethod
344 f = getattr(func, "__func__", func)
345 if f.__module__ not in _overload_registry:
347 mod_dict = _overload_registry[f.__module__]
348 if f.__qualname__ not in mod_dict:
350 return list(mod_dict[f.__qualname__].values())
352 def clear_overloads():
353 """Clear all overloads in the registry."""
354 _overload_registry.clear()
357 # This is not a real generic class. Don't use outside annotations.
360 # Various ABCs mimicking those in collections.abc.
361 # A few are simply re-exported for completeness.
364 Awaitable = typing.Awaitable
365 Coroutine = typing.Coroutine
366 AsyncIterable = typing.AsyncIterable
367 AsyncIterator = typing.AsyncIterator
369 ContextManager = typing.ContextManager
370 AsyncContextManager = typing.AsyncContextManager
371 DefaultDict = typing.DefaultDict
374 if hasattr(typing, 'OrderedDict'):
375 OrderedDict = typing.OrderedDict
378 OrderedDict = typing._alias(collections.OrderedDict, (KT, VT))
380 Counter = typing.Counter
381 ChainMap = typing.ChainMap
382 AsyncGenerator = typing.AsyncGenerator
383 NewType = typing.NewType
385 TYPE_CHECKING = typing.TYPE_CHECKING
388 _PROTO_WHITELIST = ['Callable', 'Awaitable',
389 'Iterable', 'Iterator', 'AsyncIterable', 'AsyncIterator',
390 'Hashable', 'Sized', 'Container', 'Collection', 'Reversible',
391 'ContextManager', 'AsyncContextManager']
394 def _get_protocol_attrs(cls):
396 for base in cls.__mro__[:-1]: # without object
397 if base.__name__ in ('Protocol', 'Generic'):
399 annotations = getattr(base, '__annotations__', {})
400 for attr in list(base.__dict__.keys()) + list(annotations.keys()):
401 if (not attr.startswith('_abc_') and attr not in (
402 '__abstractmethods__', '__annotations__', '__weakref__',
403 '_is_protocol', '_is_runtime_protocol', '__dict__',
404 '__args__', '__slots__',
405 '__next_in_mro__', '__parameters__', '__origin__',
406 '__orig_bases__', '__extra__', '__tree_hash__',
407 '__doc__', '__subclasshook__', '__init__', '__new__',
408 '__module__', '_MutableMapping__marker', '_gorg')):
413 def _is_callable_members_only(cls):
414 return all(callable(getattr(cls, attr, None)) for attr in _get_protocol_attrs(cls))
417 def _maybe_adjust_parameters(cls):
418 """Helper function used in Protocol.__init_subclass__ and _TypedDictMeta.__new__.
420 The contents of this function are very similar
421 to logic found in typing.Generic.__init_subclass__
422 on the CPython main branch.
425 if '__orig_bases__' in cls.__dict__:
426 tvars = typing._collect_type_vars(cls.__orig_bases__)
427 # Look for Generic[T1, ..., Tn] or Protocol[T1, ..., Tn].
428 # If found, tvars must be a subset of it.
429 # If not found, tvars is it.
430 # Also check for and reject plain Generic,
431 # and reject multiple Generic[...] and/or Protocol[...].
433 for base in cls.__orig_bases__:
434 if (isinstance(base, typing._GenericAlias) and
435 base.__origin__ in (typing.Generic, Protocol)):
437 the_base = base.__origin__.__name__
438 if gvars is not None:
440 "Cannot inherit from Generic[...]"
441 " and/or Protocol[...] multiple types.")
442 gvars = base.__parameters__
448 if not tvarset <= gvarset:
449 s_vars = ', '.join(str(t) for t in tvars if t not in gvarset)
450 s_args = ', '.join(str(g) for g in gvars)
451 raise TypeError(f"Some type variables ({s_vars}) are"
452 f" not listed in {the_base}[{s_args}]")
454 cls.__parameters__ = tuple(tvars)
458 if hasattr(typing, 'Protocol'):
459 Protocol = typing.Protocol
463 def _no_init(self, *args, **kwargs):
464 if type(self)._is_protocol:
465 raise TypeError('Protocols cannot be instantiated')
467 class _ProtocolMeta(abc.ABCMeta): # noqa: B024
468 # This metaclass is a bit unfortunate and exists only because of the lack
469 # of __instancehook__.
470 def __instancecheck__(cls, instance):
471 # We need this method for situations where attributes are
472 # assigned in __init__.
473 if ((not getattr(cls, '_is_protocol', False) or
474 _is_callable_members_only(cls)) and
475 issubclass(instance.__class__, cls)):
478 if all(hasattr(instance, attr) and
479 (not callable(getattr(cls, attr, None)) or
480 getattr(instance, attr) is not None)
481 for attr in _get_protocol_attrs(cls)):
483 return super().__instancecheck__(instance)
485 class Protocol(metaclass=_ProtocolMeta):
486 # There is quite a lot of overlapping code with typing.Generic.
487 # Unfortunately it is hard to avoid this while these live in two different
488 # modules. The duplicated code will be removed when Protocol is moved to typing.
489 """Base class for protocol classes. Protocol classes are defined as::
491 class Proto(Protocol):
492 def meth(self) -> int:
495 Such classes are primarily used with static type checkers that recognize
496 structural subtyping (static duck-typing), for example::
499 def meth(self) -> int:
502 def func(x: Proto) -> int:
505 func(C()) # Passes static type check
507 See PEP 544 for details. Protocol classes decorated with
508 @typing_extensions.runtime act as simple-minded runtime protocol that checks
509 only the presence of given attributes, ignoring their type signatures.
511 Protocol classes can be generic, they are defined as::
513 class GenProto(Protocol[T]):
520 def __new__(cls, *args, **kwds):
522 raise TypeError("Type Protocol cannot be instantiated; "
523 "it can only be used as a base class")
524 return super().__new__(cls)
527 def __class_getitem__(cls, params):
528 if not isinstance(params, tuple):
530 if not params and cls is not typing.Tuple:
532 f"Parameter list to {cls.__qualname__}[...] cannot be empty")
533 msg = "Parameters to generic types must be types."
534 params = tuple(typing._type_check(p, msg) for p in params) # noqa
536 # Generic can only be subscripted with unique type variables.
537 if not all(isinstance(p, typing.TypeVar) for p in params):
539 while isinstance(params[i], typing.TypeVar):
542 "Parameters to Protocol[...] must all be type variables."
543 f" Parameter {i + 1} is {params[i]}")
544 if len(set(params)) != len(params):
546 "Parameters to Protocol[...] must all be unique")
548 # Subscripting a regular Generic subclass.
549 _check_generic(cls, params, len(cls.__parameters__))
550 return typing._GenericAlias(cls, params)
552 def __init_subclass__(cls, *args, **kwargs):
553 if '__orig_bases__' in cls.__dict__:
554 error = typing.Generic in cls.__orig_bases__
556 error = typing.Generic in cls.__bases__
558 raise TypeError("Cannot inherit from plain Generic")
559 _maybe_adjust_parameters(cls)
561 # Determine if this is a protocol or a concrete subclass.
562 if not cls.__dict__.get('_is_protocol', None):
563 cls._is_protocol = any(b is Protocol for b in cls.__bases__)
565 # Set (or override) the protocol subclass hook.
566 def _proto_hook(other):
567 if not cls.__dict__.get('_is_protocol', None):
568 return NotImplemented
569 if not getattr(cls, '_is_runtime_protocol', False):
570 if sys._getframe(2).f_globals['__name__'] in ['abc', 'functools']:
571 return NotImplemented
572 raise TypeError("Instance and class checks can only be used with"
573 " @runtime protocols")
574 if not _is_callable_members_only(cls):
575 if sys._getframe(2).f_globals['__name__'] in ['abc', 'functools']:
576 return NotImplemented
577 raise TypeError("Protocols with non-method members"
578 " don't support issubclass()")
579 if not isinstance(other, type):
580 # Same error as for issubclass(1, int)
581 raise TypeError('issubclass() arg 1 must be a class')
582 for attr in _get_protocol_attrs(cls):
583 for base in other.__mro__:
584 if attr in base.__dict__:
585 if base.__dict__[attr] is None:
586 return NotImplemented
588 annotations = getattr(base, '__annotations__', {})
589 if (isinstance(annotations, typing.Mapping) and
590 attr in annotations and
591 isinstance(other, _ProtocolMeta) and
595 return NotImplemented
597 if '__subclasshook__' not in cls.__dict__:
598 cls.__subclasshook__ = _proto_hook
600 # We have nothing more to do for non-protocols.
601 if not cls._is_protocol:
604 # Check consistency of bases.
605 for base in cls.__bases__:
606 if not (base in (object, typing.Generic) or
607 base.__module__ == 'collections.abc' and
608 base.__name__ in _PROTO_WHITELIST or
609 isinstance(base, _ProtocolMeta) and base._is_protocol):
610 raise TypeError('Protocols can only inherit from other'
611 f' protocols, got {repr(base)}')
612 cls.__init__ = _no_init
616 if hasattr(typing, 'runtime_checkable'):
617 runtime_checkable = typing.runtime_checkable
620 def runtime_checkable(cls):
621 """Mark a protocol class as a runtime protocol, so that it
622 can be used with isinstance() and issubclass(). Raise TypeError
623 if applied to a non-protocol class.
625 This allows a simple-minded structural check very similar to the
626 one-offs in collections.abc such as Hashable.
628 if not isinstance(cls, _ProtocolMeta) or not cls._is_protocol:
629 raise TypeError('@runtime_checkable can be only applied to protocol classes,'
631 cls._is_runtime_protocol = True
635 # Exists for backwards compatibility.
636 runtime = runtime_checkable
640 if hasattr(typing, 'SupportsIndex'):
641 SupportsIndex = typing.SupportsIndex
645 class SupportsIndex(Protocol):
649 def __index__(self) -> int:
653 if hasattr(typing, "Required"):
654 # The standard library TypedDict in Python 3.8 does not store runtime information
655 # about which (if any) keys are optional. See https://bugs.python.org/issue38834
656 # The standard library TypedDict in Python 3.9.0/1 does not honour the "total"
657 # keyword with old-style TypedDict(). See https://bugs.python.org/issue42059
658 # The standard library TypedDict below Python 3.11 does not store runtime
659 # information about optional and required keys when using Required or NotRequired.
660 # Generic TypedDicts are also impossible using typing.TypedDict on Python <3.11.
661 TypedDict = typing.TypedDict
662 _TypedDictMeta = typing._TypedDictMeta
663 is_typeddict = typing.is_typeddict
665 def _check_fails(cls, other):
667 if sys._getframe(1).f_globals['__name__'] not in ['abc',
670 # Typed dicts are only for static structural subtyping.
671 raise TypeError('TypedDict does not support instance and class checks')
672 except (AttributeError, ValueError):
676 def _dict_new(*args, **kwargs):
678 raise TypeError('TypedDict.__new__(): not enough arguments')
679 _, args = args[0], args[1:] # allow the "cls" keyword be passed
680 return dict(*args, **kwargs)
682 _dict_new.__text_signature__ = '($cls, _typename, _fields=None, /, **kwargs)'
684 def _typeddict_new(*args, total=True, **kwargs):
686 raise TypeError('TypedDict.__new__(): not enough arguments')
687 _, args = args[0], args[1:] # allow the "cls" keyword be passed
689 typename, args = args[0], args[1:] # allow the "_typename" keyword be passed
690 elif '_typename' in kwargs:
691 typename = kwargs.pop('_typename')
693 warnings.warn("Passing '_typename' as keyword argument is deprecated",
694 DeprecationWarning, stacklevel=2)
696 raise TypeError("TypedDict.__new__() missing 1 required positional "
697 "argument: '_typename'")
700 fields, = args # allow the "_fields" keyword be passed
702 raise TypeError('TypedDict.__new__() takes from 2 to 3 '
703 f'positional arguments but {len(args) + 2} '
705 elif '_fields' in kwargs and len(kwargs) == 1:
706 fields = kwargs.pop('_fields')
708 warnings.warn("Passing '_fields' as keyword argument is deprecated",
709 DeprecationWarning, stacklevel=2)
716 raise TypeError("TypedDict takes either a dict or keyword arguments,"
719 ns = {'__annotations__': dict(fields)}
721 # Setting correct module is necessary to make typed dict classes pickleable.
722 ns['__module__'] = sys._getframe(1).f_globals.get('__name__', '__main__')
723 except (AttributeError, ValueError):
726 return _TypedDictMeta(typename, (), ns, total=total)
728 _typeddict_new.__text_signature__ = ('($cls, _typename, _fields=None,'
729 ' /, *, total=True, **kwargs)')
731 class _TypedDictMeta(type):
732 def __init__(cls, name, bases, ns, total=True):
733 super().__init__(name, bases, ns)
735 def __new__(cls, name, bases, ns, total=True):
736 # Create new typed dict class object.
737 # This method is called directly when TypedDict is subclassed,
738 # or via _typeddict_new when TypedDict is instantiated. This way
739 # TypedDict supports all three syntaxes described in its docstring.
740 # Subclasses and instances of TypedDict return actual dictionaries
742 ns['__new__'] = _typeddict_new if name == 'TypedDict' else _dict_new
743 # Don't insert typing.Generic into __bases__ here,
744 # or Generic.__init_subclass__ will raise TypeError
745 # in the super().__new__() call.
746 # Instead, monkey-patch __bases__ onto the class after it's been created.
747 tp_dict = super().__new__(cls, name, (dict,), ns)
749 if any(issubclass(base, typing.Generic) for base in bases):
750 tp_dict.__bases__ = (typing.Generic, dict)
751 _maybe_adjust_parameters(tp_dict)
754 own_annotations = ns.get('__annotations__', {})
755 msg = "TypedDict('Name', {f0: t0, f1: t1, ...}); each t must be a type"
757 n: typing._type_check(tp, msg) for n, tp in own_annotations.items()
759 required_keys = set()
760 optional_keys = set()
763 annotations.update(base.__dict__.get('__annotations__', {}))
764 required_keys.update(base.__dict__.get('__required_keys__', ()))
765 optional_keys.update(base.__dict__.get('__optional_keys__', ()))
767 annotations.update(own_annotations)
768 for annotation_key, annotation_type in own_annotations.items():
769 annotation_origin = get_origin(annotation_type)
770 if annotation_origin is Annotated:
771 annotation_args = get_args(annotation_type)
773 annotation_type = annotation_args[0]
774 annotation_origin = get_origin(annotation_type)
776 if annotation_origin is Required:
777 required_keys.add(annotation_key)
778 elif annotation_origin is NotRequired:
779 optional_keys.add(annotation_key)
781 required_keys.add(annotation_key)
783 optional_keys.add(annotation_key)
785 tp_dict.__annotations__ = annotations
786 tp_dict.__required_keys__ = frozenset(required_keys)
787 tp_dict.__optional_keys__ = frozenset(optional_keys)
788 if not hasattr(tp_dict, '__total__'):
789 tp_dict.__total__ = total
792 __instancecheck__ = __subclasscheck__ = _check_fails
794 TypedDict = _TypedDictMeta('TypedDict', (dict,), {})
795 TypedDict.__module__ = __name__
796 TypedDict.__doc__ = \
797 """A simple typed name space. At runtime it is equivalent to a plain dict.
799 TypedDict creates a dictionary type that expects all of its
800 instances to have a certain set of keys, with each key
801 associated with a value of a consistent type. This expectation
802 is not checked at runtime but is only enforced by type checkers.
805 class Point2D(TypedDict):
810 a: Point2D = {'x': 1, 'y': 2, 'label': 'good'} # OK
811 b: Point2D = {'z': 3, 'label': 'bad'} # Fails type check
813 assert Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first')
815 The type info can be accessed via the Point2D.__annotations__ dict, and
816 the Point2D.__required_keys__ and Point2D.__optional_keys__ frozensets.
817 TypedDict supports two additional equivalent forms::
819 Point2D = TypedDict('Point2D', x=int, y=int, label=str)
820 Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str})
822 The class syntax is only supported in Python 3.6+, while two other
823 syntax forms work for Python 2.7 and 3.2+
826 if hasattr(typing, "_TypedDictMeta"):
827 _TYPEDDICT_TYPES = (typing._TypedDictMeta, _TypedDictMeta)
829 _TYPEDDICT_TYPES = (_TypedDictMeta,)
831 def is_typeddict(tp):
832 """Check if an annotation is a TypedDict class
835 class Film(TypedDict):
839 is_typeddict(Film) # => True
840 is_typeddict(Union[list, str]) # => False
842 return isinstance(tp, tuple(_TYPEDDICT_TYPES))
845 if hasattr(typing, "assert_type"):
846 assert_type = typing.assert_type
849 def assert_type(__val, __typ):
850 """Assert (to the type checker) that the value is of the given type.
852 When the type checker encounters a call to assert_type(), it
853 emits an error if the value is not of the specified type::
855 def greet(name: str) -> None:
856 assert_type(name, str) # ok
857 assert_type(name, int) # type checker error
859 At runtime this returns the first argument unchanged and otherwise
865 if hasattr(typing, "Required"):
866 get_type_hints = typing.get_type_hints
871 # replaces _strip_annotations()
872 def _strip_extras(t):
873 """Strips Annotated, Required and NotRequired from a given type."""
874 if isinstance(t, _AnnotatedAlias):
875 return _strip_extras(t.__origin__)
876 if hasattr(t, "__origin__") and t.__origin__ in (Required, NotRequired):
877 return _strip_extras(t.__args__[0])
878 if isinstance(t, typing._GenericAlias):
879 stripped_args = tuple(_strip_extras(a) for a in t.__args__)
880 if stripped_args == t.__args__:
882 return t.copy_with(stripped_args)
883 if hasattr(types, "GenericAlias") and isinstance(t, types.GenericAlias):
884 stripped_args = tuple(_strip_extras(a) for a in t.__args__)
885 if stripped_args == t.__args__:
887 return types.GenericAlias(t.__origin__, stripped_args)
888 if hasattr(types, "UnionType") and isinstance(t, types.UnionType):
889 stripped_args = tuple(_strip_extras(a) for a in t.__args__)
890 if stripped_args == t.__args__:
892 return functools.reduce(operator.or_, stripped_args)
896 def get_type_hints(obj, globalns=None, localns=None, include_extras=False):
897 """Return type hints for an object.
899 This is often the same as obj.__annotations__, but it handles
900 forward references encoded as string literals, adds Optional[t] if a
901 default value equal to None is set and recursively replaces all
902 'Annotated[T, ...]', 'Required[T]' or 'NotRequired[T]' with 'T'
903 (unless 'include_extras=True').
905 The argument may be a module, class, method, or function. The annotations
906 are returned as a dictionary. For classes, annotations include also
909 TypeError is raised if the argument is not of a type that can contain
910 annotations, and an empty dictionary is returned if no annotations are
913 BEWARE -- the behavior of globalns and localns is counterintuitive
914 (unless you are familiar with how eval() and exec() work). The
915 search order is locals first, then globals.
917 - If no dict arguments are passed, an attempt is made to use the
918 globals from obj (or the respective module's globals for classes),
919 and these are also used as the locals. If the object does not appear
920 to have globals, an empty dictionary is used.
922 - If one dict argument is passed, it is used for both globals and
925 - If two dict arguments are passed, they specify globals and
926 locals, respectively.
928 if hasattr(typing, "Annotated"):
929 hint = typing.get_type_hints(
930 obj, globalns=globalns, localns=localns, include_extras=True
933 hint = typing.get_type_hints(obj, globalns=globalns, localns=localns)
936 return {k: _strip_extras(t) for k, t in hint.items()}
939 # Python 3.9+ has PEP 593 (Annotated)
940 if hasattr(typing, 'Annotated'):
941 Annotated = typing.Annotated
942 # Not exported and not a public API, but needed for get_origin() and get_args()
944 _AnnotatedAlias = typing._AnnotatedAlias
947 class _AnnotatedAlias(typing._GenericAlias, _root=True):
948 """Runtime representation of an annotated type.
950 At its core 'Annotated[t, dec1, dec2, ...]' is an alias for the type 't'
951 with extra annotations. The alias behaves like a normal typing alias,
952 instantiating is the same as instantiating the underlying type, binding
953 it to types is also the same.
955 def __init__(self, origin, metadata):
956 if isinstance(origin, _AnnotatedAlias):
957 metadata = origin.__metadata__ + metadata
958 origin = origin.__origin__
959 super().__init__(origin, origin)
960 self.__metadata__ = metadata
962 def copy_with(self, params):
963 assert len(params) == 1
965 return _AnnotatedAlias(new_type, self.__metadata__)
968 return (f"typing_extensions.Annotated[{typing._type_repr(self.__origin__)}, "
969 f"{', '.join(repr(a) for a in self.__metadata__)}]")
971 def __reduce__(self):
972 return operator.getitem, (
973 Annotated, (self.__origin__,) + self.__metadata__
976 def __eq__(self, other):
977 if not isinstance(other, _AnnotatedAlias):
978 return NotImplemented
979 if self.__origin__ != other.__origin__:
981 return self.__metadata__ == other.__metadata__
984 return hash((self.__origin__, self.__metadata__))
987 """Add context specific metadata to a type.
989 Example: Annotated[int, runtime_check.Unsigned] indicates to the
990 hypothetical runtime_check module that this type is an unsigned int.
991 Every other consumer of this type can ignore this metadata and treat
994 The first argument to Annotated must be a valid type (and will be in
995 the __origin__ field), the remaining arguments are kept as a tuple in
1000 - It's an error to call `Annotated` with less than two arguments.
1001 - Nested Annotated are flattened::
1003 Annotated[Annotated[T, Ann1, Ann2], Ann3] == Annotated[T, Ann1, Ann2, Ann3]
1005 - Instantiating an annotated type is equivalent to instantiating the
1008 Annotated[C, Ann1](5) == C(5)
1010 - Annotated can be used as a generic type alias::
1012 Optimized = Annotated[T, runtime.Optimize()]
1013 Optimized[int] == Annotated[int, runtime.Optimize()]
1015 OptimizedList = Annotated[List[T], runtime.Optimize()]
1016 OptimizedList[int] == Annotated[List[int], runtime.Optimize()]
1021 def __new__(cls, *args, **kwargs):
1022 raise TypeError("Type Annotated cannot be instantiated.")
1025 def __class_getitem__(cls, params):
1026 if not isinstance(params, tuple) or len(params) < 2:
1027 raise TypeError("Annotated[...] should be used "
1028 "with at least two arguments (a type and an "
1030 allowed_special_forms = (ClassVar, Final)
1031 if get_origin(params[0]) in allowed_special_forms:
1034 msg = "Annotated[t, ...]: t must be a type."
1035 origin = typing._type_check(params[0], msg)
1036 metadata = tuple(params[1:])
1037 return _AnnotatedAlias(origin, metadata)
1039 def __init_subclass__(cls, *args, **kwargs):
1041 f"Cannot subclass {cls.__module__}.Annotated"
1044 # Python 3.8 has get_origin() and get_args() but those implementations aren't
1045 # Annotated-aware, so we can't use those. Python 3.9's versions don't support
1046 # ParamSpecArgs and ParamSpecKwargs, so only Python 3.10's versions will do.
1047 if sys.version_info[:2] >= (3, 10):
1048 get_origin = typing.get_origin
1049 get_args = typing.get_args
1054 from typing import _BaseGenericAlias
1056 _BaseGenericAlias = typing._GenericAlias
1059 from typing import GenericAlias as _typing_GenericAlias
1061 _typing_GenericAlias = typing._GenericAlias
1064 """Get the unsubscripted version of a type.
1066 This supports generic types, Callable, Tuple, Union, Literal, Final, ClassVar
1067 and Annotated. Return None for unsupported types. Examples::
1069 get_origin(Literal[42]) is Literal
1070 get_origin(int) is None
1071 get_origin(ClassVar[int]) is ClassVar
1072 get_origin(Generic) is Generic
1073 get_origin(Generic[T]) is Generic
1074 get_origin(Union[T, int]) is Union
1075 get_origin(List[Tuple[T, T]][int]) == list
1076 get_origin(P.args) is P
1078 if isinstance(tp, _AnnotatedAlias):
1080 if isinstance(tp, (typing._GenericAlias, _typing_GenericAlias, _BaseGenericAlias,
1081 ParamSpecArgs, ParamSpecKwargs)):
1082 return tp.__origin__
1083 if tp is typing.Generic:
1084 return typing.Generic
1088 """Get type arguments with all substitutions performed.
1090 For unions, basic simplifications used by Union constructor are performed.
1092 get_args(Dict[str, int]) == (str, int)
1094 get_args(Union[int, Union[T, int], str][int]) == (int, str)
1095 get_args(Union[int, Tuple[T, int]][str]) == (int, Tuple[str, int])
1096 get_args(Callable[[], T][int]) == ([], int)
1098 if isinstance(tp, _AnnotatedAlias):
1099 return (tp.__origin__,) + tp.__metadata__
1100 if isinstance(tp, (typing._GenericAlias, _typing_GenericAlias)):
1101 if getattr(tp, "_special", False):
1104 if get_origin(tp) is collections.abc.Callable and res[0] is not Ellipsis:
1105 res = (list(res[:-1]), res[-1])
1111 if hasattr(typing, 'TypeAlias'):
1112 TypeAlias = typing.TypeAlias
1114 elif sys.version_info[:2] >= (3, 9):
1115 class _TypeAliasForm(typing._SpecialForm, _root=True):
1117 return 'typing_extensions.' + self._name
1120 def TypeAlias(self, parameters):
1121 """Special marker indicating that an assignment should
1122 be recognized as a proper type alias definition by type
1127 Predicate: TypeAlias = Callable[..., bool]
1129 It's invalid when used anywhere except as in the example above.
1131 raise TypeError(f"{self} is not subscriptable")
1134 class _TypeAliasForm(typing._SpecialForm, _root=True):
1136 return 'typing_extensions.' + self._name
1138 TypeAlias = _TypeAliasForm('TypeAlias',
1139 doc="""Special marker indicating that an assignment should
1140 be recognized as a proper type alias definition by type
1145 Predicate: TypeAlias = Callable[..., bool]
1147 It's invalid when used anywhere except as in the example
1151 class _DefaultMixin:
1152 """Mixin for TypeVarLike defaults."""
1156 def __init__(self, default):
1157 if isinstance(default, (tuple, list)):
1158 self.__default__ = tuple((typing._type_check(d, "Default must be a type")
1161 self.__default__ = typing._type_check(default, "Default must be a type")
1163 self.__default__ = None
1166 # Add default and infer_variance parameters from PEP 696 and 695
1167 class TypeVar(typing.TypeVar, _DefaultMixin, _root=True):
1168 """Type variable."""
1170 __module__ = 'typing'
1172 def __init__(self, name, *constraints, bound=None,
1173 covariant=False, contravariant=False,
1174 default=None, infer_variance=False):
1175 super().__init__(name, *constraints, bound=bound, covariant=covariant,
1176 contravariant=contravariant)
1177 _DefaultMixin.__init__(self, default)
1178 self.__infer_variance__ = infer_variance
1182 def_mod = sys._getframe(1).f_globals.get('__name__', '__main__')
1183 except (AttributeError, ValueError):
1185 if def_mod != 'typing_extensions':
1186 self.__module__ = def_mod
1189 # Python 3.10+ has PEP 612
1190 if hasattr(typing, 'ParamSpecArgs'):
1191 ParamSpecArgs = typing.ParamSpecArgs
1192 ParamSpecKwargs = typing.ParamSpecKwargs
1196 """Mixin to indicate that object should not be copied."""
1202 def __deepcopy__(self, memo):
1205 class ParamSpecArgs(_Immutable):
1206 """The args for a ParamSpec object.
1208 Given a ParamSpec object P, P.args is an instance of ParamSpecArgs.
1210 ParamSpecArgs objects have a reference back to their ParamSpec:
1212 P.args.__origin__ is P
1214 This type is meant for runtime introspection and has no special meaning to
1215 static type checkers.
1217 def __init__(self, origin):
1218 self.__origin__ = origin
1221 return f"{self.__origin__.__name__}.args"
1223 def __eq__(self, other):
1224 if not isinstance(other, ParamSpecArgs):
1225 return NotImplemented
1226 return self.__origin__ == other.__origin__
1228 class ParamSpecKwargs(_Immutable):
1229 """The kwargs for a ParamSpec object.
1231 Given a ParamSpec object P, P.kwargs is an instance of ParamSpecKwargs.
1233 ParamSpecKwargs objects have a reference back to their ParamSpec:
1235 P.kwargs.__origin__ is P
1237 This type is meant for runtime introspection and has no special meaning to
1238 static type checkers.
1240 def __init__(self, origin):
1241 self.__origin__ = origin
1244 return f"{self.__origin__.__name__}.kwargs"
1246 def __eq__(self, other):
1247 if not isinstance(other, ParamSpecKwargs):
1248 return NotImplemented
1249 return self.__origin__ == other.__origin__
1252 if hasattr(typing, 'ParamSpec'):
1254 # Add default Parameter - PEP 696
1255 class ParamSpec(typing.ParamSpec, _DefaultMixin, _root=True):
1256 """Parameter specification variable."""
1258 __module__ = 'typing'
1260 def __init__(self, name, *, bound=None, covariant=False, contravariant=False,
1262 super().__init__(name, bound=bound, covariant=covariant,
1263 contravariant=contravariant)
1264 _DefaultMixin.__init__(self, default)
1268 def_mod = sys._getframe(1).f_globals.get('__name__', '__main__')
1269 except (AttributeError, ValueError):
1271 if def_mod != 'typing_extensions':
1272 self.__module__ = def_mod
1277 # Inherits from list as a workaround for Callable checks in Python < 3.9.2.
1278 class ParamSpec(list, _DefaultMixin):
1279 """Parameter specification variable.
1285 Parameter specification variables exist primarily for the benefit of static
1286 type checkers. They are used to forward the parameter types of one
1287 callable to another callable, a pattern commonly found in higher order
1288 functions and decorators. They are only valid when used in ``Concatenate``,
1289 or s the first argument to ``Callable``. In Python 3.10 and higher,
1290 they are also supported in user-defined Generics at runtime.
1291 See class Generic for more information on generic types. An
1292 example for annotating a decorator::
1297 def add_logging(f: Callable[P, T]) -> Callable[P, T]:
1298 '''A type-safe decorator to add logging to a function.'''
1299 def inner(*args: P.args, **kwargs: P.kwargs) -> T:
1300 logging.info(f'{f.__name__} was called')
1301 return f(*args, **kwargs)
1305 def add_two(x: float, y: float) -> float:
1306 '''Add two numbers together.'''
1309 Parameter specification variables defined with covariant=True or
1310 contravariant=True can be used to declare covariant or contravariant
1311 generic types. These keyword arguments are valid, but their actual semantics
1312 are yet to be decided. See PEP 612 for details.
1314 Parameter specification variables can be introspected. e.g.:
1318 P.__covariant__ == False
1319 P.__contravariant__ == False
1321 Note that only parameter specification variables defined in global scope can
1325 # Trick Generic __parameters__.
1326 __class__ = typing.TypeVar
1330 return ParamSpecArgs(self)
1334 return ParamSpecKwargs(self)
1336 def __init__(self, name, *, bound=None, covariant=False, contravariant=False,
1338 super().__init__([self])
1339 self.__name__ = name
1340 self.__covariant__ = bool(covariant)
1341 self.__contravariant__ = bool(contravariant)
1343 self.__bound__ = typing._type_check(bound, 'Bound must be a type.')
1345 self.__bound__ = None
1346 _DefaultMixin.__init__(self, default)
1350 def_mod = sys._getframe(1).f_globals.get('__name__', '__main__')
1351 except (AttributeError, ValueError):
1353 if def_mod != 'typing_extensions':
1354 self.__module__ = def_mod
1357 if self.__covariant__:
1359 elif self.__contravariant__:
1363 return prefix + self.__name__
1366 return object.__hash__(self)
1368 def __eq__(self, other):
1369 return self is other
1371 def __reduce__(self):
1372 return self.__name__
1374 # Hack to get typing._type_check to pass.
1375 def __call__(self, *args, **kwargs):
1380 if not hasattr(typing, 'Concatenate'):
1381 # Inherits from list as a workaround for Callable checks in Python < 3.9.2.
1382 class _ConcatenateGenericAlias(list):
1384 # Trick Generic into looking into this for __parameters__.
1385 __class__ = typing._GenericAlias
1390 def __init__(self, origin, args):
1391 super().__init__(args)
1392 self.__origin__ = origin
1393 self.__args__ = args
1396 _type_repr = typing._type_repr
1397 return (f'{_type_repr(self.__origin__)}'
1398 f'[{", ".join(_type_repr(arg) for arg in self.__args__)}]')
1401 return hash((self.__origin__, self.__args__))
1403 # Hack to get typing._type_check to pass in Generic.
1404 def __call__(self, *args, **kwargs):
1408 def __parameters__(self):
1410 tp for tp in self.__args__ if isinstance(tp, (typing.TypeVar, ParamSpec))
1416 def _concatenate_getitem(self, parameters):
1417 if parameters == ():
1418 raise TypeError("Cannot take a Concatenate of no types.")
1419 if not isinstance(parameters, tuple):
1420 parameters = (parameters,)
1421 if not isinstance(parameters[-1], ParamSpec):
1422 raise TypeError("The last parameter to Concatenate should be a "
1423 "ParamSpec variable.")
1424 msg = "Concatenate[arg, ...]: each arg must be a type."
1425 parameters = tuple(typing._type_check(p, msg) for p in parameters)
1426 return _ConcatenateGenericAlias(self, parameters)
1430 if hasattr(typing, 'Concatenate'):
1431 Concatenate = typing.Concatenate
1432 _ConcatenateGenericAlias = typing._ConcatenateGenericAlias # noqa
1434 elif sys.version_info[:2] >= (3, 9):
1436 def Concatenate(self, parameters):
1437 """Used in conjunction with ``ParamSpec`` and ``Callable`` to represent a
1438 higher order function which adds, removes or transforms parameters of a
1443 Callable[Concatenate[int, P], int]
1445 See PEP 612 for detailed information.
1447 return _concatenate_getitem(self, parameters)
1450 class _ConcatenateForm(typing._SpecialForm, _root=True):
1452 return 'typing_extensions.' + self._name
1454 def __getitem__(self, parameters):
1455 return _concatenate_getitem(self, parameters)
1457 Concatenate = _ConcatenateForm(
1459 doc="""Used in conjunction with ``ParamSpec`` and ``Callable`` to represent a
1460 higher order function which adds, removes or transforms parameters of a
1465 Callable[Concatenate[int, P], int]
1467 See PEP 612 for detailed information.
1471 if hasattr(typing, 'TypeGuard'):
1472 TypeGuard = typing.TypeGuard
1474 elif sys.version_info[:2] >= (3, 9):
1475 class _TypeGuardForm(typing._SpecialForm, _root=True):
1477 return 'typing_extensions.' + self._name
1480 def TypeGuard(self, parameters):
1481 """Special typing form used to annotate the return type of a user-defined
1482 type guard function. ``TypeGuard`` only accepts a single type argument.
1483 At runtime, functions marked this way should return a boolean.
1485 ``TypeGuard`` aims to benefit *type narrowing* -- a technique used by static
1486 type checkers to determine a more precise type of an expression within a
1487 program's code flow. Usually type narrowing is done by analyzing
1488 conditional code flow and applying the narrowing to a block of code. The
1489 conditional expression here is sometimes referred to as a "type guard".
1491 Sometimes it would be convenient to use a user-defined boolean function
1492 as a type guard. Such a function should use ``TypeGuard[...]`` as its
1493 return type to alert static type checkers to this intention.
1495 Using ``-> TypeGuard`` tells the static type checker that for a given
1498 1. The return value is a boolean.
1499 2. If the return value is ``True``, the type of its argument
1500 is the type inside ``TypeGuard``.
1504 def is_str(val: Union[str, float]):
1505 # "isinstance" type guard
1506 if isinstance(val, str):
1507 # Type of ``val`` is narrowed to ``str``
1510 # Else, type of ``val`` is narrowed to ``float``.
1513 Strict type narrowing is not enforced -- ``TypeB`` need not be a narrower
1514 form of ``TypeA`` (it can even be a wider form) and this may lead to
1515 type-unsafe results. The main reason is to allow for things like
1516 narrowing ``List[object]`` to ``List[str]`` even though the latter is not
1517 a subtype of the former, since ``List`` is invariant. The responsibility of
1518 writing type-safe type guards is left to the user.
1520 ``TypeGuard`` also works with type variables. For more information, see
1521 PEP 647 (User-Defined Type Guards).
1523 item = typing._type_check(parameters, f'{self} accepts only a single type.')
1524 return typing._GenericAlias(self, (item,))
1527 class _TypeGuardForm(typing._SpecialForm, _root=True):
1530 return 'typing_extensions.' + self._name
1532 def __getitem__(self, parameters):
1533 item = typing._type_check(parameters,
1534 f'{self._name} accepts only a single type')
1535 return typing._GenericAlias(self, (item,))
1537 TypeGuard = _TypeGuardForm(
1539 doc="""Special typing form used to annotate the return type of a user-defined
1540 type guard function. ``TypeGuard`` only accepts a single type argument.
1541 At runtime, functions marked this way should return a boolean.
1543 ``TypeGuard`` aims to benefit *type narrowing* -- a technique used by static
1544 type checkers to determine a more precise type of an expression within a
1545 program's code flow. Usually type narrowing is done by analyzing
1546 conditional code flow and applying the narrowing to a block of code. The
1547 conditional expression here is sometimes referred to as a "type guard".
1549 Sometimes it would be convenient to use a user-defined boolean function
1550 as a type guard. Such a function should use ``TypeGuard[...]`` as its
1551 return type to alert static type checkers to this intention.
1553 Using ``-> TypeGuard`` tells the static type checker that for a given
1556 1. The return value is a boolean.
1557 2. If the return value is ``True``, the type of its argument
1558 is the type inside ``TypeGuard``.
1562 def is_str(val: Union[str, float]):
1563 # "isinstance" type guard
1564 if isinstance(val, str):
1565 # Type of ``val`` is narrowed to ``str``
1568 # Else, type of ``val`` is narrowed to ``float``.
1571 Strict type narrowing is not enforced -- ``TypeB`` need not be a narrower
1572 form of ``TypeA`` (it can even be a wider form) and this may lead to
1573 type-unsafe results. The main reason is to allow for things like
1574 narrowing ``List[object]`` to ``List[str]`` even though the latter is not
1575 a subtype of the former, since ``List`` is invariant. The responsibility of
1576 writing type-safe type guards is left to the user.
1578 ``TypeGuard`` also works with type variables. For more information, see
1579 PEP 647 (User-Defined Type Guards).
1583 # Vendored from cpython typing._SpecialFrom
1584 class _SpecialForm(typing._Final, _root=True):
1585 __slots__ = ('_name', '__doc__', '_getitem')
1587 def __init__(self, getitem):
1588 self._getitem = getitem
1589 self._name = getitem.__name__
1590 self.__doc__ = getitem.__doc__
1592 def __getattr__(self, item):
1593 if item in {'__name__', '__qualname__'}:
1596 raise AttributeError(item)
1598 def __mro_entries__(self, bases):
1599 raise TypeError(f"Cannot subclass {self!r}")
1602 return f'typing_extensions.{self._name}'
1604 def __reduce__(self):
1607 def __call__(self, *args, **kwds):
1608 raise TypeError(f"Cannot instantiate {self!r}")
1610 def __or__(self, other):
1611 return typing.Union[self, other]
1613 def __ror__(self, other):
1614 return typing.Union[other, self]
1616 def __instancecheck__(self, obj):
1617 raise TypeError(f"{self} cannot be used with isinstance()")
1619 def __subclasscheck__(self, cls):
1620 raise TypeError(f"{self} cannot be used with issubclass()")
1623 def __getitem__(self, parameters):
1624 return self._getitem(self, parameters)
1627 if hasattr(typing, "LiteralString"):
1628 LiteralString = typing.LiteralString
1631 def LiteralString(self, params):
1632 """Represents an arbitrary literal string.
1636 from typing_extensions import LiteralString
1638 def query(sql: LiteralString) -> ...:
1641 query("SELECT * FROM table") # ok
1642 query(f"SELECT * FROM {input()}") # not ok
1644 See PEP 675 for details.
1647 raise TypeError(f"{self} is not subscriptable")
1650 if hasattr(typing, "Self"):
1654 def Self(self, params):
1655 """Used to spell the type of "self" in classes.
1659 from typing import Self
1662 def parse(self, data: bytes) -> Self:
1668 raise TypeError(f"{self} is not subscriptable")
1671 if hasattr(typing, "Never"):
1672 Never = typing.Never
1675 def Never(self, params):
1676 """The bottom type, a type that has no members.
1678 This can be used to define a function that should never be
1679 called, or a function that never returns::
1681 from typing_extensions import Never
1683 def never_call_me(arg: Never) -> None:
1686 def int_or_str(arg: int | str) -> None:
1687 never_call_me(arg) # type checker error
1690 print("It's an int")
1694 never_call_me(arg) # ok, arg is of type Never
1698 raise TypeError(f"{self} is not subscriptable")
1701 if hasattr(typing, 'Required'):
1702 Required = typing.Required
1703 NotRequired = typing.NotRequired
1704 elif sys.version_info[:2] >= (3, 9):
1705 class _ExtensionsSpecialForm(typing._SpecialForm, _root=True):
1707 return 'typing_extensions.' + self._name
1709 @_ExtensionsSpecialForm
1710 def Required(self, parameters):
1711 """A special typing construct to mark a key of a total=False TypedDict
1712 as required. For example:
1714 class Movie(TypedDict, total=False):
1715 title: Required[str]
1719 title='The Matrix', # typechecker error if key is omitted
1723 There is no runtime checking that a required key is actually provided
1724 when instantiating a related TypedDict.
1726 item = typing._type_check(parameters, f'{self._name} accepts only a single type.')
1727 return typing._GenericAlias(self, (item,))
1729 @_ExtensionsSpecialForm
1730 def NotRequired(self, parameters):
1731 """A special typing construct to mark a key of a TypedDict as
1732 potentially missing. For example:
1734 class Movie(TypedDict):
1736 year: NotRequired[int]
1739 title='The Matrix', # typechecker error if key is omitted
1743 item = typing._type_check(parameters, f'{self._name} accepts only a single type.')
1744 return typing._GenericAlias(self, (item,))
1747 class _RequiredForm(typing._SpecialForm, _root=True):
1749 return 'typing_extensions.' + self._name
1751 def __getitem__(self, parameters):
1752 item = typing._type_check(parameters,
1753 f'{self._name} accepts only a single type.')
1754 return typing._GenericAlias(self, (item,))
1756 Required = _RequiredForm(
1758 doc="""A special typing construct to mark a key of a total=False TypedDict
1759 as required. For example:
1761 class Movie(TypedDict, total=False):
1762 title: Required[str]
1766 title='The Matrix', # typechecker error if key is omitted
1770 There is no runtime checking that a required key is actually provided
1771 when instantiating a related TypedDict.
1773 NotRequired = _RequiredForm(
1775 doc="""A special typing construct to mark a key of a TypedDict as
1776 potentially missing. For example:
1778 class Movie(TypedDict):
1780 year: NotRequired[int]
1783 title='The Matrix', # typechecker error if key is omitted
1789 if hasattr(typing, "Unpack"): # 3.11+
1790 Unpack = typing.Unpack
1791 elif sys.version_info[:2] >= (3, 9):
1792 class _UnpackSpecialForm(typing._SpecialForm, _root=True):
1794 return 'typing_extensions.' + self._name
1796 class _UnpackAlias(typing._GenericAlias, _root=True):
1797 __class__ = typing.TypeVar
1800 def Unpack(self, parameters):
1801 """A special typing construct to unpack a variadic type. For example:
1803 Shape = TypeVarTuple('Shape')
1804 Batch = NewType('Batch', int)
1807 x: Array[Unpack[Shape]]
1808 ) -> Array[Batch, Unpack[Shape]]: ...
1811 item = typing._type_check(parameters, f'{self._name} accepts only a single type.')
1812 return _UnpackAlias(self, (item,))
1814 def _is_unpack(obj):
1815 return isinstance(obj, _UnpackAlias)
1818 class _UnpackAlias(typing._GenericAlias, _root=True):
1819 __class__ = typing.TypeVar
1821 class _UnpackForm(typing._SpecialForm, _root=True):
1823 return 'typing_extensions.' + self._name
1825 def __getitem__(self, parameters):
1826 item = typing._type_check(parameters,
1827 f'{self._name} accepts only a single type.')
1828 return _UnpackAlias(self, (item,))
1830 Unpack = _UnpackForm(
1832 doc="""A special typing construct to unpack a variadic type. For example:
1834 Shape = TypeVarTuple('Shape')
1835 Batch = NewType('Batch', int)
1838 x: Array[Unpack[Shape]]
1839 ) -> Array[Batch, Unpack[Shape]]: ...
1843 def _is_unpack(obj):
1844 return isinstance(obj, _UnpackAlias)
1847 if hasattr(typing, "TypeVarTuple"): # 3.11+
1849 # Add default Parameter - PEP 696
1850 class TypeVarTuple(typing.TypeVarTuple, _DefaultMixin, _root=True):
1851 """Type variable tuple."""
1853 def __init__(self, name, *, default=None):
1854 super().__init__(name)
1855 _DefaultMixin.__init__(self, default)
1859 def_mod = sys._getframe(1).f_globals.get('__name__', '__main__')
1860 except (AttributeError, ValueError):
1862 if def_mod != 'typing_extensions':
1863 self.__module__ = def_mod
1866 class TypeVarTuple(_DefaultMixin):
1867 """Type variable tuple.
1871 Ts = TypeVarTuple('Ts')
1873 In the same way that a normal type variable is a stand-in for a single
1874 type such as ``int``, a type variable *tuple* is a stand-in for a *tuple*
1875 type such as ``Tuple[int, str]``.
1877 Type variable tuples can be used in ``Generic`` declarations.
1878 Consider the following example::
1880 class Array(Generic[*Ts]): ...
1882 The ``Ts`` type variable tuple here behaves like ``tuple[T1, T2]``,
1883 where ``T1`` and ``T2`` are type variables. To use these type variables
1884 as type parameters of ``Array``, we must *unpack* the type variable tuple using
1885 the star operator: ``*Ts``. The signature of ``Array`` then behaves
1886 as if we had simply written ``class Array(Generic[T1, T2]): ...``.
1887 In contrast to ``Generic[T1, T2]``, however, ``Generic[*Shape]`` allows
1888 us to parameterise the class with an *arbitrary* number of type parameters.
1890 Type variable tuples can be used anywhere a normal ``TypeVar`` can.
1891 This includes class definitions, as shown above, as well as function
1892 signatures and variable annotations::
1894 class Array(Generic[*Ts]):
1896 def __init__(self, shape: Tuple[*Ts]):
1897 self._shape: Tuple[*Ts] = shape
1899 def get_shape(self) -> Tuple[*Ts]:
1902 shape = (Height(480), Width(640))
1903 x: Array[Height, Width] = Array(shape)
1904 y = abs(x) # Inferred type is Array[Height, Width]
1905 z = x + x # ... is Array[Height, Width]
1906 x.get_shape() # ... is tuple[Height, Width]
1910 # Trick Generic __parameters__.
1911 __class__ = typing.TypeVar
1914 yield self.__unpacked__
1916 def __init__(self, name, *, default=None):
1917 self.__name__ = name
1918 _DefaultMixin.__init__(self, default)
1922 def_mod = sys._getframe(1).f_globals.get('__name__', '__main__')
1923 except (AttributeError, ValueError):
1925 if def_mod != 'typing_extensions':
1926 self.__module__ = def_mod
1928 self.__unpacked__ = Unpack[self]
1931 return self.__name__
1934 return object.__hash__(self)
1936 def __eq__(self, other):
1937 return self is other
1939 def __reduce__(self):
1940 return self.__name__
1942 def __init_subclass__(self, *args, **kwds):
1943 if '_root' not in kwds:
1944 raise TypeError("Cannot subclass special typing classes")
1947 if hasattr(typing, "reveal_type"):
1948 reveal_type = typing.reveal_type
1950 def reveal_type(__obj: T) -> T:
1951 """Reveal the inferred type of a variable.
1953 When a static type checker encounters a call to ``reveal_type()``,
1954 it will emit the inferred type of the argument::
1959 Running a static type checker (e.g., ``mypy``) on this example
1960 will produce output similar to 'Revealed type is "builtins.int"'.
1962 At runtime, the function prints the runtime type of the
1963 argument and returns it unchanged.
1966 print(f"Runtime type is {type(__obj).__name__!r}", file=sys.stderr)
1970 if hasattr(typing, "assert_never"):
1971 assert_never = typing.assert_never
1973 def assert_never(__arg: Never) -> Never:
1974 """Assert to the type checker that a line of code is unreachable.
1978 def int_or_str(arg: int | str) -> None:
1981 print("It's an int")
1987 If a type checker finds that a call to assert_never() is
1988 reachable, it will emit an error.
1990 At runtime, this throws an exception when called.
1993 raise AssertionError("Expected code to be unreachable")
1996 if hasattr(typing, 'dataclass_transform'):
1997 dataclass_transform = typing.dataclass_transform
1999 def dataclass_transform(
2001 eq_default: bool = True,
2002 order_default: bool = False,
2003 kw_only_default: bool = False,
2004 field_specifiers: typing.Tuple[
2005 typing.Union[typing.Type[typing.Any], typing.Callable[..., typing.Any]],
2008 **kwargs: typing.Any,
2009 ) -> typing.Callable[[T], T]:
2010 """Decorator that marks a function, class, or metaclass as providing
2011 dataclass-like behavior.
2015 from typing_extensions import dataclass_transform
2019 # Used on a decorator function
2020 @dataclass_transform()
2021 def create_model(cls: type[_T]) -> type[_T]:
2026 class CustomerModel:
2030 # Used on a base class
2031 @dataclass_transform()
2032 class ModelBase: ...
2034 class CustomerModel(ModelBase):
2038 # Used on a metaclass
2039 @dataclass_transform()
2040 class ModelMeta(type): ...
2042 class ModelBase(metaclass=ModelMeta): ...
2044 class CustomerModel(ModelBase):
2048 Each of the ``CustomerModel`` classes defined in this example will now
2049 behave similarly to a dataclass created with the ``@dataclasses.dataclass``
2050 decorator. For example, the type checker will synthesize an ``__init__``
2053 The arguments to this decorator can be used to customize this behavior:
2054 - ``eq_default`` indicates whether the ``eq`` parameter is assumed to be
2055 True or False if it is omitted by the caller.
2056 - ``order_default`` indicates whether the ``order`` parameter is
2057 assumed to be True or False if it is omitted by the caller.
2058 - ``kw_only_default`` indicates whether the ``kw_only`` parameter is
2059 assumed to be True or False if it is omitted by the caller.
2060 - ``field_specifiers`` specifies a static list of supported classes
2061 or functions that describe fields, similar to ``dataclasses.field()``.
2063 At runtime, this decorator records its arguments in the
2064 ``__dataclass_transform__`` attribute on the decorated object.
2066 See PEP 681 for details.
2069 def decorator(cls_or_fn):
2070 cls_or_fn.__dataclass_transform__ = {
2071 "eq_default": eq_default,
2072 "order_default": order_default,
2073 "kw_only_default": kw_only_default,
2074 "field_specifiers": field_specifiers,
2081 if hasattr(typing, "override"):
2082 override = typing.override
2084 _F = typing.TypeVar("_F", bound=typing.Callable[..., typing.Any])
2086 def override(__arg: _F) -> _F:
2087 """Indicate that a method is intended to override a method in a base class.
2092 def method(self) -> None: ...
2097 def method(self) -> None:
2100 When this decorator is applied to a method, the type checker will
2101 validate that it overrides a method with the same name on a base class.
2102 This helps prevent bugs that may occur when a base class is changed
2103 without an equivalent change to a child class.
2105 See PEP 698 for details.
2111 # We have to do some monkey patching to deal with the dual nature of
2112 # Unpack/TypeVarTuple:
2113 # - We want Unpack to be a kind of TypeVar so it gets accepted in
2114 # Generic[Unpack[Ts]]
2115 # - We want it to *not* be treated as a TypeVar for the purposes of
2116 # counting generic parameters, so that when we subscript a generic,
2117 # the runtime doesn't try to substitute the Unpack with the subscripted type.
2118 if not hasattr(typing, "TypeVarTuple"):
2119 typing._collect_type_vars = _collect_type_vars
2120 typing._check_generic = _check_generic
2123 # Backport typing.NamedTuple as it exists in Python 3.11.
2124 # In 3.11, the ability to define generic `NamedTuple`s was supported.
2125 # This was explicitly disallowed in 3.9-3.10, and only half-worked in <=3.8.
2126 if sys.version_info >= (3, 11):
2127 NamedTuple = typing.NamedTuple
2131 return sys._getframe(2).f_globals.get('__name__', '__main__')
2132 except (AttributeError, ValueError): # For platforms without _getframe()
2135 def _make_nmtuple(name, types, module, defaults=()):
2136 fields = [n for n, t in types]
2137 annotations = {n: typing._type_check(t, f"field {n} annotation must be a type")
2139 nm_tpl = collections.namedtuple(name, fields,
2140 defaults=defaults, module=module)
2141 nm_tpl.__annotations__ = nm_tpl.__new__.__annotations__ = annotations
2142 # The `_field_types` attribute was removed in 3.9;
2143 # in earlier versions, it is the same as the `__annotations__` attribute
2144 if sys.version_info < (3, 9):
2145 nm_tpl._field_types = annotations
2148 _prohibited_namedtuple_fields = typing._prohibited
2149 _special_namedtuple_fields = frozenset({'__module__', '__name__', '__annotations__'})
2151 class _NamedTupleMeta(type):
2152 def __new__(cls, typename, bases, ns):
2153 assert _NamedTuple in bases
2155 if base is not _NamedTuple and base is not typing.Generic:
2157 'can only inherit from a NamedTuple type and Generic')
2158 bases = tuple(tuple if base is _NamedTuple else base for base in bases)
2159 types = ns.get('__annotations__', {})
2161 for field_name in types:
2162 if field_name in ns:
2163 default_names.append(field_name)
2165 raise TypeError(f"Non-default namedtuple field {field_name} "
2166 f"cannot follow default field"
2167 f"{'s' if len(default_names) > 1 else ''} "
2168 f"{', '.join(default_names)}")
2169 nm_tpl = _make_nmtuple(
2170 typename, types.items(),
2171 defaults=[ns[n] for n in default_names],
2172 module=ns['__module__']
2174 nm_tpl.__bases__ = bases
2175 if typing.Generic in bases:
2176 class_getitem = typing.Generic.__class_getitem__.__func__
2177 nm_tpl.__class_getitem__ = classmethod(class_getitem)
2178 # update from user namespace without overriding special namedtuple attributes
2180 if key in _prohibited_namedtuple_fields:
2181 raise AttributeError("Cannot overwrite NamedTuple attribute " + key)
2182 elif key not in _special_namedtuple_fields and key not in nm_tpl._fields:
2183 setattr(nm_tpl, key, ns[key])
2184 if typing.Generic in bases:
2185 nm_tpl.__init_subclass__()
2188 def NamedTuple(__typename, __fields=None, **kwargs):
2189 if __fields is None:
2190 __fields = kwargs.items()
2192 raise TypeError("Either list of fields or keywords"
2193 " can be provided to NamedTuple, not both")
2194 return _make_nmtuple(__typename, __fields, module=_caller())
2196 NamedTuple.__doc__ = typing.NamedTuple.__doc__
2197 _NamedTuple = type.__new__(_NamedTupleMeta, 'NamedTuple', (), {})
2199 # On 3.8+, alter the signature so that it matches typing.NamedTuple.
2200 # The signature of typing.NamedTuple on >=3.8 is invalid syntax in Python 3.7,
2201 # so just leave the signature as it is on 3.7.
2202 if sys.version_info >= (3, 8):
2203 NamedTuple.__text_signature__ = '(typename, fields=None, /, **kwargs)'
2205 def _namedtuple_mro_entries(bases):
2206 assert NamedTuple in bases
2207 return (_NamedTuple,)
2209 NamedTuple.__mro_entries__ = _namedtuple_mro_entries