13 # Super-special typing primitives.
28 # ABCs (from collections.abc).
34 'AsyncContextManager',
38 # Concrete collection types.
47 # Structural checks, a.k.a. protocols.
61 'dataclass_transform',
68 'get_protocol_members',
91 # Pure aliases, have always been in typing
128 'no_type_check_decorator',
131 # for backward compatibility
135 # The functions below are modified copies of typing internal helpers.
136 # They are needed by _ProtocolMeta and they provide support for PEP 646.
144 _marker
= _Sentinel()
147 def _check_generic(cls
, parameters
, elen
=_marker
):
148 """Check correct count for parameters of a generic cls (internal helper).
149 This gives a nice error message in case of count mismatch.
152 raise TypeError(f
"{cls} is not a generic class")
154 if not hasattr(cls
, "__parameters__") or not cls
.__parameters
__:
155 raise TypeError(f
"{cls} is not a generic class")
156 elen
= len(cls
.__parameters
__)
157 alen
= len(parameters
)
159 if hasattr(cls
, "__parameters__"):
160 parameters
= [p
for p
in cls
.__parameters
__ if not _is_unpack(p
)]
161 num_tv_tuples
= sum(isinstance(p
, TypeVarTuple
) for p
in parameters
)
162 if (num_tv_tuples
> 0) and (alen
>= elen
- num_tv_tuples
):
164 raise TypeError(f
"Too {'many' if alen > elen else 'few'} parameters for {cls};"
165 f
" actual {alen}, expected {elen}")
168 if sys
.version_info
>= (3, 10):
169 def _should_collect_from_parameters(t
):
171 t
, (typing
._GenericAlias
, _types
.GenericAlias
, _types
.UnionType
)
173 elif sys
.version_info
>= (3, 9):
174 def _should_collect_from_parameters(t
):
175 return isinstance(t
, (typing
._GenericAlias
, _types
.GenericAlias
))
177 def _should_collect_from_parameters(t
):
178 return isinstance(t
, typing
._GenericAlias
) and not t
._special
181 def _collect_type_vars(types
, typevar_types
=None):
182 """Collect all type variable contained in types in order of
183 first appearance (lexicographic order). For example::
185 _collect_type_vars((T, List[S, T])) == (T, S)
187 if typevar_types
is None:
188 typevar_types
= typing
.TypeVar
192 isinstance(t
, typevar_types
) and
197 if _should_collect_from_parameters(t
):
198 tvars
.extend([t
for t
in t
.__parameters
__ if t
not in tvars
])
202 NoReturn
= typing
.NoReturn
204 # Some unconstrained type variables. These are used by the container types.
205 # (These are not for export.)
206 T
= typing
.TypeVar('T') # Any type.
207 KT
= typing
.TypeVar('KT') # Key type.
208 VT
= typing
.TypeVar('VT') # Value type.
209 T_co
= typing
.TypeVar('T_co', covariant
=True) # Any type covariant containers.
210 T_contra
= typing
.TypeVar('T_contra', contravariant
=True) # Ditto contravariant.
213 if sys
.version_info
>= (3, 11):
214 from typing
import Any
217 class _AnyMeta(type):
218 def __instancecheck__(self
, obj
):
220 raise TypeError("typing_extensions.Any cannot be used with isinstance()")
221 return super().__instancecheck
__(obj
)
225 return "typing_extensions.Any"
226 return super().__repr
__()
228 class Any(metaclass
=_AnyMeta
):
229 """Special type indicating an unconstrained type.
230 - Any is compatible with every type.
231 - Any assumed to have all methods.
232 - All values assumed to be instances of Any.
233 Note that all the above statements are true from the point of view of
234 static type checkers. At runtime, Any should not be used with instance
237 def __new__(cls
, *args
, **kwargs
):
239 raise TypeError("Any cannot be instantiated")
240 return super().__new
__(cls
, *args
, **kwargs
)
243 ClassVar
= typing
.ClassVar
246 class _ExtensionsSpecialForm(typing
._SpecialForm
, _root
=True):
248 return 'typing_extensions.' + self
._name
251 # On older versions of typing there is an internal class named "Final".
253 if hasattr(typing
, 'Final') and sys
.version_info
[:2] >= (3, 7):
257 class _FinalForm(_ExtensionsSpecialForm
, _root
=True):
258 def __getitem__(self
, parameters
):
259 item
= typing
._type
_check
(parameters
,
260 f
'{self._name} accepts only a single type.')
261 return typing
._GenericAlias
(self
, (item
,))
263 Final
= _FinalForm('Final',
264 doc
="""A special typing construct to indicate that a name
265 cannot be re-assigned or overridden in a subclass.
268 MAX_SIZE: Final = 9000
269 MAX_SIZE += 1 # Error reported by type checker
272 TIMEOUT: Final[int] = 10
273 class FastConnector(Connection):
274 TIMEOUT = 1 # Error reported by type checker
276 There is no runtime checking of these properties.""")
278 if sys
.version_info
>= (3, 11):
281 # @final exists in 3.8+, but we backport it for all versions
282 # before 3.11 to keep support for the __final__ attribute.
283 # See https://bugs.python.org/issue46342
285 """This decorator can be used to indicate to type checkers that
286 the decorated method cannot be overridden, and decorated class
287 cannot be subclassed. For example:
291 def done(self) -> None:
294 def done(self) -> None: # Error reported by type checker
299 class Other(Leaf): # Error reported by type checker
302 There is no runtime checking of these properties. The decorator
303 sets the ``__final__`` attribute to ``True`` on the decorated object
304 to allow runtime introspection.
308 except (AttributeError, TypeError):
309 # Skip the attribute silently if it is not writable.
310 # AttributeError happens if the object has __slots__ or a
311 # read-only property, TypeError if it's a builtin class.
317 return typing
.TypeVar(name
)
320 # A Literal bug was fixed in 3.11.0, 3.10.1 and 3.9.8
321 if sys
.version_info
>= (3, 10, 1):
322 Literal
= typing
.Literal
324 def _flatten_literal_params(parameters
):
325 """An internal helper for Literal creation: flatten Literals among parameters"""
328 if isinstance(p
, _LiteralGenericAlias
):
329 params
.extend(p
.__args
__)
334 def _value_and_type_iter(params
):
338 class _LiteralGenericAlias(typing
._GenericAlias
, _root
=True):
339 def __eq__(self
, other
):
340 if not isinstance(other
, _LiteralGenericAlias
):
341 return NotImplemented
342 these_args_deduped
= set(_value_and_type_iter(self
.__args
__))
343 other_args_deduped
= set(_value_and_type_iter(other
.__args
__))
344 return these_args_deduped
== other_args_deduped
347 return hash(frozenset(_value_and_type_iter(self
.__args
__)))
349 class _LiteralForm(_ExtensionsSpecialForm
, _root
=True):
350 def __init__(self
, doc
: str):
351 self
._name
= 'Literal'
352 self
._doc
= self
.__doc
__ = doc
354 def __getitem__(self
, parameters
):
355 if not isinstance(parameters
, tuple):
356 parameters
= (parameters
,)
358 parameters
= _flatten_literal_params(parameters
)
360 val_type_pairs
= list(_value_and_type_iter(parameters
))
362 deduped_pairs
= set(val_type_pairs
)
364 # unhashable parameters
367 # similar logic to typing._deduplicate on Python 3.9+
368 if len(deduped_pairs
) < len(val_type_pairs
):
370 for pair
in val_type_pairs
:
371 if pair
in deduped_pairs
:
372 new_parameters
.append(pair
[0])
373 deduped_pairs
.remove(pair
)
374 assert not deduped_pairs
, deduped_pairs
375 parameters
= tuple(new_parameters
)
377 return _LiteralGenericAlias(self
, parameters
)
379 Literal
= _LiteralForm(doc
="""\
380 A type that can be used to indicate to type checkers
381 that the corresponding value has a value literally equivalent
382 to the provided parameter. For example:
386 The type checker understands that 'var' is literally equal to
387 the value 4 and no other value.
389 Literal[...] cannot be subclassed. There is no runtime
390 checking verifying that the parameter is actually a value
391 instead of a type.""")
394 _overload_dummy
= typing
._overload
_dummy
397 if hasattr(typing
, "get_overloads"): # 3.11+
398 overload
= typing
.overload
399 get_overloads
= typing
.get_overloads
400 clear_overloads
= typing
.clear_overloads
402 # {module: {qualname: {firstlineno: func}}}
403 _overload_registry
= collections
.defaultdict(
404 functools
.partial(collections
.defaultdict
, dict)
408 """Decorator for overloaded functions/methods.
410 In a stub file, place two or more stub definitions for the same
411 function in a row, each decorated with @overload. For example:
414 def utf8(value: None) -> None: ...
416 def utf8(value: bytes) -> bytes: ...
418 def utf8(value: str) -> bytes: ...
420 In a non-stub file (i.e. a regular .py file), do the same but
421 follow it with an implementation. The implementation should *not*
422 be decorated with @overload. For example:
425 def utf8(value: None) -> None: ...
427 def utf8(value: bytes) -> bytes: ...
429 def utf8(value: str) -> bytes: ...
431 # implementation goes here
433 The overloads for a function can be retrieved at runtime using the
434 get_overloads() function.
436 # classmethod and staticmethod
437 f
= getattr(func
, "__func__", func
)
439 _overload_registry
[f
.__module
__][f
.__qualname
__][
440 f
.__code
__.co_firstlineno
442 except AttributeError:
443 # Not a normal function; ignore.
445 return _overload_dummy
447 def get_overloads(func
):
448 """Return all defined overloads for *func* as a sequence."""
449 # classmethod and staticmethod
450 f
= getattr(func
, "__func__", func
)
451 if f
.__module
__ not in _overload_registry
:
453 mod_dict
= _overload_registry
[f
.__module
__]
454 if f
.__qualname
__ not in mod_dict
:
456 return list(mod_dict
[f
.__qualname
__].values())
458 def clear_overloads():
459 """Clear all overloads in the registry."""
460 _overload_registry
.clear()
463 # This is not a real generic class. Don't use outside annotations.
466 # Various ABCs mimicking those in collections.abc.
467 # A few are simply re-exported for completeness.
470 Awaitable
= typing
.Awaitable
471 Coroutine
= typing
.Coroutine
472 AsyncIterable
= typing
.AsyncIterable
473 AsyncIterator
= typing
.AsyncIterator
475 ContextManager
= typing
.ContextManager
476 AsyncContextManager
= typing
.AsyncContextManager
477 DefaultDict
= typing
.DefaultDict
480 if hasattr(typing
, 'OrderedDict'):
481 OrderedDict
= typing
.OrderedDict
484 OrderedDict
= typing
._alias
(collections
.OrderedDict
, (KT
, VT
))
486 Counter
= typing
.Counter
487 ChainMap
= typing
.ChainMap
488 AsyncGenerator
= typing
.AsyncGenerator
490 TYPE_CHECKING
= typing
.TYPE_CHECKING
495 'Callable', 'Awaitable', 'Iterable', 'Iterator', 'AsyncIterable',
496 'Hashable', 'Sized', 'Container', 'Collection', 'Reversible', 'Buffer',
498 'contextlib': ['AbstractContextManager', 'AbstractAsyncContextManager'],
499 'typing_extensions': ['Buffer'],
504 "__abstractmethods__", "__annotations__", "__weakref__", "_is_protocol",
505 "_is_runtime_protocol", "__dict__", "__slots__", "__parameters__",
506 "__orig_bases__", "__module__", "_MutableMapping__marker", "__doc__",
507 "__subclasshook__", "__orig_class__", "__init__", "__new__",
508 "__protocol_attrs__", "__callable_proto_members_only__",
511 if sys
.version_info
< (3, 8):
513 "_gorg", "__next_in_mro__", "__extra__", "__tree_hash__", "__args__",
517 if sys
.version_info
>= (3, 9):
518 _EXCLUDED_ATTRS
.add("__class_getitem__")
520 if sys
.version_info
>= (3, 12):
521 _EXCLUDED_ATTRS
.add("__type_params__")
523 _EXCLUDED_ATTRS
= frozenset(_EXCLUDED_ATTRS
)
526 def _get_protocol_attrs(cls
):
528 for base
in cls
.__mro
__[:-1]: # without object
529 if base
.__name
__ in {'Protocol', 'Generic'}
:
531 annotations
= getattr(base
, '__annotations__', {})
532 for attr
in (*base
.__dict
__, *annotations
):
533 if (not attr
.startswith('_abc_') and attr
not in _EXCLUDED_ATTRS
):
538 def _maybe_adjust_parameters(cls
):
539 """Helper function used in Protocol.__init_subclass__ and _TypedDictMeta.__new__.
541 The contents of this function are very similar
542 to logic found in typing.Generic.__init_subclass__
543 on the CPython main branch.
546 if '__orig_bases__' in cls
.__dict
__:
547 tvars
= _collect_type_vars(cls
.__orig
_bases
__)
548 # Look for Generic[T1, ..., Tn] or Protocol[T1, ..., Tn].
549 # If found, tvars must be a subset of it.
550 # If not found, tvars is it.
551 # Also check for and reject plain Generic,
552 # and reject multiple Generic[...] and/or Protocol[...].
554 for base
in cls
.__orig
_bases
__:
555 if (isinstance(base
, typing
._GenericAlias
) and
556 base
.__origin
__ in (typing
.Generic
, Protocol
)):
558 the_base
= base
.__origin
__.__name
__
559 if gvars
is not None:
561 "Cannot inherit from Generic[...]"
562 " and/or Protocol[...] multiple types.")
563 gvars
= base
.__parameters
__
569 if not tvarset
<= gvarset
:
570 s_vars
= ', '.join(str(t
) for t
in tvars
if t
not in gvarset
)
571 s_args
= ', '.join(str(g
) for g
in gvars
)
572 raise TypeError(f
"Some type variables ({s_vars}) are"
573 f
" not listed in {the_base}[{s_args}]")
575 cls
.__parameters
__ = tuple(tvars
)
578 def _caller(depth
=2):
580 return sys
._getframe
(depth
).f_globals
.get('__name__', '__main__')
581 except (AttributeError, ValueError): # For platforms without _getframe()
585 # The performance of runtime-checkable protocols is significantly improved on Python 3.12,
586 # so we backport the 3.12 version of Protocol to Python <=3.11
587 if sys
.version_info
>= (3, 12):
588 Protocol
= typing
.Protocol
590 def _allow_reckless_class_checks(depth
=3):
591 """Allow instance and class checks for special stdlib modules.
592 The abc and functools modules indiscriminately call isinstance() and
593 issubclass() on the whole MRO of a user class, which may contain protocols.
595 return _caller(depth
) in {'abc', 'functools', None}
597 def _no_init(self
, *args
, **kwargs
):
598 if type(self
)._is
_protocol
:
599 raise TypeError('Protocols cannot be instantiated')
601 if sys
.version_info
>= (3, 8):
602 # Inheriting from typing._ProtocolMeta isn't actually desirable,
603 # but is necessary to allow typing.Protocol and typing_extensions.Protocol
604 # to mix without getting TypeErrors about "metaclass conflict"
605 _typing_Protocol
= typing
.Protocol
606 _ProtocolMetaBase
= type(_typing_Protocol
)
608 _typing_Protocol
= _marker
609 _ProtocolMetaBase
= abc
.ABCMeta
611 class _ProtocolMeta(_ProtocolMetaBase
):
612 # This metaclass is somewhat unfortunate,
613 # but is necessary for several reasons...
615 # NOTE: DO NOT call super() in any methods in this class
616 # That would call the methods on typing._ProtocolMeta on Python 3.8-3.11
618 def __new__(mcls
, name
, bases
, namespace
, **kwargs
):
619 if name
== "Protocol" and len(bases
) < 2:
621 elif {Protocol, _typing_Protocol}
& set(bases
):
624 base
in {object, typing.Generic, Protocol, _typing_Protocol}
625 or base
.__name
__ in _PROTO_ALLOWLIST
.get(base
.__module
__, [])
629 f
"Protocols can only inherit from other protocols, "
632 return abc
.ABCMeta
.__new
__(mcls
, name
, bases
, namespace
, **kwargs
)
634 def __init__(cls
, *args
, **kwargs
):
635 abc
.ABCMeta
.__init
__(cls
, *args
, **kwargs
)
636 if getattr(cls
, "_is_protocol", False):
637 cls
.__protocol
_attrs
__ = _get_protocol_attrs(cls
)
638 # PEP 544 prohibits using issubclass()
639 # with protocols that have non-method members.
640 cls
.__callable
_proto
_members
_only
__ = all(
641 callable(getattr(cls
, attr
, None)) for attr
in cls
.__protocol
_attrs
__
644 def __subclasscheck__(cls
, other
):
646 return type.__subclasscheck
__(cls
, other
)
648 getattr(cls
, '_is_protocol', False)
649 and not _allow_reckless_class_checks()
651 if not isinstance(other
, type):
652 # Same error message as for issubclass(1, int).
653 raise TypeError('issubclass() arg 1 must be a class')
655 not cls
.__callable
_proto
_members
_only
__
656 and cls
.__dict
__.get("__subclasshook__") is _proto_hook
659 "Protocols with non-method members don't support issubclass()"
661 if not getattr(cls
, '_is_runtime_protocol', False):
663 "Instance and class checks can only be used with "
664 "@runtime_checkable protocols"
666 return abc
.ABCMeta
.__subclasscheck
__(cls
, other
)
668 def __instancecheck__(cls
, instance
):
669 # We need this method for situations where attributes are
670 # assigned in __init__.
672 return type.__instancecheck
__(cls
, instance
)
673 if not getattr(cls
, "_is_protocol", False):
674 # i.e., it's a concrete subclass of a protocol
675 return abc
.ABCMeta
.__instancecheck
__(cls
, instance
)
678 not getattr(cls
, '_is_runtime_protocol', False) and
679 not _allow_reckless_class_checks()
681 raise TypeError("Instance and class checks can only be used with"
682 " @runtime_checkable protocols")
684 if abc
.ABCMeta
.__instancecheck
__(cls
, instance
):
687 for attr
in cls
.__protocol
_attrs
__:
689 val
= inspect
.getattr_static(instance
, attr
)
690 except AttributeError:
692 if val
is None and callable(getattr(cls
, attr
, None)):
699 def __eq__(cls
, other
):
700 # Hack so that typing.Generic.__class_getitem__
701 # treats typing_extensions.Protocol
702 # as equivalent to typing.Protocol on Python 3.8+
703 if abc
.ABCMeta
.__eq
__(cls
, other
) is True:
706 cls
is Protocol
and other
is getattr(typing
, "Protocol", object())
709 # This has to be defined, or the abc-module cache
710 # complains about classes with this metaclass being unhashable,
711 # if we define only __eq__!
712 def __hash__(cls
) -> int:
713 return type.__hash
__(cls
)
716 def _proto_hook(cls
, other
):
717 if not cls
.__dict
__.get('_is_protocol', False):
718 return NotImplemented
720 for attr
in cls
.__protocol
_attrs
__:
721 for base
in other
.__mro
__:
722 # Check if the members appears in the class dictionary...
723 if attr
in base
.__dict
__:
724 if base
.__dict
__[attr
] is None:
725 return NotImplemented
728 # ...or in annotations, if it is a sub-protocol.
729 annotations
= getattr(base
, '__annotations__', {})
731 isinstance(annotations
, collections
.abc
.Mapping
)
732 and attr
in annotations
733 and is_protocol(other
)
737 return NotImplemented
740 if sys
.version_info
>= (3, 8):
741 class Protocol(typing
.Generic
, metaclass
=_ProtocolMeta
):
742 __doc__
= typing
.Protocol
.__doc
__
745 _is_runtime_protocol
= False
747 def __init_subclass__(cls
, *args
, **kwargs
):
748 super().__init
_subclass
__(*args
, **kwargs
)
750 # Determine if this is a protocol or a concrete subclass.
751 if not cls
.__dict
__.get('_is_protocol', False):
752 cls
._is
_protocol
= any(b
is Protocol
for b
in cls
.__bases
__)
754 # Set (or override) the protocol subclass hook.
755 if '__subclasshook__' not in cls
.__dict
__:
756 cls
.__subclasshook
__ = _proto_hook
758 # Prohibit instantiation for protocol classes
759 if cls
._is
_protocol
and cls
.__init
__ is Protocol
.__init
__:
760 cls
.__init
__ = _no_init
763 class Protocol(metaclass
=_ProtocolMeta
):
764 # There is quite a lot of overlapping code with typing.Generic.
765 # Unfortunately it is hard to avoid this on Python <3.8,
766 # as the typing module on Python 3.7 doesn't let us subclass typing.Generic!
767 """Base class for protocol classes. Protocol classes are defined as::
769 class Proto(Protocol):
770 def meth(self) -> int:
773 Such classes are primarily used with static type checkers that recognize
774 structural subtyping (static duck-typing), for example::
777 def meth(self) -> int:
780 def func(x: Proto) -> int:
783 func(C()) # Passes static type check
785 See PEP 544 for details. Protocol classes decorated with
786 @typing_extensions.runtime_checkable act
787 as simple-minded runtime-checkable protocols that check
788 only the presence of given attributes, ignoring their type signatures.
790 Protocol classes can be generic, they are defined as::
792 class GenProto(Protocol[T]):
798 _is_runtime_protocol
= False
800 def __new__(cls
, *args
, **kwds
):
802 raise TypeError("Type Protocol cannot be instantiated; "
803 "it can only be used as a base class")
804 return super().__new
__(cls
)
807 def __class_getitem__(cls
, params
):
808 if not isinstance(params
, tuple):
810 if not params
and cls
is not typing
.Tuple
:
812 f
"Parameter list to {cls.__qualname__}[...] cannot be empty")
813 msg
= "Parameters to generic types must be types."
814 params
= tuple(typing
._type
_check
(p
, msg
) for p
in params
)
816 # Generic can only be subscripted with unique type variables.
817 if not all(isinstance(p
, typing
.TypeVar
) for p
in params
):
819 while isinstance(params
[i
], typing
.TypeVar
):
822 "Parameters to Protocol[...] must all be type variables."
823 f
" Parameter {i + 1} is {params[i]}")
824 if len(set(params
)) != len(params
):
826 "Parameters to Protocol[...] must all be unique")
828 # Subscripting a regular Generic subclass.
829 _check_generic(cls
, params
, len(cls
.__parameters
__))
830 return typing
._GenericAlias
(cls
, params
)
832 def __init_subclass__(cls
, *args
, **kwargs
):
833 if '__orig_bases__' in cls
.__dict
__:
834 error
= typing
.Generic
in cls
.__orig
_bases
__
836 error
= typing
.Generic
in cls
.__bases
__
838 raise TypeError("Cannot inherit from plain Generic")
839 _maybe_adjust_parameters(cls
)
841 # Determine if this is a protocol or a concrete subclass.
842 if not cls
.__dict
__.get('_is_protocol', None):
843 cls
._is
_protocol
= any(b
is Protocol
for b
in cls
.__bases
__)
845 # Set (or override) the protocol subclass hook.
846 if '__subclasshook__' not in cls
.__dict
__:
847 cls
.__subclasshook
__ = _proto_hook
849 # Prohibit instantiation for protocol classes
850 if cls
._is
_protocol
and cls
.__init
__ is Protocol
.__init
__:
851 cls
.__init
__ = _no_init
854 if sys
.version_info
>= (3, 8):
855 runtime_checkable
= typing
.runtime_checkable
857 def runtime_checkable(cls
):
858 """Mark a protocol class as a runtime protocol, so that it
859 can be used with isinstance() and issubclass(). Raise TypeError
860 if applied to a non-protocol class.
862 This allows a simple-minded structural check very similar to the
863 one-offs in collections.abc such as Hashable.
866 (isinstance(cls
, _ProtocolMeta
) or issubclass(cls
, typing
.Generic
))
867 and getattr(cls
, "_is_protocol", False)
869 raise TypeError('@runtime_checkable can be only applied to protocol classes,'
871 cls
._is
_runtime
_protocol
= True
875 # Exists for backwards compatibility.
876 runtime
= runtime_checkable
879 # Our version of runtime-checkable protocols is faster on Python 3.7-3.11
880 if sys
.version_info
>= (3, 12):
881 SupportsInt
= typing
.SupportsInt
882 SupportsFloat
= typing
.SupportsFloat
883 SupportsComplex
= typing
.SupportsComplex
884 SupportsBytes
= typing
.SupportsBytes
885 SupportsIndex
= typing
.SupportsIndex
886 SupportsAbs
= typing
.SupportsAbs
887 SupportsRound
= typing
.SupportsRound
890 class SupportsInt(Protocol
):
891 """An ABC with one abstract method __int__."""
895 def __int__(self
) -> int:
899 class SupportsFloat(Protocol
):
900 """An ABC with one abstract method __float__."""
904 def __float__(self
) -> float:
908 class SupportsComplex(Protocol
):
909 """An ABC with one abstract method __complex__."""
913 def __complex__(self
) -> complex:
917 class SupportsBytes(Protocol
):
918 """An ABC with one abstract method __bytes__."""
922 def __bytes__(self
) -> bytes:
926 class SupportsIndex(Protocol
):
930 def __index__(self
) -> int:
934 class SupportsAbs(Protocol
[T_co
]):
936 An ABC with one abstract method __abs__ that is covariant in its return type.
941 def __abs__(self
) -> T_co
:
945 class SupportsRound(Protocol
[T_co
]):
947 An ABC with one abstract method __round__ that is covariant in its return type.
952 def __round__(self
, ndigits
: int = 0) -> T_co
:
956 def _ensure_subclassable(mro_entries
):
958 if sys
.implementation
.name
== "pypy" and sys
.version_info
< (3, 9):
960 "__call__": staticmethod(func
),
961 "__mro_entries__": staticmethod(mro_entries
)
963 t
= type(func
.__name
__, (), cls_dict
)
964 return functools
.update_wrapper(t(), func
)
966 func
.__mro
_entries
__ = mro_entries
971 if sys
.version_info
>= (3, 13):
972 # The standard library TypedDict in Python 3.8 does not store runtime information
973 # about which (if any) keys are optional. See https://bugs.python.org/issue38834
974 # The standard library TypedDict in Python 3.9.0/1 does not honour the "total"
975 # keyword with old-style TypedDict(). See https://bugs.python.org/issue42059
976 # The standard library TypedDict below Python 3.11 does not store runtime
977 # information about optional and required keys when using Required or NotRequired.
978 # Generic TypedDicts are also impossible using typing.TypedDict on Python <3.11.
979 # Aaaand on 3.12 we add __orig_bases__ to TypedDict
980 # to enable better runtime introspection.
981 # On 3.13 we deprecate some odd ways of creating TypedDicts.
982 TypedDict
= typing
.TypedDict
983 _TypedDictMeta
= typing
._TypedDictMeta
984 is_typeddict
= typing
.is_typeddict
987 _TAKES_MODULE
= "module" in inspect
.signature(typing
._type
_check
).parameters
989 if sys
.version_info
>= (3, 8):
990 _fake_name
= "Protocol"
992 _fake_name
= "_Protocol"
994 class _TypedDictMeta(type):
995 def __new__(cls
, name
, bases
, ns
, total
=True):
996 """Create new typed dict class object.
998 This method is called when TypedDict is subclassed,
999 or when TypedDict is instantiated. This way
1000 TypedDict supports all three syntax forms described in its docstring.
1001 Subclasses and instances of TypedDict return actual dictionaries.
1004 if type(base
) is not _TypedDictMeta
and base
is not typing
.Generic
:
1005 raise TypeError('cannot inherit from both a TypedDict type '
1006 'and a non-TypedDict base class')
1008 if any(issubclass(b
, typing
.Generic
) for b
in bases
):
1009 generic_base
= (typing
.Generic
,)
1013 # typing.py generally doesn't let you inherit from plain Generic, unless
1014 # the name of the class happens to be "Protocol" (or "_Protocol" on 3.7).
1015 tp_dict
= type.__new
__(_TypedDictMeta
, _fake_name
, (*generic_base
, dict), ns
)
1016 tp_dict
.__name
__ = name
1017 if tp_dict
.__qualname
__ == _fake_name
:
1018 tp_dict
.__qualname
__ = name
1020 if not hasattr(tp_dict
, '__orig_bases__'):
1021 tp_dict
.__orig
_bases
__ = bases
1024 own_annotations
= ns
.get('__annotations__', {})
1025 msg
= "TypedDict('Name', {f0: t0, f1: t1, ...}); each t must be a type"
1028 n
: typing
._type
_check
(tp
, msg
, module
=tp_dict
.__module
__)
1029 for n
, tp
in own_annotations
.items()
1033 n
: typing
._type
_check
(tp
, msg
)
1034 for n
, tp
in own_annotations
.items()
1036 required_keys
= set()
1037 optional_keys
= set()
1040 annotations
.update(base
.__dict
__.get('__annotations__', {}))
1041 required_keys
.update(base
.__dict
__.get('__required_keys__', ()))
1042 optional_keys
.update(base
.__dict
__.get('__optional_keys__', ()))
1044 annotations
.update(own_annotations
)
1045 for annotation_key
, annotation_type
in own_annotations
.items():
1046 annotation_origin
= get_origin(annotation_type
)
1047 if annotation_origin
is Annotated
:
1048 annotation_args
= get_args(annotation_type
)
1050 annotation_type
= annotation_args
[0]
1051 annotation_origin
= get_origin(annotation_type
)
1053 if annotation_origin
is Required
:
1054 required_keys
.add(annotation_key
)
1055 elif annotation_origin
is NotRequired
:
1056 optional_keys
.add(annotation_key
)
1058 required_keys
.add(annotation_key
)
1060 optional_keys
.add(annotation_key
)
1062 tp_dict
.__annotations
__ = annotations
1063 tp_dict
.__required
_keys
__ = frozenset(required_keys
)
1064 tp_dict
.__optional
_keys
__ = frozenset(optional_keys
)
1065 if not hasattr(tp_dict
, '__total__'):
1066 tp_dict
.__total
__ = total
1069 __call__
= dict # static method
1071 def __subclasscheck__(cls
, other
):
1072 # Typed dicts are only for static structural subtyping.
1073 raise TypeError('TypedDict does not support instance and class checks')
1075 __instancecheck__
= __subclasscheck__
1077 _TypedDict
= type.__new
__(_TypedDictMeta
, 'TypedDict', (), {})
1079 @_ensure_subclassable(lambda bases
: (_TypedDict
,))
1080 def TypedDict(__typename
, __fields
=_marker
, *, total
=True, **kwargs
):
1081 """A simple typed namespace. At runtime it is equivalent to a plain dict.
1083 TypedDict creates a dictionary type such that a type checker will expect all
1084 instances to have a certain set of keys, where each key is
1085 associated with a value of a consistent type. This expectation
1086 is not checked at runtime.
1090 class Point2D(TypedDict):
1095 a: Point2D = {'x': 1, 'y': 2, 'label': 'good'} # OK
1096 b: Point2D = {'z': 3, 'label': 'bad'} # Fails type check
1098 assert Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first')
1100 The type info can be accessed via the Point2D.__annotations__ dict, and
1101 the Point2D.__required_keys__ and Point2D.__optional_keys__ frozensets.
1102 TypedDict supports an additional equivalent form::
1104 Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str})
1106 By default, all keys must be present in a TypedDict. It is possible
1107 to override this by specifying totality::
1109 class Point2D(TypedDict, total=False):
1113 This means that a Point2D TypedDict can have any of the keys omitted. A type
1114 checker is only expected to support a literal False or True as the value of
1115 the total argument. True is the default, and makes all items defined in the
1116 class body be required.
1118 The Required and NotRequired special forms can also be used to mark
1119 individual keys as being required or not required::
1121 class Point2D(TypedDict):
1122 x: int # the "x" key must always be present (Required is the default)
1123 y: NotRequired[int] # the "y" key can be omitted
1125 See PEP 655 for more details on Required and NotRequired.
1127 if __fields
is _marker
or __fields
is None:
1128 if __fields
is _marker
:
1129 deprecated_thing
= "Failing to pass a value for the 'fields' parameter"
1131 deprecated_thing
= "Passing `None` as the 'fields' parameter"
1133 example
= f
"`{__typename} = TypedDict({__typename!r}, {{}})`"
1135 f
"{deprecated_thing} is deprecated and will be disallowed in "
1136 "Python 3.15. To create a TypedDict class with 0 fields "
1137 "using the functional syntax, pass an empty dictionary, e.g. "
1139 warnings
.warn(deprecation_msg
, DeprecationWarning, stacklevel
=2)
1142 raise TypeError("TypedDict takes either a dict or keyword arguments,"
1146 "The kwargs-based syntax for TypedDict definitions is deprecated "
1147 "in Python 3.11, will be removed in Python 3.13, and may not be "
1148 "understood by third-party type checkers.",
1153 ns
= {'__annotations__': dict(__fields)}
1155 if module
is not None:
1156 # Setting correct module is necessary to make typed dict classes pickleable.
1157 ns
['__module__'] = module
1159 td
= _TypedDictMeta(__typename
, (), ns
, total
=total
)
1160 td
.__orig
_bases
__ = (TypedDict
,)
1163 if hasattr(typing
, "_TypedDictMeta"):
1164 _TYPEDDICT_TYPES
= (typing
._TypedDictMeta
, _TypedDictMeta
)
1166 _TYPEDDICT_TYPES
= (_TypedDictMeta
,)
1168 def is_typeddict(tp
):
1169 """Check if an annotation is a TypedDict class
1172 class Film(TypedDict):
1176 is_typeddict(Film) # => True
1177 is_typeddict(Union[list, str]) # => False
1179 # On 3.8, this would otherwise return True
1180 if hasattr(typing
, "TypedDict") and tp
is typing
.TypedDict
:
1182 return isinstance(tp
, _TYPEDDICT_TYPES
)
1185 if hasattr(typing
, "assert_type"):
1186 assert_type
= typing
.assert_type
1189 def assert_type(__val
, __typ
):
1190 """Assert (to the type checker) that the value is of the given type.
1192 When the type checker encounters a call to assert_type(), it
1193 emits an error if the value is not of the specified type::
1195 def greet(name: str) -> None:
1196 assert_type(name, str) # ok
1197 assert_type(name, int) # type checker error
1199 At runtime this returns the first argument unchanged and otherwise
1205 if hasattr(typing
, "Required"):
1206 get_type_hints
= typing
.get_type_hints
1208 # replaces _strip_annotations()
1209 def _strip_extras(t
):
1210 """Strips Annotated, Required and NotRequired from a given type."""
1211 if isinstance(t
, _AnnotatedAlias
):
1212 return _strip_extras(t
.__origin
__)
1213 if hasattr(t
, "__origin__") and t
.__origin
__ in (Required
, NotRequired
):
1214 return _strip_extras(t
.__args
__[0])
1215 if isinstance(t
, typing
._GenericAlias
):
1216 stripped_args
= tuple(_strip_extras(a
) for a
in t
.__args
__)
1217 if stripped_args
== t
.__args
__:
1219 return t
.copy_with(stripped_args
)
1220 if hasattr(_types
, "GenericAlias") and isinstance(t
, _types
.GenericAlias
):
1221 stripped_args
= tuple(_strip_extras(a
) for a
in t
.__args
__)
1222 if stripped_args
== t
.__args
__:
1224 return _types
.GenericAlias(t
.__origin
__, stripped_args
)
1225 if hasattr(_types
, "UnionType") and isinstance(t
, _types
.UnionType
):
1226 stripped_args
= tuple(_strip_extras(a
) for a
in t
.__args
__)
1227 if stripped_args
== t
.__args
__:
1229 return functools
.reduce(operator
.or_
, stripped_args
)
1233 def get_type_hints(obj
, globalns
=None, localns
=None, include_extras
=False):
1234 """Return type hints for an object.
1236 This is often the same as obj.__annotations__, but it handles
1237 forward references encoded as string literals, adds Optional[t] if a
1238 default value equal to None is set and recursively replaces all
1239 'Annotated[T, ...]', 'Required[T]' or 'NotRequired[T]' with 'T'
1240 (unless 'include_extras=True').
1242 The argument may be a module, class, method, or function. The annotations
1243 are returned as a dictionary. For classes, annotations include also
1246 TypeError is raised if the argument is not of a type that can contain
1247 annotations, and an empty dictionary is returned if no annotations are
1250 BEWARE -- the behavior of globalns and localns is counterintuitive
1251 (unless you are familiar with how eval() and exec() work). The
1252 search order is locals first, then globals.
1254 - If no dict arguments are passed, an attempt is made to use the
1255 globals from obj (or the respective module's globals for classes),
1256 and these are also used as the locals. If the object does not appear
1257 to have globals, an empty dictionary is used.
1259 - If one dict argument is passed, it is used for both globals and
1262 - If two dict arguments are passed, they specify globals and
1263 locals, respectively.
1265 if hasattr(typing
, "Annotated"):
1266 hint
= typing
.get_type_hints(
1267 obj
, globalns
=globalns
, localns
=localns
, include_extras
=True
1270 hint
= typing
.get_type_hints(obj
, globalns
=globalns
, localns
=localns
)
1273 return {k: _strip_extras(t) for k, t in hint.items()}
1276 # Python 3.9+ has PEP 593 (Annotated)
1277 if hasattr(typing
, 'Annotated'):
1278 Annotated
= typing
.Annotated
1279 # Not exported and not a public API, but needed for get_origin() and get_args()
1281 _AnnotatedAlias
= typing
._AnnotatedAlias
1284 class _AnnotatedAlias(typing
._GenericAlias
, _root
=True):
1285 """Runtime representation of an annotated type.
1287 At its core 'Annotated[t, dec1, dec2, ...]' is an alias for the type 't'
1288 with extra annotations. The alias behaves like a normal typing alias,
1289 instantiating is the same as instantiating the underlying type, binding
1290 it to types is also the same.
1292 def __init__(self
, origin
, metadata
):
1293 if isinstance(origin
, _AnnotatedAlias
):
1294 metadata
= origin
.__metadata
__ + metadata
1295 origin
= origin
.__origin
__
1296 super().__init
__(origin
, origin
)
1297 self
.__metadata
__ = metadata
1299 def copy_with(self
, params
):
1300 assert len(params
) == 1
1301 new_type
= params
[0]
1302 return _AnnotatedAlias(new_type
, self
.__metadata
__)
1305 return (f
"typing_extensions.Annotated[{typing._type_repr(self.__origin__)}, "
1306 f
"{', '.join(repr(a) for a in self.__metadata__)}]")
1308 def __reduce__(self
):
1309 return operator
.getitem
, (
1310 Annotated
, (self
.__origin
__,) + self
.__metadata
__
1313 def __eq__(self
, other
):
1314 if not isinstance(other
, _AnnotatedAlias
):
1315 return NotImplemented
1316 if self
.__origin
__ != other
.__origin
__:
1318 return self
.__metadata
__ == other
.__metadata
__
1321 return hash((self
.__origin
__, self
.__metadata
__))
1324 """Add context specific metadata to a type.
1326 Example: Annotated[int, runtime_check.Unsigned] indicates to the
1327 hypothetical runtime_check module that this type is an unsigned int.
1328 Every other consumer of this type can ignore this metadata and treat
1331 The first argument to Annotated must be a valid type (and will be in
1332 the __origin__ field), the remaining arguments are kept as a tuple in
1333 the __extra__ field.
1337 - It's an error to call `Annotated` with less than two arguments.
1338 - Nested Annotated are flattened::
1340 Annotated[Annotated[T, Ann1, Ann2], Ann3] == Annotated[T, Ann1, Ann2, Ann3]
1342 - Instantiating an annotated type is equivalent to instantiating the
1345 Annotated[C, Ann1](5) == C(5)
1347 - Annotated can be used as a generic type alias::
1349 Optimized = Annotated[T, runtime.Optimize()]
1350 Optimized[int] == Annotated[int, runtime.Optimize()]
1352 OptimizedList = Annotated[List[T], runtime.Optimize()]
1353 OptimizedList[int] == Annotated[List[int], runtime.Optimize()]
1358 def __new__(cls
, *args
, **kwargs
):
1359 raise TypeError("Type Annotated cannot be instantiated.")
1362 def __class_getitem__(cls
, params
):
1363 if not isinstance(params
, tuple) or len(params
) < 2:
1364 raise TypeError("Annotated[...] should be used "
1365 "with at least two arguments (a type and an "
1367 allowed_special_forms
= (ClassVar
, Final
)
1368 if get_origin(params
[0]) in allowed_special_forms
:
1371 msg
= "Annotated[t, ...]: t must be a type."
1372 origin
= typing
._type
_check
(params
[0], msg
)
1373 metadata
= tuple(params
[1:])
1374 return _AnnotatedAlias(origin
, metadata
)
1376 def __init_subclass__(cls
, *args
, **kwargs
):
1378 f
"Cannot subclass {cls.__module__}.Annotated"
1381 # Python 3.8 has get_origin() and get_args() but those implementations aren't
1382 # Annotated-aware, so we can't use those. Python 3.9's versions don't support
1383 # ParamSpecArgs and ParamSpecKwargs, so only Python 3.10's versions will do.
1384 if sys
.version_info
[:2] >= (3, 10):
1385 get_origin
= typing
.get_origin
1386 get_args
= typing
.get_args
1391 from typing
import _BaseGenericAlias
1393 _BaseGenericAlias
= typing
._GenericAlias
1396 from typing
import GenericAlias
as _typing_GenericAlias
1398 _typing_GenericAlias
= typing
._GenericAlias
1401 """Get the unsubscripted version of a type.
1403 This supports generic types, Callable, Tuple, Union, Literal, Final, ClassVar
1404 and Annotated. Return None for unsupported types. Examples::
1406 get_origin(Literal[42]) is Literal
1407 get_origin(int) is None
1408 get_origin(ClassVar[int]) is ClassVar
1409 get_origin(Generic) is Generic
1410 get_origin(Generic[T]) is Generic
1411 get_origin(Union[T, int]) is Union
1412 get_origin(List[Tuple[T, T]][int]) == list
1413 get_origin(P.args) is P
1415 if isinstance(tp
, _AnnotatedAlias
):
1417 if isinstance(tp
, (typing
._GenericAlias
, _typing_GenericAlias
, _BaseGenericAlias
,
1418 ParamSpecArgs
, ParamSpecKwargs
)):
1419 return tp
.__origin
__
1420 if tp
is typing
.Generic
:
1421 return typing
.Generic
1425 """Get type arguments with all substitutions performed.
1427 For unions, basic simplifications used by Union constructor are performed.
1429 get_args(Dict[str, int]) == (str, int)
1431 get_args(Union[int, Union[T, int], str][int]) == (int, str)
1432 get_args(Union[int, Tuple[T, int]][str]) == (int, Tuple[str, int])
1433 get_args(Callable[[], T][int]) == ([], int)
1435 if isinstance(tp
, _AnnotatedAlias
):
1436 return (tp
.__origin
__,) + tp
.__metadata
__
1437 if isinstance(tp
, (typing
._GenericAlias
, _typing_GenericAlias
)):
1438 if getattr(tp
, "_special", False):
1441 if get_origin(tp
) is collections
.abc
.Callable
and res
[0] is not Ellipsis:
1442 res
= (list(res
[:-1]), res
[-1])
1448 if hasattr(typing
, 'TypeAlias'):
1449 TypeAlias
= typing
.TypeAlias
1451 elif sys
.version_info
[:2] >= (3, 9):
1452 @_ExtensionsSpecialForm
1453 def TypeAlias(self
, parameters
):
1454 """Special marker indicating that an assignment should
1455 be recognized as a proper type alias definition by type
1460 Predicate: TypeAlias = Callable[..., bool]
1462 It's invalid when used anywhere except as in the example above.
1464 raise TypeError(f
"{self} is not subscriptable")
1467 TypeAlias
= _ExtensionsSpecialForm(
1469 doc
="""Special marker indicating that an assignment should
1470 be recognized as a proper type alias definition by type
1475 Predicate: TypeAlias = Callable[..., bool]
1477 It's invalid when used anywhere except as in the example
1482 def _set_default(type_param
, default
):
1483 if isinstance(default
, (tuple, list)):
1484 type_param
.__default
__ = tuple((typing
._type
_check
(d
, "Default must be a type")
1486 elif default
!= _marker
:
1487 type_param
.__default
__ = typing
._type
_check
(default
, "Default must be a type")
1489 type_param
.__default
__ = None
1492 def _set_module(typevarlike
):
1494 def_mod
= _caller(depth
=3)
1495 if def_mod
!= 'typing_extensions':
1496 typevarlike
.__module
__ = def_mod
1499 class _DefaultMixin
:
1500 """Mixin for TypeVarLike defaults."""
1503 __init__
= _set_default
1506 # Classes using this metaclass must provide a _backported_typevarlike ClassVar
1507 class _TypeVarLikeMeta(type):
1508 def __instancecheck__(cls
, __instance
: Any
) -> bool:
1509 return isinstance(__instance
, cls
._backported
_typevarlike
)
1512 # Add default and infer_variance parameters from PEP 696 and 695
1513 class TypeVar(metaclass
=_TypeVarLikeMeta
):
1514 """Type variable."""
1516 _backported_typevarlike
= typing
.TypeVar
1518 def __new__(cls
, name
, *constraints
, bound
=None,
1519 covariant
=False, contravariant
=False,
1520 default
=_marker
, infer_variance
=False):
1521 if hasattr(typing
, "TypeAliasType"):
1522 # PEP 695 implemented, can pass infer_variance to typing.TypeVar
1523 typevar
= typing
.TypeVar(name
, *constraints
, bound
=bound
,
1524 covariant
=covariant
, contravariant
=contravariant
,
1525 infer_variance
=infer_variance
)
1527 typevar
= typing
.TypeVar(name
, *constraints
, bound
=bound
,
1528 covariant
=covariant
, contravariant
=contravariant
)
1529 if infer_variance
and (covariant
or contravariant
):
1530 raise ValueError("Variance cannot be specified with infer_variance.")
1531 typevar
.__infer
_variance
__ = infer_variance
1532 _set_default(typevar
, default
)
1533 _set_module(typevar
)
1536 def __init_subclass__(cls
) -> None:
1537 raise TypeError(f
"type '{__name__}.TypeVar' is not an acceptable base type")
1540 # Python 3.10+ has PEP 612
1541 if hasattr(typing
, 'ParamSpecArgs'):
1542 ParamSpecArgs
= typing
.ParamSpecArgs
1543 ParamSpecKwargs
= typing
.ParamSpecKwargs
1547 """Mixin to indicate that object should not be copied."""
1553 def __deepcopy__(self
, memo
):
1556 class ParamSpecArgs(_Immutable
):
1557 """The args for a ParamSpec object.
1559 Given a ParamSpec object P, P.args is an instance of ParamSpecArgs.
1561 ParamSpecArgs objects have a reference back to their ParamSpec:
1563 P.args.__origin__ is P
1565 This type is meant for runtime introspection and has no special meaning to
1566 static type checkers.
1568 def __init__(self
, origin
):
1569 self
.__origin
__ = origin
1572 return f
"{self.__origin__.__name__}.args"
1574 def __eq__(self
, other
):
1575 if not isinstance(other
, ParamSpecArgs
):
1576 return NotImplemented
1577 return self
.__origin
__ == other
.__origin
__
1579 class ParamSpecKwargs(_Immutable
):
1580 """The kwargs for a ParamSpec object.
1582 Given a ParamSpec object P, P.kwargs is an instance of ParamSpecKwargs.
1584 ParamSpecKwargs objects have a reference back to their ParamSpec:
1586 P.kwargs.__origin__ is P
1588 This type is meant for runtime introspection and has no special meaning to
1589 static type checkers.
1591 def __init__(self
, origin
):
1592 self
.__origin
__ = origin
1595 return f
"{self.__origin__.__name__}.kwargs"
1597 def __eq__(self
, other
):
1598 if not isinstance(other
, ParamSpecKwargs
):
1599 return NotImplemented
1600 return self
.__origin
__ == other
.__origin
__
1603 if hasattr(typing
, 'ParamSpec'):
1605 # Add default parameter - PEP 696
1606 class ParamSpec(metaclass
=_TypeVarLikeMeta
):
1607 """Parameter specification."""
1609 _backported_typevarlike
= typing
.ParamSpec
1611 def __new__(cls
, name
, *, bound
=None,
1612 covariant
=False, contravariant
=False,
1613 infer_variance
=False, default
=_marker
):
1614 if hasattr(typing
, "TypeAliasType"):
1615 # PEP 695 implemented, can pass infer_variance to typing.TypeVar
1616 paramspec
= typing
.ParamSpec(name
, bound
=bound
,
1617 covariant
=covariant
,
1618 contravariant
=contravariant
,
1619 infer_variance
=infer_variance
)
1621 paramspec
= typing
.ParamSpec(name
, bound
=bound
,
1622 covariant
=covariant
,
1623 contravariant
=contravariant
)
1624 paramspec
.__infer
_variance
__ = infer_variance
1626 _set_default(paramspec
, default
)
1627 _set_module(paramspec
)
1630 def __init_subclass__(cls
) -> None:
1631 raise TypeError(f
"type '{__name__}.ParamSpec' is not an acceptable base type")
1636 # Inherits from list as a workaround for Callable checks in Python < 3.9.2.
1637 class ParamSpec(list, _DefaultMixin
):
1638 """Parameter specification variable.
1644 Parameter specification variables exist primarily for the benefit of static
1645 type checkers. They are used to forward the parameter types of one
1646 callable to another callable, a pattern commonly found in higher order
1647 functions and decorators. They are only valid when used in ``Concatenate``,
1648 or s the first argument to ``Callable``. In Python 3.10 and higher,
1649 they are also supported in user-defined Generics at runtime.
1650 See class Generic for more information on generic types. An
1651 example for annotating a decorator::
1656 def add_logging(f: Callable[P, T]) -> Callable[P, T]:
1657 '''A type-safe decorator to add logging to a function.'''
1658 def inner(*args: P.args, **kwargs: P.kwargs) -> T:
1659 logging.info(f'{f.__name__} was called')
1660 return f(*args, **kwargs)
1664 def add_two(x: float, y: float) -> float:
1665 '''Add two numbers together.'''
1668 Parameter specification variables defined with covariant=True or
1669 contravariant=True can be used to declare covariant or contravariant
1670 generic types. These keyword arguments are valid, but their actual semantics
1671 are yet to be decided. See PEP 612 for details.
1673 Parameter specification variables can be introspected. e.g.:
1677 P.__covariant__ == False
1678 P.__contravariant__ == False
1680 Note that only parameter specification variables defined in global scope can
1684 # Trick Generic __parameters__.
1685 __class__
= typing
.TypeVar
1689 return ParamSpecArgs(self
)
1693 return ParamSpecKwargs(self
)
1695 def __init__(self
, name
, *, bound
=None, covariant
=False, contravariant
=False,
1696 infer_variance
=False, default
=_marker
):
1697 super().__init
__([self
])
1698 self
.__name
__ = name
1699 self
.__covariant
__ = bool(covariant
)
1700 self
.__contravariant
__ = bool(contravariant
)
1701 self
.__infer
_variance
__ = bool(infer_variance
)
1703 self
.__bound
__ = typing
._type
_check
(bound
, 'Bound must be a type.')
1705 self
.__bound
__ = None
1706 _DefaultMixin
.__init
__(self
, default
)
1710 if def_mod
!= 'typing_extensions':
1711 self
.__module
__ = def_mod
1714 if self
.__infer
_variance
__:
1716 elif self
.__covariant
__:
1718 elif self
.__contravariant
__:
1722 return prefix
+ self
.__name
__
1725 return object.__hash
__(self
)
1727 def __eq__(self
, other
):
1728 return self
is other
1730 def __reduce__(self
):
1731 return self
.__name
__
1733 # Hack to get typing._type_check to pass.
1734 def __call__(self
, *args
, **kwargs
):
1739 if not hasattr(typing
, 'Concatenate'):
1740 # Inherits from list as a workaround for Callable checks in Python < 3.9.2.
1741 class _ConcatenateGenericAlias(list):
1743 # Trick Generic into looking into this for __parameters__.
1744 __class__
= typing
._GenericAlias
1749 def __init__(self
, origin
, args
):
1750 super().__init
__(args
)
1751 self
.__origin
__ = origin
1752 self
.__args
__ = args
1755 _type_repr
= typing
._type
_repr
1756 return (f
'{_type_repr(self.__origin__)}'
1757 f
'[{", ".join(_type_repr(arg) for arg in self.__args__)}]')
1760 return hash((self
.__origin
__, self
.__args
__))
1762 # Hack to get typing._type_check to pass in Generic.
1763 def __call__(self
, *args
, **kwargs
):
1767 def __parameters__(self
):
1769 tp
for tp
in self
.__args
__ if isinstance(tp
, (typing
.TypeVar
, ParamSpec
))
1775 def _concatenate_getitem(self
, parameters
):
1776 if parameters
== ():
1777 raise TypeError("Cannot take a Concatenate of no types.")
1778 if not isinstance(parameters
, tuple):
1779 parameters
= (parameters
,)
1780 if not isinstance(parameters
[-1], ParamSpec
):
1781 raise TypeError("The last parameter to Concatenate should be a "
1782 "ParamSpec variable.")
1783 msg
= "Concatenate[arg, ...]: each arg must be a type."
1784 parameters
= tuple(typing
._type
_check
(p
, msg
) for p
in parameters
)
1785 return _ConcatenateGenericAlias(self
, parameters
)
1789 if hasattr(typing
, 'Concatenate'):
1790 Concatenate
= typing
.Concatenate
1791 _ConcatenateGenericAlias
= typing
._ConcatenateGenericAlias
# noqa: F811
1793 elif sys
.version_info
[:2] >= (3, 9):
1794 @_ExtensionsSpecialForm
1795 def Concatenate(self
, parameters
):
1796 """Used in conjunction with ``ParamSpec`` and ``Callable`` to represent a
1797 higher order function which adds, removes or transforms parameters of a
1802 Callable[Concatenate[int, P], int]
1804 See PEP 612 for detailed information.
1806 return _concatenate_getitem(self
, parameters
)
1809 class _ConcatenateForm(_ExtensionsSpecialForm
, _root
=True):
1810 def __getitem__(self
, parameters
):
1811 return _concatenate_getitem(self
, parameters
)
1813 Concatenate
= _ConcatenateForm(
1815 doc
="""Used in conjunction with ``ParamSpec`` and ``Callable`` to represent a
1816 higher order function which adds, removes or transforms parameters of a
1821 Callable[Concatenate[int, P], int]
1823 See PEP 612 for detailed information.
1827 if hasattr(typing
, 'TypeGuard'):
1828 TypeGuard
= typing
.TypeGuard
1830 elif sys
.version_info
[:2] >= (3, 9):
1831 @_ExtensionsSpecialForm
1832 def TypeGuard(self
, parameters
):
1833 """Special typing form used to annotate the return type of a user-defined
1834 type guard function. ``TypeGuard`` only accepts a single type argument.
1835 At runtime, functions marked this way should return a boolean.
1837 ``TypeGuard`` aims to benefit *type narrowing* -- a technique used by static
1838 type checkers to determine a more precise type of an expression within a
1839 program's code flow. Usually type narrowing is done by analyzing
1840 conditional code flow and applying the narrowing to a block of code. The
1841 conditional expression here is sometimes referred to as a "type guard".
1843 Sometimes it would be convenient to use a user-defined boolean function
1844 as a type guard. Such a function should use ``TypeGuard[...]`` as its
1845 return type to alert static type checkers to this intention.
1847 Using ``-> TypeGuard`` tells the static type checker that for a given
1850 1. The return value is a boolean.
1851 2. If the return value is ``True``, the type of its argument
1852 is the type inside ``TypeGuard``.
1856 def is_str(val: Union[str, float]):
1857 # "isinstance" type guard
1858 if isinstance(val, str):
1859 # Type of ``val`` is narrowed to ``str``
1862 # Else, type of ``val`` is narrowed to ``float``.
1865 Strict type narrowing is not enforced -- ``TypeB`` need not be a narrower
1866 form of ``TypeA`` (it can even be a wider form) and this may lead to
1867 type-unsafe results. The main reason is to allow for things like
1868 narrowing ``List[object]`` to ``List[str]`` even though the latter is not
1869 a subtype of the former, since ``List`` is invariant. The responsibility of
1870 writing type-safe type guards is left to the user.
1872 ``TypeGuard`` also works with type variables. For more information, see
1873 PEP 647 (User-Defined Type Guards).
1875 item
= typing
._type
_check
(parameters
, f
'{self} accepts only a single type.')
1876 return typing
._GenericAlias
(self
, (item
,))
1879 class _TypeGuardForm(_ExtensionsSpecialForm
, _root
=True):
1880 def __getitem__(self
, parameters
):
1881 item
= typing
._type
_check
(parameters
,
1882 f
'{self._name} accepts only a single type')
1883 return typing
._GenericAlias
(self
, (item
,))
1885 TypeGuard
= _TypeGuardForm(
1887 doc
="""Special typing form used to annotate the return type of a user-defined
1888 type guard function. ``TypeGuard`` only accepts a single type argument.
1889 At runtime, functions marked this way should return a boolean.
1891 ``TypeGuard`` aims to benefit *type narrowing* -- a technique used by static
1892 type checkers to determine a more precise type of an expression within a
1893 program's code flow. Usually type narrowing is done by analyzing
1894 conditional code flow and applying the narrowing to a block of code. The
1895 conditional expression here is sometimes referred to as a "type guard".
1897 Sometimes it would be convenient to use a user-defined boolean function
1898 as a type guard. Such a function should use ``TypeGuard[...]`` as its
1899 return type to alert static type checkers to this intention.
1901 Using ``-> TypeGuard`` tells the static type checker that for a given
1904 1. The return value is a boolean.
1905 2. If the return value is ``True``, the type of its argument
1906 is the type inside ``TypeGuard``.
1910 def is_str(val: Union[str, float]):
1911 # "isinstance" type guard
1912 if isinstance(val, str):
1913 # Type of ``val`` is narrowed to ``str``
1916 # Else, type of ``val`` is narrowed to ``float``.
1919 Strict type narrowing is not enforced -- ``TypeB`` need not be a narrower
1920 form of ``TypeA`` (it can even be a wider form) and this may lead to
1921 type-unsafe results. The main reason is to allow for things like
1922 narrowing ``List[object]`` to ``List[str]`` even though the latter is not
1923 a subtype of the former, since ``List`` is invariant. The responsibility of
1924 writing type-safe type guards is left to the user.
1926 ``TypeGuard`` also works with type variables. For more information, see
1927 PEP 647 (User-Defined Type Guards).
1931 # Vendored from cpython typing._SpecialFrom
1932 class _SpecialForm(typing
._Final
, _root
=True):
1933 __slots__
= ('_name', '__doc__', '_getitem')
1935 def __init__(self
, getitem
):
1936 self
._getitem
= getitem
1937 self
._name
= getitem
.__name
__
1938 self
.__doc
__ = getitem
.__doc
__
1940 def __getattr__(self
, item
):
1941 if item
in {'__name__', '__qualname__'}
:
1944 raise AttributeError(item
)
1946 def __mro_entries__(self
, bases
):
1947 raise TypeError(f
"Cannot subclass {self!r}")
1950 return f
'typing_extensions.{self._name}'
1952 def __reduce__(self
):
1955 def __call__(self
, *args
, **kwds
):
1956 raise TypeError(f
"Cannot instantiate {self!r}")
1958 def __or__(self
, other
):
1959 return typing
.Union
[self
, other
]
1961 def __ror__(self
, other
):
1962 return typing
.Union
[other
, self
]
1964 def __instancecheck__(self
, obj
):
1965 raise TypeError(f
"{self} cannot be used with isinstance()")
1967 def __subclasscheck__(self
, cls
):
1968 raise TypeError(f
"{self} cannot be used with issubclass()")
1971 def __getitem__(self
, parameters
):
1972 return self
._getitem
(self
, parameters
)
1975 if hasattr(typing
, "LiteralString"):
1976 LiteralString
= typing
.LiteralString
1979 def LiteralString(self
, params
):
1980 """Represents an arbitrary literal string.
1984 from pip._vendor.typing_extensions import LiteralString
1986 def query(sql: LiteralString) -> ...:
1989 query("SELECT * FROM table") # ok
1990 query(f"SELECT * FROM {input()}") # not ok
1992 See PEP 675 for details.
1995 raise TypeError(f
"{self} is not subscriptable")
1998 if hasattr(typing
, "Self"):
2002 def Self(self
, params
):
2003 """Used to spell the type of "self" in classes.
2007 from typing import Self
2010 def parse(self, data: bytes) -> Self:
2016 raise TypeError(f
"{self} is not subscriptable")
2019 if hasattr(typing
, "Never"):
2020 Never
= typing
.Never
2023 def Never(self
, params
):
2024 """The bottom type, a type that has no members.
2026 This can be used to define a function that should never be
2027 called, or a function that never returns::
2029 from pip._vendor.typing_extensions import Never
2031 def never_call_me(arg: Never) -> None:
2034 def int_or_str(arg: int | str) -> None:
2035 never_call_me(arg) # type checker error
2038 print("It's an int")
2042 never_call_me(arg) # ok, arg is of type Never
2046 raise TypeError(f
"{self} is not subscriptable")
2049 if hasattr(typing
, 'Required'):
2050 Required
= typing
.Required
2051 NotRequired
= typing
.NotRequired
2052 elif sys
.version_info
[:2] >= (3, 9):
2053 @_ExtensionsSpecialForm
2054 def Required(self
, parameters
):
2055 """A special typing construct to mark a key of a total=False TypedDict
2056 as required. For example:
2058 class Movie(TypedDict, total=False):
2059 title: Required[str]
2063 title='The Matrix', # typechecker error if key is omitted
2067 There is no runtime checking that a required key is actually provided
2068 when instantiating a related TypedDict.
2070 item
= typing
._type
_check
(parameters
, f
'{self._name} accepts only a single type.')
2071 return typing
._GenericAlias
(self
, (item
,))
2073 @_ExtensionsSpecialForm
2074 def NotRequired(self
, parameters
):
2075 """A special typing construct to mark a key of a TypedDict as
2076 potentially missing. For example:
2078 class Movie(TypedDict):
2080 year: NotRequired[int]
2083 title='The Matrix', # typechecker error if key is omitted
2087 item
= typing
._type
_check
(parameters
, f
'{self._name} accepts only a single type.')
2088 return typing
._GenericAlias
(self
, (item
,))
2091 class _RequiredForm(_ExtensionsSpecialForm
, _root
=True):
2092 def __getitem__(self
, parameters
):
2093 item
= typing
._type
_check
(parameters
,
2094 f
'{self._name} accepts only a single type.')
2095 return typing
._GenericAlias
(self
, (item
,))
2097 Required
= _RequiredForm(
2099 doc
="""A special typing construct to mark a key of a total=False TypedDict
2100 as required. For example:
2102 class Movie(TypedDict, total=False):
2103 title: Required[str]
2107 title='The Matrix', # typechecker error if key is omitted
2111 There is no runtime checking that a required key is actually provided
2112 when instantiating a related TypedDict.
2114 NotRequired
= _RequiredForm(
2116 doc
="""A special typing construct to mark a key of a TypedDict as
2117 potentially missing. For example:
2119 class Movie(TypedDict):
2121 year: NotRequired[int]
2124 title='The Matrix', # typechecker error if key is omitted
2131 Type unpack operator.
2133 The type unpack operator takes the child types from some container type,
2134 such as `tuple[int, str]` or a `TypeVarTuple`, and 'pulls them out'. For
2137 # For some generic class `Foo`:
2138 Foo[Unpack[tuple[int, str]]] # Equivalent to Foo[int, str]
2140 Ts = TypeVarTuple('Ts')
2141 # Specifies that `Bar` is generic in an arbitrary number of types.
2142 # (Think of `Ts` as a tuple of an arbitrary number of individual
2143 # `TypeVar`s, which the `Unpack` is 'pulling out' directly into the
2145 class Bar(Generic[Unpack[Ts]]): ...
2147 Bar[int, str] # Also valid
2149 From Python 3.11, this can also be done using the `*` operator:
2151 Foo[*tuple[int, str]]
2152 class Bar(Generic[*Ts]): ...
2154 The operator can also be used along with a `TypedDict` to annotate
2155 `**kwargs` in a function signature. For instance:
2157 class Movie(TypedDict):
2161 # This function expects two keyword arguments - *name* of type `str` and
2162 # *year* of type `int`.
2163 def foo(**kwargs: Unpack[Movie]): ...
2165 Note that there is only some runtime checking of this operator. Not
2166 everything the runtime allows may be accepted by static type checkers.
2168 For more information, see PEP 646 and PEP 692.
2172 if sys
.version_info
>= (3, 12): # PEP 692 changed the repr of Unpack[]
2173 Unpack
= typing
.Unpack
2175 def _is_unpack(obj
):
2176 return get_origin(obj
) is Unpack
2178 elif sys
.version_info
[:2] >= (3, 9):
2179 class _UnpackSpecialForm(_ExtensionsSpecialForm
, _root
=True):
2180 def __init__(self
, getitem
):
2181 super().__init
__(getitem
)
2182 self
.__doc
__ = _UNPACK_DOC
2184 class _UnpackAlias(typing
._GenericAlias
, _root
=True):
2185 __class__
= typing
.TypeVar
2188 def Unpack(self
, parameters
):
2189 item
= typing
._type
_check
(parameters
, f
'{self._name} accepts only a single type.')
2190 return _UnpackAlias(self
, (item
,))
2192 def _is_unpack(obj
):
2193 return isinstance(obj
, _UnpackAlias
)
2196 class _UnpackAlias(typing
._GenericAlias
, _root
=True):
2197 __class__
= typing
.TypeVar
2199 class _UnpackForm(_ExtensionsSpecialForm
, _root
=True):
2200 def __getitem__(self
, parameters
):
2201 item
= typing
._type
_check
(parameters
,
2202 f
'{self._name} accepts only a single type.')
2203 return _UnpackAlias(self
, (item
,))
2205 Unpack
= _UnpackForm('Unpack', doc
=_UNPACK_DOC
)
2207 def _is_unpack(obj
):
2208 return isinstance(obj
, _UnpackAlias
)
2211 if hasattr(typing
, "TypeVarTuple"): # 3.11+
2213 # Add default parameter - PEP 696
2214 class TypeVarTuple(metaclass
=_TypeVarLikeMeta
):
2215 """Type variable tuple."""
2217 _backported_typevarlike
= typing
.TypeVarTuple
2219 def __new__(cls
, name
, *, default
=_marker
):
2220 tvt
= typing
.TypeVarTuple(name
)
2221 _set_default(tvt
, default
)
2225 def __init_subclass__(self
, *args
, **kwds
):
2226 raise TypeError("Cannot subclass special typing classes")
2229 class TypeVarTuple(_DefaultMixin
):
2230 """Type variable tuple.
2234 Ts = TypeVarTuple('Ts')
2236 In the same way that a normal type variable is a stand-in for a single
2237 type such as ``int``, a type variable *tuple* is a stand-in for a *tuple*
2238 type such as ``Tuple[int, str]``.
2240 Type variable tuples can be used in ``Generic`` declarations.
2241 Consider the following example::
2243 class Array(Generic[*Ts]): ...
2245 The ``Ts`` type variable tuple here behaves like ``tuple[T1, T2]``,
2246 where ``T1`` and ``T2`` are type variables. To use these type variables
2247 as type parameters of ``Array``, we must *unpack* the type variable tuple using
2248 the star operator: ``*Ts``. The signature of ``Array`` then behaves
2249 as if we had simply written ``class Array(Generic[T1, T2]): ...``.
2250 In contrast to ``Generic[T1, T2]``, however, ``Generic[*Shape]`` allows
2251 us to parameterise the class with an *arbitrary* number of type parameters.
2253 Type variable tuples can be used anywhere a normal ``TypeVar`` can.
2254 This includes class definitions, as shown above, as well as function
2255 signatures and variable annotations::
2257 class Array(Generic[*Ts]):
2259 def __init__(self, shape: Tuple[*Ts]):
2260 self._shape: Tuple[*Ts] = shape
2262 def get_shape(self) -> Tuple[*Ts]:
2265 shape = (Height(480), Width(640))
2266 x: Array[Height, Width] = Array(shape)
2267 y = abs(x) # Inferred type is Array[Height, Width]
2268 z = x + x # ... is Array[Height, Width]
2269 x.get_shape() # ... is tuple[Height, Width]
2273 # Trick Generic __parameters__.
2274 __class__
= typing
.TypeVar
2277 yield self
.__unpacked
__
2279 def __init__(self
, name
, *, default
=_marker
):
2280 self
.__name
__ = name
2281 _DefaultMixin
.__init
__(self
, default
)
2285 if def_mod
!= 'typing_extensions':
2286 self
.__module
__ = def_mod
2288 self
.__unpacked
__ = Unpack
[self
]
2291 return self
.__name
__
2294 return object.__hash
__(self
)
2296 def __eq__(self
, other
):
2297 return self
is other
2299 def __reduce__(self
):
2300 return self
.__name
__
2302 def __init_subclass__(self
, *args
, **kwds
):
2303 if '_root' not in kwds
:
2304 raise TypeError("Cannot subclass special typing classes")
2307 if hasattr(typing
, "reveal_type"):
2308 reveal_type
= typing
.reveal_type
2310 def reveal_type(__obj
: T
) -> T
:
2311 """Reveal the inferred type of a variable.
2313 When a static type checker encounters a call to ``reveal_type()``,
2314 it will emit the inferred type of the argument::
2319 Running a static type checker (e.g., ``mypy``) on this example
2320 will produce output similar to 'Revealed type is "builtins.int"'.
2322 At runtime, the function prints the runtime type of the
2323 argument and returns it unchanged.
2326 print(f
"Runtime type is {type(__obj).__name__!r}", file=sys
.stderr
)
2330 if hasattr(typing
, "assert_never"):
2331 assert_never
= typing
.assert_never
2333 def assert_never(__arg
: Never
) -> Never
:
2334 """Assert to the type checker that a line of code is unreachable.
2338 def int_or_str(arg: int | str) -> None:
2341 print("It's an int")
2347 If a type checker finds that a call to assert_never() is
2348 reachable, it will emit an error.
2350 At runtime, this throws an exception when called.
2353 raise AssertionError("Expected code to be unreachable")
2356 if sys
.version_info
>= (3, 12):
2357 # dataclass_transform exists in 3.11 but lacks the frozen_default parameter
2358 dataclass_transform
= typing
.dataclass_transform
2360 def dataclass_transform(
2362 eq_default
: bool = True,
2363 order_default
: bool = False,
2364 kw_only_default
: bool = False,
2365 frozen_default
: bool = False,
2366 field_specifiers
: typing
.Tuple
[
2367 typing
.Union
[typing
.Type
[typing
.Any
], typing
.Callable
[..., typing
.Any
]],
2370 **kwargs
: typing
.Any
,
2371 ) -> typing
.Callable
[[T
], T
]:
2372 """Decorator that marks a function, class, or metaclass as providing
2373 dataclass-like behavior.
2377 from pip._vendor.typing_extensions import dataclass_transform
2381 # Used on a decorator function
2382 @dataclass_transform()
2383 def create_model(cls: type[_T]) -> type[_T]:
2388 class CustomerModel:
2392 # Used on a base class
2393 @dataclass_transform()
2394 class ModelBase: ...
2396 class CustomerModel(ModelBase):
2400 # Used on a metaclass
2401 @dataclass_transform()
2402 class ModelMeta(type): ...
2404 class ModelBase(metaclass=ModelMeta): ...
2406 class CustomerModel(ModelBase):
2410 Each of the ``CustomerModel`` classes defined in this example will now
2411 behave similarly to a dataclass created with the ``@dataclasses.dataclass``
2412 decorator. For example, the type checker will synthesize an ``__init__``
2415 The arguments to this decorator can be used to customize this behavior:
2416 - ``eq_default`` indicates whether the ``eq`` parameter is assumed to be
2417 True or False if it is omitted by the caller.
2418 - ``order_default`` indicates whether the ``order`` parameter is
2419 assumed to be True or False if it is omitted by the caller.
2420 - ``kw_only_default`` indicates whether the ``kw_only`` parameter is
2421 assumed to be True or False if it is omitted by the caller.
2422 - ``frozen_default`` indicates whether the ``frozen`` parameter is
2423 assumed to be True or False if it is omitted by the caller.
2424 - ``field_specifiers`` specifies a static list of supported classes
2425 or functions that describe fields, similar to ``dataclasses.field()``.
2427 At runtime, this decorator records its arguments in the
2428 ``__dataclass_transform__`` attribute on the decorated object.
2430 See PEP 681 for details.
2433 def decorator(cls_or_fn
):
2434 cls_or_fn
.__dataclass
_transform
__ = {
2435 "eq_default": eq_default
,
2436 "order_default": order_default
,
2437 "kw_only_default": kw_only_default
,
2438 "frozen_default": frozen_default
,
2439 "field_specifiers": field_specifiers
,
2446 if hasattr(typing
, "override"):
2447 override
= typing
.override
2449 _F
= typing
.TypeVar("_F", bound
=typing
.Callable
[..., typing
.Any
])
2451 def override(__arg
: _F
) -> _F
:
2452 """Indicate that a method is intended to override a method in a base class.
2457 def method(self) -> None: ...
2462 def method(self) -> None:
2465 When this decorator is applied to a method, the type checker will
2466 validate that it overrides a method with the same name on a base class.
2467 This helps prevent bugs that may occur when a base class is changed
2468 without an equivalent change to a child class.
2470 There is no runtime checking of these properties. The decorator
2471 sets the ``__override__`` attribute to ``True`` on the decorated object
2472 to allow runtime introspection.
2474 See PEP 698 for details.
2478 __arg
.__override
__ = True
2479 except (AttributeError, TypeError):
2480 # Skip the attribute silently if it is not writable.
2481 # AttributeError happens if the object has __slots__ or a
2482 # read-only property, TypeError if it's a builtin class.
2487 if hasattr(typing
, "deprecated"):
2488 deprecated
= typing
.deprecated
2490 _T
= typing
.TypeVar("_T")
2495 category
: typing
.Optional
[typing
.Type
[Warning]] = DeprecationWarning,
2496 stacklevel
: int = 1,
2497 ) -> typing
.Callable
[[_T
], _T
]:
2498 """Indicate that a class, function or overload is deprecated.
2502 @deprecated("Use B instead")
2506 @deprecated("Use g instead")
2511 @deprecated("int support is deprecated")
2512 def g(x: int) -> int: ...
2514 def g(x: str) -> int: ...
2516 When this decorator is applied to an object, the type checker
2517 will generate a diagnostic on usage of the deprecated object.
2519 The warning specified by ``category`` will be emitted on use
2520 of deprecated objects. For functions, that happens on calls;
2521 for classes, on instantiation. If the ``category`` is ``None``,
2522 no warning is emitted. The ``stacklevel`` determines where the
2523 warning is emitted. If it is ``1`` (the default), the warning
2524 is emitted at the direct caller of the deprecated object; if it
2525 is higher, it is emitted further up the stack.
2527 The decorator sets the ``__deprecated__``
2528 attribute on the decorated object to the deprecation message
2529 passed to the decorator. If applied to an overload, the decorator
2530 must be after the ``@overload`` decorator for the attribute to
2531 exist on the overload as returned by ``get_overloads()``.
2533 See PEP 702 for details.
2536 def decorator(__arg
: _T
) -> _T
:
2537 if category
is None:
2538 __arg
.__deprecated
__ = __msg
2540 elif isinstance(__arg
, type):
2541 original_new
= __arg
.__new
__
2542 has_init
= __arg
.__init
__ is not object.__init
__
2544 @functools.wraps(original_new
)
2545 def __new__(cls
, *args
, **kwargs
):
2546 warnings
.warn(__msg
, category
=category
, stacklevel
=stacklevel
+ 1)
2547 if original_new
is not object.__new
__:
2548 return original_new(cls
, *args
, **kwargs
)
2549 # Mirrors a similar check in object.__new__.
2550 elif not has_init
and (args
or kwargs
):
2551 raise TypeError(f
"{cls.__name__}() takes no arguments")
2553 return original_new(cls
)
2555 __arg
.__new
__ = staticmethod(__new__
)
2556 __arg
.__deprecated
__ = __new__
.__deprecated
__ = __msg
2558 elif callable(__arg
):
2559 @functools.wraps(__arg
)
2560 def wrapper(*args
, **kwargs
):
2561 warnings
.warn(__msg
, category
=category
, stacklevel
=stacklevel
+ 1)
2562 return __arg(*args
, **kwargs
)
2564 __arg
.__deprecated
__ = wrapper
.__deprecated
__ = __msg
2568 "@deprecated decorator with non-None category must be applied to "
2569 f
"a class or callable, not {__arg!r}"
2575 # We have to do some monkey patching to deal with the dual nature of
2576 # Unpack/TypeVarTuple:
2577 # - We want Unpack to be a kind of TypeVar so it gets accepted in
2578 # Generic[Unpack[Ts]]
2579 # - We want it to *not* be treated as a TypeVar for the purposes of
2580 # counting generic parameters, so that when we subscript a generic,
2581 # the runtime doesn't try to substitute the Unpack with the subscripted type.
2582 if not hasattr(typing
, "TypeVarTuple"):
2583 typing
._collect
_type
_vars
= _collect_type_vars
2584 typing
._check
_generic
= _check_generic
2587 # Backport typing.NamedTuple as it exists in Python 3.12.
2588 # In 3.11, the ability to define generic `NamedTuple`s was supported.
2589 # This was explicitly disallowed in 3.9-3.10, and only half-worked in <=3.8.
2590 # On 3.12, we added __orig_bases__ to call-based NamedTuples
2591 # On 3.13, we deprecated kwargs-based NamedTuples
2592 if sys
.version_info
>= (3, 13):
2593 NamedTuple
= typing
.NamedTuple
2595 def _make_nmtuple(name
, types
, module
, defaults
=()):
2596 fields
= [n
for n
, t
in types
]
2597 annotations
= {n: typing._type_check(t, f"field {n} annotation must be a
type")
2599 nm_tpl = collections.namedtuple(name, fields,
2600 defaults=defaults, module=module)
2601 nm_tpl.__annotations__ = nm_tpl.__new__.__annotations__ = annotations
2602 # The `_field_types` attribute was removed in 3.9;
2603 # in earlier versions, it is the same as the `__annotations__` attribute
2604 if sys.version_info < (3, 9):
2605 nm_tpl._field_types = annotations
2608 _prohibited_namedtuple_fields = typing._prohibited
2609 _special_namedtuple_fields = frozenset({'__module__', '__name__', '__annotations__'})
2611 class _NamedTupleMeta(type):
2612 def __new__(cls, typename, bases, ns):
2613 assert _NamedTuple in bases
2615 if base is not _NamedTuple and base is not typing.Generic:
2617 'can only inherit from a NamedTuple type and Generic')
2618 bases = tuple(tuple if base is _NamedTuple else base for base in bases)
2619 types = ns.get('__annotations__', {})
2621 for field_name in types:
2622 if field_name in ns:
2623 default_names.append(field_name)
2625 raise TypeError(f"Non
-default namedtuple field {field_name}
"
2626 f"cannot follow default field
"
2627 f"{'s' if len(default_names) > 1 else ''}
"
2628 f"{', '.join(default_names)}
")
2629 nm_tpl = _make_nmtuple(
2630 typename, types.items(),
2631 defaults=[ns[n] for n in default_names],
2632 module=ns['__module__']
2634 nm_tpl.__bases__ = bases
2635 if typing.Generic in bases:
2636 if hasattr(typing, '_generic_class_getitem'): # 3.12+
2637 nm_tpl.__class_getitem__ = classmethod(typing._generic_class_getitem)
2639 class_getitem = typing.Generic.__class_getitem__.__func__
2640 nm_tpl.__class_getitem__ = classmethod(class_getitem)
2641 # update from user namespace without overriding special namedtuple attributes
2643 if key in _prohibited_namedtuple_fields:
2644 raise AttributeError("Cannot overwrite NamedTuple attribute
" + key)
2645 elif key not in _special_namedtuple_fields and key not in nm_tpl._fields:
2646 setattr(nm_tpl, key, ns[key])
2647 if typing.Generic in bases:
2648 nm_tpl.__init_subclass__()
2651 _NamedTuple = type.__new__(_NamedTupleMeta, 'NamedTuple', (), {})
2653 def _namedtuple_mro_entries(bases):
2654 assert NamedTuple in bases
2655 return (_NamedTuple,)
2657 @_ensure_subclassable(_namedtuple_mro_entries)
2658 def NamedTuple(__typename, __fields=_marker, **kwargs):
2659 """Typed version of namedtuple.
2663 class Employee(NamedTuple):
2667 This is equivalent to::
2669 Employee = collections.namedtuple('Employee', ['name', 'id'])
2671 The resulting class has an extra __annotations__ attribute, giving a
2672 dict that maps field names to types. (The field names are also in
2673 the _fields attribute, which is part of the namedtuple API.)
2674 An alternative equivalent functional syntax is also accepted::
2676 Employee = NamedTuple('Employee', [('name', str), ('id', int)])
2678 if __fields is _marker:
2680 deprecated_thing = "Creating NamedTuple classes using keyword arguments
"
2682 "{name}
is deprecated
and will be disallowed
in Python {remove}
. "
2683 "Use the
class-based
or functional syntax instead
."
2686 deprecated_thing = "Failing to
pass a value
for the
'fields' parameter
"
2687 example = f"`{__typename}
= NamedTuple({__typename!r}
, [])`
"
2689 "{name}
is deprecated
and will be disallowed
in Python {remove}
. "
2690 "To create a NamedTuple
class with 0 fields
"
2691 "using the functional syntax
, "
2692 "pass an empty
list, e
.g
. "
2694 elif __fields is None:
2697 "Cannot
pass `
None`
as the
'fields' parameter
"
2698 "and also specify fields using keyword arguments
"
2701 deprecated_thing = "Passing `
None`
as the
'fields' parameter
"
2702 example = f"`{__typename}
= NamedTuple({__typename!r}
, [])`
"
2704 "{name}
is deprecated
and will be disallowed
in Python {remove}
. "
2705 "To create a NamedTuple
class with 0 fields
"
2706 "using the functional syntax
, "
2707 "pass an empty
list, e
.g
. "
2710 raise TypeError("Either
list of fields
or keywords
"
2711 " can be provided to NamedTuple
, not both
")
2712 if __fields is _marker or __fields is None:
2714 deprecation_msg.format(name=deprecated_thing, remove="3.15"),
2718 __fields = kwargs.items()
2719 nt = _make_nmtuple(__typename, __fields, module=_caller())
2720 nt.__orig_bases__ = (NamedTuple,)
2723 # On 3.8+, alter the signature so that it matches typing.NamedTuple.
2724 # The signature of typing.NamedTuple on >=3.8 is invalid syntax in Python 3.7,
2725 # so just leave the signature as it is on 3.7.
2726 if sys.version_info >= (3, 8):
2727 _new_signature = '(typename, fields=None, /, **kwargs)'
2728 if isinstance(NamedTuple, _types.FunctionType):
2729 NamedTuple.__text_signature__ = _new_signature
2731 NamedTuple.__call__.__text_signature__ = _new_signature
2734 if hasattr(collections.abc, "Buffer
"):
2735 Buffer = collections.abc.Buffer
2737 class Buffer(abc.ABC):
2738 """Base class for classes that implement the buffer protocol.
2740 The buffer protocol allows Python objects to expose a low-level
2741 memory buffer interface. Before Python 3.12, it is not possible
2742 to implement the buffer protocol in pure Python code, or even
2743 to check whether a class implements the buffer protocol. In
2744 Python 3.12 and higher, the ``__buffer__`` method allows access
2745 to the buffer protocol from Python code, and the
2746 ``collections.abc.Buffer`` ABC allows checking whether a class
2747 implements the buffer protocol.
2749 To indicate support for the buffer protocol in earlier versions,
2750 inherit from this ABC, either in a stub file or at runtime,
2751 or use ABC registration. This ABC provides no methods, because
2752 there is no Python-accessible methods shared by pre-3.12 buffer
2753 classes. It is useful primarily for static checks.
2757 # As a courtesy, register the most common stdlib buffer classes.
2758 Buffer.register(memoryview)
2759 Buffer.register(bytearray)
2760 Buffer.register(bytes)
2763 # Backport of types.get_original_bases, available on 3.12+ in CPython
2764 if hasattr(_types, "get_original_bases
"):
2765 get_original_bases = _types.get_original_bases
2767 def get_original_bases(__cls):
2768 """Return the class's "original
" bases prior to modification by `__mro_entries__`.
2772 from typing import TypeVar, Generic
2773 from pip._vendor.typing_extensions import NamedTuple, TypedDict
2776 class Foo(Generic[T]): ...
2777 class Bar(Foo[int], float): ...
2778 class Baz(list[str]): ...
2779 Eggs = NamedTuple("Eggs
", [("a
", int), ("b
", str)])
2780 Spam = TypedDict("Spam
", {"a": int, "b": str})
2782 assert get_original_bases(Bar) == (Foo[int], float)
2783 assert get_original_bases(Baz) == (list[str],)
2784 assert get_original_bases(Eggs) == (NamedTuple,)
2785 assert get_original_bases(Spam) == (TypedDict,)
2786 assert get_original_bases(int) == (object,)
2789 return __cls.__orig_bases__
2790 except AttributeError:
2792 return __cls.__bases__
2793 except AttributeError:
2795 f'Expected an instance of type, not {type(__cls).__name__!r}'
2799 # NewType is a class on Python 3.10+, making it pickleable
2800 # The error message for subclassing instances of NewType was improved on 3.11+
2801 if sys.version_info >= (3, 11):
2802 NewType = typing.NewType
2805 """NewType creates simple unique types with almost zero
2806 runtime overhead. NewType(name, tp) is considered a subtype of tp
2807 by static type checkers. At runtime, NewType(name, tp) returns
2808 a dummy callable that simply returns its argument. Usage::
2809 UserId = NewType('UserId', int)
2810 def name_by_id(user_id: UserId) -> str:
2812 UserId('user') # Fails type check
2813 name_by_id(42) # Fails type check
2814 name_by_id(UserId(42)) # OK
2815 num = UserId(5) + 1 # type: int
2818 def __call__(self, obj):
2821 def __init__(self, name, tp):
2822 self.__qualname__ = name
2824 name = name.rpartition('.')[-1]
2825 self.__name__ = name
2826 self.__supertype__ = tp
2828 if def_mod != 'typing_extensions':
2829 self.__module__ = def_mod
2831 def __mro_entries__(self, bases):
2832 # We defined __mro_entries__ to get a better error message
2833 # if a user attempts to subclass a NewType instance. bpo-46170
2834 supercls_name = self.__name__
2837 def __init_subclass__(cls):
2838 subcls_name = cls.__name__
2840 f"Cannot subclass an instance of NewType
. "
2841 f"Perhaps you were looking
for: "
2842 f"`{subcls_name}
= NewType({subcls_name!r}
, {supercls_name}
)`
"
2848 return f'{self.__module__}.{self.__qualname__}'
2850 def __reduce__(self):
2851 return self.__qualname__
2853 if sys.version_info >= (3, 10):
2855 # It doesn't make sense to have these methods on Python <3.10
2857 def __or__(self, other):
2858 return typing.Union[self, other]
2860 def __ror__(self, other):
2861 return typing.Union[other, self]
2864 if hasattr(typing, "TypeAliasType
"):
2865 TypeAliasType = typing.TypeAliasType
2867 def _is_unionable(obj):
2868 """Corresponds to is_unionable() in unionobject.c in CPython."""
2869 return obj is None or isinstance(obj, (
2871 _types.GenericAlias,
2876 class TypeAliasType:
2877 """Create named, parameterized type aliases.
2879 This provides a backport of the new `type` statement in Python 3.12:
2881 type ListOrSet[T] = list[T] | set[T]
2886 ListOrSet = TypeAliasType("ListOrSet
", list[T] | set[T], type_params=(T,))
2888 The name ListOrSet can then be used as an alias for the type it refers to.
2890 The type_params argument should contain all the type parameters used
2891 in the value of the type alias. If the alias is not generic, this
2892 argument is omitted.
2894 Static type checkers should only support type aliases declared using
2895 TypeAliasType that follow these rules:
2897 - The first argument (the name) must be a string literal.
2898 - The TypeAliasType instance must be immediately assigned to a variable
2899 of the same name. (For example, 'X = TypeAliasType("Y
", int)' is invalid,
2900 as is 'X, Y = TypeAliasType("X
", int), TypeAliasType("Y
", int)').
2904 def __init__(self, name: str, value, *, type_params=()):
2905 if not isinstance(name, str):
2906 raise TypeError("TypeAliasType name must be a string
")
2907 self.__value__ = value
2908 self.__type_params__ = type_params
2911 for type_param in type_params:
2912 if isinstance(type_param, TypeVarTuple):
2913 parameters.extend(type_param)
2915 parameters.append(type_param)
2916 self.__parameters__ = tuple(parameters)
2918 if def_mod != 'typing_extensions':
2919 self.__module__ = def_mod
2920 # Setting this attribute closes the TypeAliasType from further modification
2921 self.__name__ = name
2923 def __setattr__(self, __name: str, __value: object) -> None:
2924 if hasattr(self, "__name__
"):
2925 self._raise_attribute_error(__name)
2926 super().__setattr__(__name, __value)
2928 def __delattr__(self, __name: str) -> Never:
2929 self._raise_attribute_error(__name)
2931 def _raise_attribute_error(self, name: str) -> Never:
2932 # Match the Python 3.12 error messages exactly
2933 if name == "__name__
":
2934 raise AttributeError("readonly attribute
")
2935 elif name in {"__value__", "__type_params__", "__parameters__", "__module__"}:
2936 raise AttributeError(
2937 f"attribute
'{name}' of
'typing.TypeAliasType' objects
"
2941 raise AttributeError(
2942 f"'typing.TypeAliasType' object has no attribute
'{name}'"
2945 def __repr__(self) -> str:
2946 return self.__name__
2948 def __getitem__(self, parameters):
2949 if not isinstance(parameters, tuple):
2950 parameters = (parameters,)
2953 item, f'Subscripting {self.__name__} requires a type.'
2955 for item in parameters
2957 return typing._GenericAlias(self, tuple(parameters))
2959 def __reduce__(self):
2960 return self.__name__
2962 def __init_subclass__(cls, *args, **kwargs):
2964 "type 'typing_extensions.TypeAliasType' is not an acceptable base
type"
2967 # The presence of this method convinces typing._type_check
2968 # that TypeAliasTypes are types.
2970 raise TypeError("Type alias
is not callable")
2972 if sys.version_info >= (3, 10):
2973 def __or__(self, right):
2974 # For forward compatibility with 3.12, reject Unions
2975 # that are not accepted by the built-in Union.
2976 if not _is_unionable(right):
2977 return NotImplemented
2978 return typing.Union[self, right]
2980 def __ror__(self, left):
2981 if not _is_unionable(left):
2982 return NotImplemented
2983 return typing.Union[left, self]
2986 if hasattr(typing, "is_protocol
"):
2987 is_protocol = typing.is_protocol
2988 get_protocol_members = typing.get_protocol_members
2990 def is_protocol(__tp: type) -> bool:
2991 """Return True if the given type is a Protocol.
2995 >>> from typing_extensions import Protocol, is_protocol
2996 >>> class P(Protocol):
2997 ... def a(self) -> str: ...
3001 >>> is_protocol(int)
3005 isinstance(__tp, type)
3006 and getattr(__tp, '_is_protocol', False)
3007 and __tp is not Protocol
3008 and __tp is not getattr(typing, "Protocol
", object())
3011 def get_protocol_members(__tp: type) -> typing.FrozenSet[str]:
3012 """Return the set of members defined in a Protocol.
3016 >>> from typing_extensions import Protocol, get_protocol_members
3017 >>> class P(Protocol):
3018 ... def a(self) -> str: ...
3020 >>> get_protocol_members(P)
3021 frozenset({'a', 'b'})
3023 Raise a TypeError for arguments that are not Protocols.
3025 if not is_protocol(__tp):
3026 raise TypeError(f'{__tp!r} is not a Protocol')
3027 if hasattr(__tp, '__protocol_attrs__'):
3028 return frozenset(__tp.__protocol_attrs__)
3029 return frozenset(_get_protocol_attrs(__tp))
3032 # Aliases for items that have always been in typing.
3033 # Explicitly assign these (rather than using `from typing import *` at the top),
3034 # so that we get a CI error if one of these is deleted from typing.py
3035 # in a future version of Python
3036 AbstractSet = typing.AbstractSet
3037 AnyStr = typing.AnyStr
3038 BinaryIO = typing.BinaryIO
3039 Callable = typing.Callable
3040 Collection = typing.Collection
3041 Container = typing.Container
3043 ForwardRef = typing.ForwardRef
3044 FrozenSet = typing.FrozenSet
3045 Generator = typing.Generator
3046 Generic = typing.Generic
3047 Hashable = typing.Hashable
3049 ItemsView = typing.ItemsView
3050 Iterable = typing.Iterable
3051 Iterator = typing.Iterator
3052 KeysView = typing.KeysView
3054 Mapping = typing.Mapping
3055 MappingView = typing.MappingView
3056 Match = typing.Match
3057 MutableMapping = typing.MutableMapping
3058 MutableSequence = typing.MutableSequence
3059 MutableSet = typing.MutableSet
3060 Optional = typing.Optional
3061 Pattern = typing.Pattern
3062 Reversible = typing.Reversible
3063 Sequence = typing.Sequence
3065 Sized = typing.Sized
3066 TextIO = typing.TextIO
3067 Tuple = typing.Tuple
3068 Union = typing.Union
3069 ValuesView = typing.ValuesView
3071 no_type_check = typing.no_type_check
3072 no_type_check_decorator = typing.no_type_check_decorator