Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/typing_extensions.py: 37%
1281 statements
« prev ^ index » next coverage.py v7.4.4, created at 2024-04-20 06:09 +0000
« prev ^ index » next coverage.py v7.4.4, created at 2024-04-20 06:09 +0000
1import abc
2import collections
3import collections.abc
4import functools
5import inspect
6import operator
7import sys
8import types as _types
9import typing
10import warnings
12__all__ = [
13 # Super-special typing primitives.
14 'Any',
15 'ClassVar',
16 'Concatenate',
17 'Final',
18 'LiteralString',
19 'ParamSpec',
20 'ParamSpecArgs',
21 'ParamSpecKwargs',
22 'Self',
23 'Type',
24 'TypeVar',
25 'TypeVarTuple',
26 'Unpack',
28 # ABCs (from collections.abc).
29 'Awaitable',
30 'AsyncIterator',
31 'AsyncIterable',
32 'Coroutine',
33 'AsyncGenerator',
34 'AsyncContextManager',
35 'Buffer',
36 'ChainMap',
38 # Concrete collection types.
39 'ContextManager',
40 'Counter',
41 'Deque',
42 'DefaultDict',
43 'NamedTuple',
44 'OrderedDict',
45 'TypedDict',
47 # Structural checks, a.k.a. protocols.
48 'SupportsAbs',
49 'SupportsBytes',
50 'SupportsComplex',
51 'SupportsFloat',
52 'SupportsIndex',
53 'SupportsInt',
54 'SupportsRound',
56 # One-off things.
57 'Annotated',
58 'assert_never',
59 'assert_type',
60 'clear_overloads',
61 'dataclass_transform',
62 'deprecated',
63 'Doc',
64 'get_overloads',
65 'final',
66 'get_args',
67 'get_origin',
68 'get_original_bases',
69 'get_protocol_members',
70 'get_type_hints',
71 'IntVar',
72 'is_protocol',
73 'is_typeddict',
74 'Literal',
75 'NewType',
76 'overload',
77 'override',
78 'Protocol',
79 'reveal_type',
80 'runtime',
81 'runtime_checkable',
82 'Text',
83 'TypeAlias',
84 'TypeAliasType',
85 'TypeGuard',
86 'TypeIs',
87 'TYPE_CHECKING',
88 'Never',
89 'NoReturn',
90 'ReadOnly',
91 'Required',
92 'NotRequired',
94 # Pure aliases, have always been in typing
95 'AbstractSet',
96 'AnyStr',
97 'BinaryIO',
98 'Callable',
99 'Collection',
100 'Container',
101 'Dict',
102 'ForwardRef',
103 'FrozenSet',
104 'Generator',
105 'Generic',
106 'Hashable',
107 'IO',
108 'ItemsView',
109 'Iterable',
110 'Iterator',
111 'KeysView',
112 'List',
113 'Mapping',
114 'MappingView',
115 'Match',
116 'MutableMapping',
117 'MutableSequence',
118 'MutableSet',
119 'Optional',
120 'Pattern',
121 'Reversible',
122 'Sequence',
123 'Set',
124 'Sized',
125 'TextIO',
126 'Tuple',
127 'Union',
128 'ValuesView',
129 'cast',
130 'no_type_check',
131 'no_type_check_decorator',
132]
134# for backward compatibility
135PEP_560 = True
136GenericMeta = type
138# The functions below are modified copies of typing internal helpers.
139# They are needed by _ProtocolMeta and they provide support for PEP 646.
142class _Sentinel:
143 def __repr__(self):
144 return "<sentinel>"
147_marker = _Sentinel()
150if sys.version_info >= (3, 10):
151 def _should_collect_from_parameters(t):
152 return isinstance(
153 t, (typing._GenericAlias, _types.GenericAlias, _types.UnionType)
154 )
155elif sys.version_info >= (3, 9):
156 def _should_collect_from_parameters(t):
157 return isinstance(t, (typing._GenericAlias, _types.GenericAlias))
158else:
159 def _should_collect_from_parameters(t):
160 return isinstance(t, typing._GenericAlias) and not t._special
163NoReturn = typing.NoReturn
165# Some unconstrained type variables. These are used by the container types.
166# (These are not for export.)
167T = typing.TypeVar('T') # Any type.
168KT = typing.TypeVar('KT') # Key type.
169VT = typing.TypeVar('VT') # Value type.
170T_co = typing.TypeVar('T_co', covariant=True) # Any type covariant containers.
171T_contra = typing.TypeVar('T_contra', contravariant=True) # Ditto contravariant.
174if sys.version_info >= (3, 11):
175 from typing import Any
176else:
178 class _AnyMeta(type):
179 def __instancecheck__(self, obj):
180 if self is Any:
181 raise TypeError("typing_extensions.Any cannot be used with isinstance()")
182 return super().__instancecheck__(obj)
184 def __repr__(self):
185 if self is Any:
186 return "typing_extensions.Any"
187 return super().__repr__()
189 class Any(metaclass=_AnyMeta):
190 """Special type indicating an unconstrained type.
191 - Any is compatible with every type.
192 - Any assumed to have all methods.
193 - All values assumed to be instances of Any.
194 Note that all the above statements are true from the point of view of
195 static type checkers. At runtime, Any should not be used with instance
196 checks.
197 """
198 def __new__(cls, *args, **kwargs):
199 if cls is Any:
200 raise TypeError("Any cannot be instantiated")
201 return super().__new__(cls, *args, **kwargs)
204ClassVar = typing.ClassVar
207class _ExtensionsSpecialForm(typing._SpecialForm, _root=True):
208 def __repr__(self):
209 return 'typing_extensions.' + self._name
212Final = typing.Final
214if sys.version_info >= (3, 11):
215 final = typing.final
216else:
217 # @final exists in 3.8+, but we backport it for all versions
218 # before 3.11 to keep support for the __final__ attribute.
219 # See https://bugs.python.org/issue46342
220 def final(f):
221 """This decorator can be used to indicate to type checkers that
222 the decorated method cannot be overridden, and decorated class
223 cannot be subclassed. For example:
225 class Base:
226 @final
227 def done(self) -> None:
228 ...
229 class Sub(Base):
230 def done(self) -> None: # Error reported by type checker
231 ...
232 @final
233 class Leaf:
234 ...
235 class Other(Leaf): # Error reported by type checker
236 ...
238 There is no runtime checking of these properties. The decorator
239 sets the ``__final__`` attribute to ``True`` on the decorated object
240 to allow runtime introspection.
241 """
242 try:
243 f.__final__ = True
244 except (AttributeError, TypeError):
245 # Skip the attribute silently if it is not writable.
246 # AttributeError happens if the object has __slots__ or a
247 # read-only property, TypeError if it's a builtin class.
248 pass
249 return f
252def IntVar(name):
253 return typing.TypeVar(name)
256# A Literal bug was fixed in 3.11.0, 3.10.1 and 3.9.8
257if sys.version_info >= (3, 10, 1):
258 Literal = typing.Literal
259else:
260 def _flatten_literal_params(parameters):
261 """An internal helper for Literal creation: flatten Literals among parameters"""
262 params = []
263 for p in parameters:
264 if isinstance(p, _LiteralGenericAlias):
265 params.extend(p.__args__)
266 else:
267 params.append(p)
268 return tuple(params)
270 def _value_and_type_iter(params):
271 for p in params:
272 yield p, type(p)
274 class _LiteralGenericAlias(typing._GenericAlias, _root=True):
275 def __eq__(self, other):
276 if not isinstance(other, _LiteralGenericAlias):
277 return NotImplemented
278 these_args_deduped = set(_value_and_type_iter(self.__args__))
279 other_args_deduped = set(_value_and_type_iter(other.__args__))
280 return these_args_deduped == other_args_deduped
282 def __hash__(self):
283 return hash(frozenset(_value_and_type_iter(self.__args__)))
285 class _LiteralForm(_ExtensionsSpecialForm, _root=True):
286 def __init__(self, doc: str):
287 self._name = 'Literal'
288 self._doc = self.__doc__ = doc
290 def __getitem__(self, parameters):
291 if not isinstance(parameters, tuple):
292 parameters = (parameters,)
294 parameters = _flatten_literal_params(parameters)
296 val_type_pairs = list(_value_and_type_iter(parameters))
297 try:
298 deduped_pairs = set(val_type_pairs)
299 except TypeError:
300 # unhashable parameters
301 pass
302 else:
303 # similar logic to typing._deduplicate on Python 3.9+
304 if len(deduped_pairs) < len(val_type_pairs):
305 new_parameters = []
306 for pair in val_type_pairs:
307 if pair in deduped_pairs:
308 new_parameters.append(pair[0])
309 deduped_pairs.remove(pair)
310 assert not deduped_pairs, deduped_pairs
311 parameters = tuple(new_parameters)
313 return _LiteralGenericAlias(self, parameters)
315 Literal = _LiteralForm(doc="""\
316 A type that can be used to indicate to type checkers
317 that the corresponding value has a value literally equivalent
318 to the provided parameter. For example:
320 var: Literal[4] = 4
322 The type checker understands that 'var' is literally equal to
323 the value 4 and no other value.
325 Literal[...] cannot be subclassed. There is no runtime
326 checking verifying that the parameter is actually a value
327 instead of a type.""")
330_overload_dummy = typing._overload_dummy
333if hasattr(typing, "get_overloads"): # 3.11+
334 overload = typing.overload
335 get_overloads = typing.get_overloads
336 clear_overloads = typing.clear_overloads
337else:
338 # {module: {qualname: {firstlineno: func}}}
339 _overload_registry = collections.defaultdict(
340 functools.partial(collections.defaultdict, dict)
341 )
343 def overload(func):
344 """Decorator for overloaded functions/methods.
346 In a stub file, place two or more stub definitions for the same
347 function in a row, each decorated with @overload. For example:
349 @overload
350 def utf8(value: None) -> None: ...
351 @overload
352 def utf8(value: bytes) -> bytes: ...
353 @overload
354 def utf8(value: str) -> bytes: ...
356 In a non-stub file (i.e. a regular .py file), do the same but
357 follow it with an implementation. The implementation should *not*
358 be decorated with @overload. For example:
360 @overload
361 def utf8(value: None) -> None: ...
362 @overload
363 def utf8(value: bytes) -> bytes: ...
364 @overload
365 def utf8(value: str) -> bytes: ...
366 def utf8(value):
367 # implementation goes here
369 The overloads for a function can be retrieved at runtime using the
370 get_overloads() function.
371 """
372 # classmethod and staticmethod
373 f = getattr(func, "__func__", func)
374 try:
375 _overload_registry[f.__module__][f.__qualname__][
376 f.__code__.co_firstlineno
377 ] = func
378 except AttributeError:
379 # Not a normal function; ignore.
380 pass
381 return _overload_dummy
383 def get_overloads(func):
384 """Return all defined overloads for *func* as a sequence."""
385 # classmethod and staticmethod
386 f = getattr(func, "__func__", func)
387 if f.__module__ not in _overload_registry:
388 return []
389 mod_dict = _overload_registry[f.__module__]
390 if f.__qualname__ not in mod_dict:
391 return []
392 return list(mod_dict[f.__qualname__].values())
394 def clear_overloads():
395 """Clear all overloads in the registry."""
396 _overload_registry.clear()
399# This is not a real generic class. Don't use outside annotations.
400Type = typing.Type
402# Various ABCs mimicking those in collections.abc.
403# A few are simply re-exported for completeness.
404Awaitable = typing.Awaitable
405Coroutine = typing.Coroutine
406AsyncIterable = typing.AsyncIterable
407AsyncIterator = typing.AsyncIterator
408Deque = typing.Deque
409ContextManager = typing.ContextManager
410AsyncContextManager = typing.AsyncContextManager
411DefaultDict = typing.DefaultDict
412OrderedDict = typing.OrderedDict
413Counter = typing.Counter
414ChainMap = typing.ChainMap
415AsyncGenerator = typing.AsyncGenerator
416Text = typing.Text
417TYPE_CHECKING = typing.TYPE_CHECKING
420_PROTO_ALLOWLIST = {
421 'collections.abc': [
422 'Callable', 'Awaitable', 'Iterable', 'Iterator', 'AsyncIterable',
423 'Hashable', 'Sized', 'Container', 'Collection', 'Reversible', 'Buffer',
424 ],
425 'contextlib': ['AbstractContextManager', 'AbstractAsyncContextManager'],
426 'typing_extensions': ['Buffer'],
427}
430_EXCLUDED_ATTRS = {
431 "__abstractmethods__", "__annotations__", "__weakref__", "_is_protocol",
432 "_is_runtime_protocol", "__dict__", "__slots__", "__parameters__",
433 "__orig_bases__", "__module__", "_MutableMapping__marker", "__doc__",
434 "__subclasshook__", "__orig_class__", "__init__", "__new__",
435 "__protocol_attrs__", "__non_callable_proto_members__",
436 "__match_args__",
437}
439if sys.version_info >= (3, 9):
440 _EXCLUDED_ATTRS.add("__class_getitem__")
442if sys.version_info >= (3, 12):
443 _EXCLUDED_ATTRS.add("__type_params__")
445_EXCLUDED_ATTRS = frozenset(_EXCLUDED_ATTRS)
448def _get_protocol_attrs(cls):
449 attrs = set()
450 for base in cls.__mro__[:-1]: # without object
451 if base.__name__ in {'Protocol', 'Generic'}:
452 continue
453 annotations = getattr(base, '__annotations__', {})
454 for attr in (*base.__dict__, *annotations):
455 if (not attr.startswith('_abc_') and attr not in _EXCLUDED_ATTRS):
456 attrs.add(attr)
457 return attrs
460def _caller(depth=2):
461 try:
462 return sys._getframe(depth).f_globals.get('__name__', '__main__')
463 except (AttributeError, ValueError): # For platforms without _getframe()
464 return None
467# `__match_args__` attribute was removed from protocol members in 3.13,
468# we want to backport this change to older Python versions.
469if sys.version_info >= (3, 13):
470 Protocol = typing.Protocol
471else:
472 def _allow_reckless_class_checks(depth=3):
473 """Allow instance and class checks for special stdlib modules.
474 The abc and functools modules indiscriminately call isinstance() and
475 issubclass() on the whole MRO of a user class, which may contain protocols.
476 """
477 return _caller(depth) in {'abc', 'functools', None}
479 def _no_init(self, *args, **kwargs):
480 if type(self)._is_protocol:
481 raise TypeError('Protocols cannot be instantiated')
483 def _type_check_issubclass_arg_1(arg):
484 """Raise TypeError if `arg` is not an instance of `type`
485 in `issubclass(arg, <protocol>)`.
487 In most cases, this is verified by type.__subclasscheck__.
488 Checking it again unnecessarily would slow down issubclass() checks,
489 so, we don't perform this check unless we absolutely have to.
491 For various error paths, however,
492 we want to ensure that *this* error message is shown to the user
493 where relevant, rather than a typing.py-specific error message.
494 """
495 if not isinstance(arg, type):
496 # Same error message as for issubclass(1, int).
497 raise TypeError('issubclass() arg 1 must be a class')
499 # Inheriting from typing._ProtocolMeta isn't actually desirable,
500 # but is necessary to allow typing.Protocol and typing_extensions.Protocol
501 # to mix without getting TypeErrors about "metaclass conflict"
502 class _ProtocolMeta(type(typing.Protocol)):
503 # This metaclass is somewhat unfortunate,
504 # but is necessary for several reasons...
505 #
506 # NOTE: DO NOT call super() in any methods in this class
507 # That would call the methods on typing._ProtocolMeta on Python 3.8-3.11
508 # and those are slow
509 def __new__(mcls, name, bases, namespace, **kwargs):
510 if name == "Protocol" and len(bases) < 2:
511 pass
512 elif {Protocol, typing.Protocol} & set(bases):
513 for base in bases:
514 if not (
515 base in {object, typing.Generic, Protocol, typing.Protocol}
516 or base.__name__ in _PROTO_ALLOWLIST.get(base.__module__, [])
517 or is_protocol(base)
518 ):
519 raise TypeError(
520 f"Protocols can only inherit from other protocols, "
521 f"got {base!r}"
522 )
523 return abc.ABCMeta.__new__(mcls, name, bases, namespace, **kwargs)
525 def __init__(cls, *args, **kwargs):
526 abc.ABCMeta.__init__(cls, *args, **kwargs)
527 if getattr(cls, "_is_protocol", False):
528 cls.__protocol_attrs__ = _get_protocol_attrs(cls)
530 def __subclasscheck__(cls, other):
531 if cls is Protocol:
532 return type.__subclasscheck__(cls, other)
533 if (
534 getattr(cls, '_is_protocol', False)
535 and not _allow_reckless_class_checks()
536 ):
537 if not getattr(cls, '_is_runtime_protocol', False):
538 _type_check_issubclass_arg_1(other)
539 raise TypeError(
540 "Instance and class checks can only be used with "
541 "@runtime_checkable protocols"
542 )
543 if (
544 # this attribute is set by @runtime_checkable:
545 cls.__non_callable_proto_members__
546 and cls.__dict__.get("__subclasshook__") is _proto_hook
547 ):
548 _type_check_issubclass_arg_1(other)
549 non_method_attrs = sorted(cls.__non_callable_proto_members__)
550 raise TypeError(
551 "Protocols with non-method members don't support issubclass()."
552 f" Non-method members: {str(non_method_attrs)[1:-1]}."
553 )
554 return abc.ABCMeta.__subclasscheck__(cls, other)
556 def __instancecheck__(cls, instance):
557 # We need this method for situations where attributes are
558 # assigned in __init__.
559 if cls is Protocol:
560 return type.__instancecheck__(cls, instance)
561 if not getattr(cls, "_is_protocol", False):
562 # i.e., it's a concrete subclass of a protocol
563 return abc.ABCMeta.__instancecheck__(cls, instance)
565 if (
566 not getattr(cls, '_is_runtime_protocol', False) and
567 not _allow_reckless_class_checks()
568 ):
569 raise TypeError("Instance and class checks can only be used with"
570 " @runtime_checkable protocols")
572 if abc.ABCMeta.__instancecheck__(cls, instance):
573 return True
575 for attr in cls.__protocol_attrs__:
576 try:
577 val = inspect.getattr_static(instance, attr)
578 except AttributeError:
579 break
580 # this attribute is set by @runtime_checkable:
581 if val is None and attr not in cls.__non_callable_proto_members__:
582 break
583 else:
584 return True
586 return False
588 def __eq__(cls, other):
589 # Hack so that typing.Generic.__class_getitem__
590 # treats typing_extensions.Protocol
591 # as equivalent to typing.Protocol
592 if abc.ABCMeta.__eq__(cls, other) is True:
593 return True
594 return cls is Protocol and other is typing.Protocol
596 # This has to be defined, or the abc-module cache
597 # complains about classes with this metaclass being unhashable,
598 # if we define only __eq__!
599 def __hash__(cls) -> int:
600 return type.__hash__(cls)
602 @classmethod
603 def _proto_hook(cls, other):
604 if not cls.__dict__.get('_is_protocol', False):
605 return NotImplemented
607 for attr in cls.__protocol_attrs__:
608 for base in other.__mro__:
609 # Check if the members appears in the class dictionary...
610 if attr in base.__dict__:
611 if base.__dict__[attr] is None:
612 return NotImplemented
613 break
615 # ...or in annotations, if it is a sub-protocol.
616 annotations = getattr(base, '__annotations__', {})
617 if (
618 isinstance(annotations, collections.abc.Mapping)
619 and attr in annotations
620 and is_protocol(other)
621 ):
622 break
623 else:
624 return NotImplemented
625 return True
627 class Protocol(typing.Generic, metaclass=_ProtocolMeta):
628 __doc__ = typing.Protocol.__doc__
629 __slots__ = ()
630 _is_protocol = True
631 _is_runtime_protocol = False
633 def __init_subclass__(cls, *args, **kwargs):
634 super().__init_subclass__(*args, **kwargs)
636 # Determine if this is a protocol or a concrete subclass.
637 if not cls.__dict__.get('_is_protocol', False):
638 cls._is_protocol = any(b is Protocol for b in cls.__bases__)
640 # Set (or override) the protocol subclass hook.
641 if '__subclasshook__' not in cls.__dict__:
642 cls.__subclasshook__ = _proto_hook
644 # Prohibit instantiation for protocol classes
645 if cls._is_protocol and cls.__init__ is Protocol.__init__:
646 cls.__init__ = _no_init
649if sys.version_info >= (3, 13):
650 runtime_checkable = typing.runtime_checkable
651else:
652 def runtime_checkable(cls):
653 """Mark a protocol class as a runtime protocol.
655 Such protocol can be used with isinstance() and issubclass().
656 Raise TypeError if applied to a non-protocol class.
657 This allows a simple-minded structural check very similar to
658 one trick ponies in collections.abc such as Iterable.
660 For example::
662 @runtime_checkable
663 class Closable(Protocol):
664 def close(self): ...
666 assert isinstance(open('/some/file'), Closable)
668 Warning: this will check only the presence of the required methods,
669 not their type signatures!
670 """
671 if not issubclass(cls, typing.Generic) or not getattr(cls, '_is_protocol', False):
672 raise TypeError('@runtime_checkable can be only applied to protocol classes,'
673 ' got %r' % cls)
674 cls._is_runtime_protocol = True
676 # Only execute the following block if it's a typing_extensions.Protocol class.
677 # typing.Protocol classes don't need it.
678 if isinstance(cls, _ProtocolMeta):
679 # PEP 544 prohibits using issubclass()
680 # with protocols that have non-method members.
681 # See gh-113320 for why we compute this attribute here,
682 # rather than in `_ProtocolMeta.__init__`
683 cls.__non_callable_proto_members__ = set()
684 for attr in cls.__protocol_attrs__:
685 try:
686 is_callable = callable(getattr(cls, attr, None))
687 except Exception as e:
688 raise TypeError(
689 f"Failed to determine whether protocol member {attr!r} "
690 "is a method member"
691 ) from e
692 else:
693 if not is_callable:
694 cls.__non_callable_proto_members__.add(attr)
696 return cls
699# The "runtime" alias exists for backwards compatibility.
700runtime = runtime_checkable
703# Our version of runtime-checkable protocols is faster on Python 3.8-3.11
704if sys.version_info >= (3, 12):
705 SupportsInt = typing.SupportsInt
706 SupportsFloat = typing.SupportsFloat
707 SupportsComplex = typing.SupportsComplex
708 SupportsBytes = typing.SupportsBytes
709 SupportsIndex = typing.SupportsIndex
710 SupportsAbs = typing.SupportsAbs
711 SupportsRound = typing.SupportsRound
712else:
713 @runtime_checkable
714 class SupportsInt(Protocol):
715 """An ABC with one abstract method __int__."""
716 __slots__ = ()
718 @abc.abstractmethod
719 def __int__(self) -> int:
720 pass
722 @runtime_checkable
723 class SupportsFloat(Protocol):
724 """An ABC with one abstract method __float__."""
725 __slots__ = ()
727 @abc.abstractmethod
728 def __float__(self) -> float:
729 pass
731 @runtime_checkable
732 class SupportsComplex(Protocol):
733 """An ABC with one abstract method __complex__."""
734 __slots__ = ()
736 @abc.abstractmethod
737 def __complex__(self) -> complex:
738 pass
740 @runtime_checkable
741 class SupportsBytes(Protocol):
742 """An ABC with one abstract method __bytes__."""
743 __slots__ = ()
745 @abc.abstractmethod
746 def __bytes__(self) -> bytes:
747 pass
749 @runtime_checkable
750 class SupportsIndex(Protocol):
751 __slots__ = ()
753 @abc.abstractmethod
754 def __index__(self) -> int:
755 pass
757 @runtime_checkable
758 class SupportsAbs(Protocol[T_co]):
759 """
760 An ABC with one abstract method __abs__ that is covariant in its return type.
761 """
762 __slots__ = ()
764 @abc.abstractmethod
765 def __abs__(self) -> T_co:
766 pass
768 @runtime_checkable
769 class SupportsRound(Protocol[T_co]):
770 """
771 An ABC with one abstract method __round__ that is covariant in its return type.
772 """
773 __slots__ = ()
775 @abc.abstractmethod
776 def __round__(self, ndigits: int = 0) -> T_co:
777 pass
780def _ensure_subclassable(mro_entries):
781 def inner(func):
782 if sys.implementation.name == "pypy" and sys.version_info < (3, 9):
783 cls_dict = {
784 "__call__": staticmethod(func),
785 "__mro_entries__": staticmethod(mro_entries)
786 }
787 t = type(func.__name__, (), cls_dict)
788 return functools.update_wrapper(t(), func)
789 else:
790 func.__mro_entries__ = mro_entries
791 return func
792 return inner
795# Update this to something like >=3.13.0b1 if and when
796# PEP 728 is implemented in CPython
797_PEP_728_IMPLEMENTED = False
799if _PEP_728_IMPLEMENTED:
800 # The standard library TypedDict in Python 3.8 does not store runtime information
801 # about which (if any) keys are optional. See https://bugs.python.org/issue38834
802 # The standard library TypedDict in Python 3.9.0/1 does not honour the "total"
803 # keyword with old-style TypedDict(). See https://bugs.python.org/issue42059
804 # The standard library TypedDict below Python 3.11 does not store runtime
805 # information about optional and required keys when using Required or NotRequired.
806 # Generic TypedDicts are also impossible using typing.TypedDict on Python <3.11.
807 # Aaaand on 3.12 we add __orig_bases__ to TypedDict
808 # to enable better runtime introspection.
809 # On 3.13 we deprecate some odd ways of creating TypedDicts.
810 # Also on 3.13, PEP 705 adds the ReadOnly[] qualifier.
811 # PEP 728 (still pending) makes more changes.
812 TypedDict = typing.TypedDict
813 _TypedDictMeta = typing._TypedDictMeta
814 is_typeddict = typing.is_typeddict
815else:
816 # 3.10.0 and later
817 _TAKES_MODULE = "module" in inspect.signature(typing._type_check).parameters
819 def _get_typeddict_qualifiers(annotation_type):
820 while True:
821 annotation_origin = get_origin(annotation_type)
822 if annotation_origin is Annotated:
823 annotation_args = get_args(annotation_type)
824 if annotation_args:
825 annotation_type = annotation_args[0]
826 else:
827 break
828 elif annotation_origin is Required:
829 yield Required
830 annotation_type, = get_args(annotation_type)
831 elif annotation_origin is NotRequired:
832 yield NotRequired
833 annotation_type, = get_args(annotation_type)
834 elif annotation_origin is ReadOnly:
835 yield ReadOnly
836 annotation_type, = get_args(annotation_type)
837 else:
838 break
840 class _TypedDictMeta(type):
841 def __new__(cls, name, bases, ns, *, total=True, closed=False):
842 """Create new typed dict class object.
844 This method is called when TypedDict is subclassed,
845 or when TypedDict is instantiated. This way
846 TypedDict supports all three syntax forms described in its docstring.
847 Subclasses and instances of TypedDict return actual dictionaries.
848 """
849 for base in bases:
850 if type(base) is not _TypedDictMeta and base is not typing.Generic:
851 raise TypeError('cannot inherit from both a TypedDict type '
852 'and a non-TypedDict base class')
854 if any(issubclass(b, typing.Generic) for b in bases):
855 generic_base = (typing.Generic,)
856 else:
857 generic_base = ()
859 # typing.py generally doesn't let you inherit from plain Generic, unless
860 # the name of the class happens to be "Protocol"
861 tp_dict = type.__new__(_TypedDictMeta, "Protocol", (*generic_base, dict), ns)
862 tp_dict.__name__ = name
863 if tp_dict.__qualname__ == "Protocol":
864 tp_dict.__qualname__ = name
866 if not hasattr(tp_dict, '__orig_bases__'):
867 tp_dict.__orig_bases__ = bases
869 annotations = {}
870 own_annotations = ns.get('__annotations__', {})
871 msg = "TypedDict('Name', {f0: t0, f1: t1, ...}); each t must be a type"
872 if _TAKES_MODULE:
873 own_annotations = {
874 n: typing._type_check(tp, msg, module=tp_dict.__module__)
875 for n, tp in own_annotations.items()
876 }
877 else:
878 own_annotations = {
879 n: typing._type_check(tp, msg)
880 for n, tp in own_annotations.items()
881 }
882 required_keys = set()
883 optional_keys = set()
884 readonly_keys = set()
885 mutable_keys = set()
886 extra_items_type = None
888 for base in bases:
889 base_dict = base.__dict__
891 annotations.update(base_dict.get('__annotations__', {}))
892 required_keys.update(base_dict.get('__required_keys__', ()))
893 optional_keys.update(base_dict.get('__optional_keys__', ()))
894 readonly_keys.update(base_dict.get('__readonly_keys__', ()))
895 mutable_keys.update(base_dict.get('__mutable_keys__', ()))
896 base_extra_items_type = base_dict.get('__extra_items__', None)
897 if base_extra_items_type is not None:
898 extra_items_type = base_extra_items_type
900 if closed and extra_items_type is None:
901 extra_items_type = Never
902 if closed and "__extra_items__" in own_annotations:
903 annotation_type = own_annotations.pop("__extra_items__")
904 qualifiers = set(_get_typeddict_qualifiers(annotation_type))
905 if Required in qualifiers:
906 raise TypeError(
907 "Special key __extra_items__ does not support "
908 "Required"
909 )
910 if NotRequired in qualifiers:
911 raise TypeError(
912 "Special key __extra_items__ does not support "
913 "NotRequired"
914 )
915 extra_items_type = annotation_type
917 annotations.update(own_annotations)
918 for annotation_key, annotation_type in own_annotations.items():
919 qualifiers = set(_get_typeddict_qualifiers(annotation_type))
921 if Required in qualifiers:
922 required_keys.add(annotation_key)
923 elif NotRequired in qualifiers:
924 optional_keys.add(annotation_key)
925 elif total:
926 required_keys.add(annotation_key)
927 else:
928 optional_keys.add(annotation_key)
929 if ReadOnly in qualifiers:
930 mutable_keys.discard(annotation_key)
931 readonly_keys.add(annotation_key)
932 else:
933 mutable_keys.add(annotation_key)
934 readonly_keys.discard(annotation_key)
936 tp_dict.__annotations__ = annotations
937 tp_dict.__required_keys__ = frozenset(required_keys)
938 tp_dict.__optional_keys__ = frozenset(optional_keys)
939 tp_dict.__readonly_keys__ = frozenset(readonly_keys)
940 tp_dict.__mutable_keys__ = frozenset(mutable_keys)
941 if not hasattr(tp_dict, '__total__'):
942 tp_dict.__total__ = total
943 tp_dict.__closed__ = closed
944 tp_dict.__extra_items__ = extra_items_type
945 return tp_dict
947 __call__ = dict # static method
949 def __subclasscheck__(cls, other):
950 # Typed dicts are only for static structural subtyping.
951 raise TypeError('TypedDict does not support instance and class checks')
953 __instancecheck__ = __subclasscheck__
955 _TypedDict = type.__new__(_TypedDictMeta, 'TypedDict', (), {})
957 @_ensure_subclassable(lambda bases: (_TypedDict,))
958 def TypedDict(typename, fields=_marker, /, *, total=True, closed=False, **kwargs):
959 """A simple typed namespace. At runtime it is equivalent to a plain dict.
961 TypedDict creates a dictionary type such that a type checker will expect all
962 instances to have a certain set of keys, where each key is
963 associated with a value of a consistent type. This expectation
964 is not checked at runtime.
966 Usage::
968 class Point2D(TypedDict):
969 x: int
970 y: int
971 label: str
973 a: Point2D = {'x': 1, 'y': 2, 'label': 'good'} # OK
974 b: Point2D = {'z': 3, 'label': 'bad'} # Fails type check
976 assert Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first')
978 The type info can be accessed via the Point2D.__annotations__ dict, and
979 the Point2D.__required_keys__ and Point2D.__optional_keys__ frozensets.
980 TypedDict supports an additional equivalent form::
982 Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str})
984 By default, all keys must be present in a TypedDict. It is possible
985 to override this by specifying totality::
987 class Point2D(TypedDict, total=False):
988 x: int
989 y: int
991 This means that a Point2D TypedDict can have any of the keys omitted. A type
992 checker is only expected to support a literal False or True as the value of
993 the total argument. True is the default, and makes all items defined in the
994 class body be required.
996 The Required and NotRequired special forms can also be used to mark
997 individual keys as being required or not required::
999 class Point2D(TypedDict):
1000 x: int # the "x" key must always be present (Required is the default)
1001 y: NotRequired[int] # the "y" key can be omitted
1003 See PEP 655 for more details on Required and NotRequired.
1004 """
1005 if fields is _marker or fields is None:
1006 if fields is _marker:
1007 deprecated_thing = "Failing to pass a value for the 'fields' parameter"
1008 else:
1009 deprecated_thing = "Passing `None` as the 'fields' parameter"
1011 example = f"`{typename} = TypedDict({typename!r}, {{}})`"
1012 deprecation_msg = (
1013 f"{deprecated_thing} is deprecated and will be disallowed in "
1014 "Python 3.15. To create a TypedDict class with 0 fields "
1015 "using the functional syntax, pass an empty dictionary, e.g. "
1016 ) + example + "."
1017 warnings.warn(deprecation_msg, DeprecationWarning, stacklevel=2)
1018 if closed is not False and closed is not True:
1019 kwargs["closed"] = closed
1020 closed = False
1021 fields = kwargs
1022 elif kwargs:
1023 raise TypeError("TypedDict takes either a dict or keyword arguments,"
1024 " but not both")
1025 if kwargs:
1026 if sys.version_info >= (3, 13):
1027 raise TypeError("TypedDict takes no keyword arguments")
1028 warnings.warn(
1029 "The kwargs-based syntax for TypedDict definitions is deprecated "
1030 "in Python 3.11, will be removed in Python 3.13, and may not be "
1031 "understood by third-party type checkers.",
1032 DeprecationWarning,
1033 stacklevel=2,
1034 )
1036 ns = {'__annotations__': dict(fields)}
1037 module = _caller()
1038 if module is not None:
1039 # Setting correct module is necessary to make typed dict classes pickleable.
1040 ns['__module__'] = module
1042 td = _TypedDictMeta(typename, (), ns, total=total, closed=closed)
1043 td.__orig_bases__ = (TypedDict,)
1044 return td
1046 if hasattr(typing, "_TypedDictMeta"):
1047 _TYPEDDICT_TYPES = (typing._TypedDictMeta, _TypedDictMeta)
1048 else:
1049 _TYPEDDICT_TYPES = (_TypedDictMeta,)
1051 def is_typeddict(tp):
1052 """Check if an annotation is a TypedDict class
1054 For example::
1055 class Film(TypedDict):
1056 title: str
1057 year: int
1059 is_typeddict(Film) # => True
1060 is_typeddict(Union[list, str]) # => False
1061 """
1062 # On 3.8, this would otherwise return True
1063 if hasattr(typing, "TypedDict") and tp is typing.TypedDict:
1064 return False
1065 return isinstance(tp, _TYPEDDICT_TYPES)
1068if hasattr(typing, "assert_type"):
1069 assert_type = typing.assert_type
1071else:
1072 def assert_type(val, typ, /):
1073 """Assert (to the type checker) that the value is of the given type.
1075 When the type checker encounters a call to assert_type(), it
1076 emits an error if the value is not of the specified type::
1078 def greet(name: str) -> None:
1079 assert_type(name, str) # ok
1080 assert_type(name, int) # type checker error
1082 At runtime this returns the first argument unchanged and otherwise
1083 does nothing.
1084 """
1085 return val
1088if hasattr(typing, "ReadOnly"): # 3.13+
1089 get_type_hints = typing.get_type_hints
1090else: # <=3.13
1091 # replaces _strip_annotations()
1092 def _strip_extras(t):
1093 """Strips Annotated, Required and NotRequired from a given type."""
1094 if isinstance(t, _AnnotatedAlias):
1095 return _strip_extras(t.__origin__)
1096 if hasattr(t, "__origin__") and t.__origin__ in (Required, NotRequired, ReadOnly):
1097 return _strip_extras(t.__args__[0])
1098 if isinstance(t, typing._GenericAlias):
1099 stripped_args = tuple(_strip_extras(a) for a in t.__args__)
1100 if stripped_args == t.__args__:
1101 return t
1102 return t.copy_with(stripped_args)
1103 if hasattr(_types, "GenericAlias") and isinstance(t, _types.GenericAlias):
1104 stripped_args = tuple(_strip_extras(a) for a in t.__args__)
1105 if stripped_args == t.__args__:
1106 return t
1107 return _types.GenericAlias(t.__origin__, stripped_args)
1108 if hasattr(_types, "UnionType") and isinstance(t, _types.UnionType):
1109 stripped_args = tuple(_strip_extras(a) for a in t.__args__)
1110 if stripped_args == t.__args__:
1111 return t
1112 return functools.reduce(operator.or_, stripped_args)
1114 return t
1116 def get_type_hints(obj, globalns=None, localns=None, include_extras=False):
1117 """Return type hints for an object.
1119 This is often the same as obj.__annotations__, but it handles
1120 forward references encoded as string literals, adds Optional[t] if a
1121 default value equal to None is set and recursively replaces all
1122 'Annotated[T, ...]', 'Required[T]' or 'NotRequired[T]' with 'T'
1123 (unless 'include_extras=True').
1125 The argument may be a module, class, method, or function. The annotations
1126 are returned as a dictionary. For classes, annotations include also
1127 inherited members.
1129 TypeError is raised if the argument is not of a type that can contain
1130 annotations, and an empty dictionary is returned if no annotations are
1131 present.
1133 BEWARE -- the behavior of globalns and localns is counterintuitive
1134 (unless you are familiar with how eval() and exec() work). The
1135 search order is locals first, then globals.
1137 - If no dict arguments are passed, an attempt is made to use the
1138 globals from obj (or the respective module's globals for classes),
1139 and these are also used as the locals. If the object does not appear
1140 to have globals, an empty dictionary is used.
1142 - If one dict argument is passed, it is used for both globals and
1143 locals.
1145 - If two dict arguments are passed, they specify globals and
1146 locals, respectively.
1147 """
1148 if hasattr(typing, "Annotated"): # 3.9+
1149 hint = typing.get_type_hints(
1150 obj, globalns=globalns, localns=localns, include_extras=True
1151 )
1152 else: # 3.8
1153 hint = typing.get_type_hints(obj, globalns=globalns, localns=localns)
1154 if include_extras:
1155 return hint
1156 return {k: _strip_extras(t) for k, t in hint.items()}
1159# Python 3.9+ has PEP 593 (Annotated)
1160if hasattr(typing, 'Annotated'):
1161 Annotated = typing.Annotated
1162 # Not exported and not a public API, but needed for get_origin() and get_args()
1163 # to work.
1164 _AnnotatedAlias = typing._AnnotatedAlias
1165# 3.8
1166else:
1167 class _AnnotatedAlias(typing._GenericAlias, _root=True):
1168 """Runtime representation of an annotated type.
1170 At its core 'Annotated[t, dec1, dec2, ...]' is an alias for the type 't'
1171 with extra annotations. The alias behaves like a normal typing alias,
1172 instantiating is the same as instantiating the underlying type, binding
1173 it to types is also the same.
1174 """
1175 def __init__(self, origin, metadata):
1176 if isinstance(origin, _AnnotatedAlias):
1177 metadata = origin.__metadata__ + metadata
1178 origin = origin.__origin__
1179 super().__init__(origin, origin)
1180 self.__metadata__ = metadata
1182 def copy_with(self, params):
1183 assert len(params) == 1
1184 new_type = params[0]
1185 return _AnnotatedAlias(new_type, self.__metadata__)
1187 def __repr__(self):
1188 return (f"typing_extensions.Annotated[{typing._type_repr(self.__origin__)}, "
1189 f"{', '.join(repr(a) for a in self.__metadata__)}]")
1191 def __reduce__(self):
1192 return operator.getitem, (
1193 Annotated, (self.__origin__,) + self.__metadata__
1194 )
1196 def __eq__(self, other):
1197 if not isinstance(other, _AnnotatedAlias):
1198 return NotImplemented
1199 if self.__origin__ != other.__origin__:
1200 return False
1201 return self.__metadata__ == other.__metadata__
1203 def __hash__(self):
1204 return hash((self.__origin__, self.__metadata__))
1206 class Annotated:
1207 """Add context specific metadata to a type.
1209 Example: Annotated[int, runtime_check.Unsigned] indicates to the
1210 hypothetical runtime_check module that this type is an unsigned int.
1211 Every other consumer of this type can ignore this metadata and treat
1212 this type as int.
1214 The first argument to Annotated must be a valid type (and will be in
1215 the __origin__ field), the remaining arguments are kept as a tuple in
1216 the __extra__ field.
1218 Details:
1220 - It's an error to call `Annotated` with less than two arguments.
1221 - Nested Annotated are flattened::
1223 Annotated[Annotated[T, Ann1, Ann2], Ann3] == Annotated[T, Ann1, Ann2, Ann3]
1225 - Instantiating an annotated type is equivalent to instantiating the
1226 underlying type::
1228 Annotated[C, Ann1](5) == C(5)
1230 - Annotated can be used as a generic type alias::
1232 Optimized = Annotated[T, runtime.Optimize()]
1233 Optimized[int] == Annotated[int, runtime.Optimize()]
1235 OptimizedList = Annotated[List[T], runtime.Optimize()]
1236 OptimizedList[int] == Annotated[List[int], runtime.Optimize()]
1237 """
1239 __slots__ = ()
1241 def __new__(cls, *args, **kwargs):
1242 raise TypeError("Type Annotated cannot be instantiated.")
1244 @typing._tp_cache
1245 def __class_getitem__(cls, params):
1246 if not isinstance(params, tuple) or len(params) < 2:
1247 raise TypeError("Annotated[...] should be used "
1248 "with at least two arguments (a type and an "
1249 "annotation).")
1250 allowed_special_forms = (ClassVar, Final)
1251 if get_origin(params[0]) in allowed_special_forms:
1252 origin = params[0]
1253 else:
1254 msg = "Annotated[t, ...]: t must be a type."
1255 origin = typing._type_check(params[0], msg)
1256 metadata = tuple(params[1:])
1257 return _AnnotatedAlias(origin, metadata)
1259 def __init_subclass__(cls, *args, **kwargs):
1260 raise TypeError(
1261 f"Cannot subclass {cls.__module__}.Annotated"
1262 )
1264# Python 3.8 has get_origin() and get_args() but those implementations aren't
1265# Annotated-aware, so we can't use those. Python 3.9's versions don't support
1266# ParamSpecArgs and ParamSpecKwargs, so only Python 3.10's versions will do.
1267if sys.version_info[:2] >= (3, 10):
1268 get_origin = typing.get_origin
1269 get_args = typing.get_args
1270# 3.8-3.9
1271else:
1272 try:
1273 # 3.9+
1274 from typing import _BaseGenericAlias
1275 except ImportError:
1276 _BaseGenericAlias = typing._GenericAlias
1277 try:
1278 # 3.9+
1279 from typing import GenericAlias as _typing_GenericAlias
1280 except ImportError:
1281 _typing_GenericAlias = typing._GenericAlias
1283 def get_origin(tp):
1284 """Get the unsubscripted version of a type.
1286 This supports generic types, Callable, Tuple, Union, Literal, Final, ClassVar
1287 and Annotated. Return None for unsupported types. Examples::
1289 get_origin(Literal[42]) is Literal
1290 get_origin(int) is None
1291 get_origin(ClassVar[int]) is ClassVar
1292 get_origin(Generic) is Generic
1293 get_origin(Generic[T]) is Generic
1294 get_origin(Union[T, int]) is Union
1295 get_origin(List[Tuple[T, T]][int]) == list
1296 get_origin(P.args) is P
1297 """
1298 if isinstance(tp, _AnnotatedAlias):
1299 return Annotated
1300 if isinstance(tp, (typing._GenericAlias, _typing_GenericAlias, _BaseGenericAlias,
1301 ParamSpecArgs, ParamSpecKwargs)):
1302 return tp.__origin__
1303 if tp is typing.Generic:
1304 return typing.Generic
1305 return None
1307 def get_args(tp):
1308 """Get type arguments with all substitutions performed.
1310 For unions, basic simplifications used by Union constructor are performed.
1311 Examples::
1312 get_args(Dict[str, int]) == (str, int)
1313 get_args(int) == ()
1314 get_args(Union[int, Union[T, int], str][int]) == (int, str)
1315 get_args(Union[int, Tuple[T, int]][str]) == (int, Tuple[str, int])
1316 get_args(Callable[[], T][int]) == ([], int)
1317 """
1318 if isinstance(tp, _AnnotatedAlias):
1319 return (tp.__origin__,) + tp.__metadata__
1320 if isinstance(tp, (typing._GenericAlias, _typing_GenericAlias)):
1321 if getattr(tp, "_special", False):
1322 return ()
1323 res = tp.__args__
1324 if get_origin(tp) is collections.abc.Callable and res[0] is not Ellipsis:
1325 res = (list(res[:-1]), res[-1])
1326 return res
1327 return ()
1330# 3.10+
1331if hasattr(typing, 'TypeAlias'):
1332 TypeAlias = typing.TypeAlias
1333# 3.9
1334elif sys.version_info[:2] >= (3, 9):
1335 @_ExtensionsSpecialForm
1336 def TypeAlias(self, parameters):
1337 """Special marker indicating that an assignment should
1338 be recognized as a proper type alias definition by type
1339 checkers.
1341 For example::
1343 Predicate: TypeAlias = Callable[..., bool]
1345 It's invalid when used anywhere except as in the example above.
1346 """
1347 raise TypeError(f"{self} is not subscriptable")
1348# 3.8
1349else:
1350 TypeAlias = _ExtensionsSpecialForm(
1351 'TypeAlias',
1352 doc="""Special marker indicating that an assignment should
1353 be recognized as a proper type alias definition by type
1354 checkers.
1356 For example::
1358 Predicate: TypeAlias = Callable[..., bool]
1360 It's invalid when used anywhere except as in the example
1361 above."""
1362 )
1365def _set_default(type_param, default):
1366 if isinstance(default, (tuple, list)):
1367 type_param.__default__ = tuple((typing._type_check(d, "Default must be a type")
1368 for d in default))
1369 elif default != _marker:
1370 if isinstance(type_param, ParamSpec) and default is ...: # ... not valid <3.11
1371 type_param.__default__ = default
1372 else:
1373 type_param.__default__ = typing._type_check(default, "Default must be a type")
1374 else:
1375 type_param.__default__ = None
1378def _set_module(typevarlike):
1379 # for pickling:
1380 def_mod = _caller(depth=3)
1381 if def_mod != 'typing_extensions':
1382 typevarlike.__module__ = def_mod
1385class _DefaultMixin:
1386 """Mixin for TypeVarLike defaults."""
1388 __slots__ = ()
1389 __init__ = _set_default
1392# Classes using this metaclass must provide a _backported_typevarlike ClassVar
1393class _TypeVarLikeMeta(type):
1394 def __instancecheck__(cls, __instance: Any) -> bool:
1395 return isinstance(__instance, cls._backported_typevarlike)
1398# Add default and infer_variance parameters from PEP 696 and 695
1399class TypeVar(metaclass=_TypeVarLikeMeta):
1400 """Type variable."""
1402 _backported_typevarlike = typing.TypeVar
1404 def __new__(cls, name, *constraints, bound=None,
1405 covariant=False, contravariant=False,
1406 default=_marker, infer_variance=False):
1407 if hasattr(typing, "TypeAliasType"):
1408 # PEP 695 implemented (3.12+), can pass infer_variance to typing.TypeVar
1409 typevar = typing.TypeVar(name, *constraints, bound=bound,
1410 covariant=covariant, contravariant=contravariant,
1411 infer_variance=infer_variance)
1412 else:
1413 typevar = typing.TypeVar(name, *constraints, bound=bound,
1414 covariant=covariant, contravariant=contravariant)
1415 if infer_variance and (covariant or contravariant):
1416 raise ValueError("Variance cannot be specified with infer_variance.")
1417 typevar.__infer_variance__ = infer_variance
1418 _set_default(typevar, default)
1419 _set_module(typevar)
1420 return typevar
1422 def __init_subclass__(cls) -> None:
1423 raise TypeError(f"type '{__name__}.TypeVar' is not an acceptable base type")
1426# Python 3.10+ has PEP 612
1427if hasattr(typing, 'ParamSpecArgs'):
1428 ParamSpecArgs = typing.ParamSpecArgs
1429 ParamSpecKwargs = typing.ParamSpecKwargs
1430# 3.8-3.9
1431else:
1432 class _Immutable:
1433 """Mixin to indicate that object should not be copied."""
1434 __slots__ = ()
1436 def __copy__(self):
1437 return self
1439 def __deepcopy__(self, memo):
1440 return self
1442 class ParamSpecArgs(_Immutable):
1443 """The args for a ParamSpec object.
1445 Given a ParamSpec object P, P.args is an instance of ParamSpecArgs.
1447 ParamSpecArgs objects have a reference back to their ParamSpec:
1449 P.args.__origin__ is P
1451 This type is meant for runtime introspection and has no special meaning to
1452 static type checkers.
1453 """
1454 def __init__(self, origin):
1455 self.__origin__ = origin
1457 def __repr__(self):
1458 return f"{self.__origin__.__name__}.args"
1460 def __eq__(self, other):
1461 if not isinstance(other, ParamSpecArgs):
1462 return NotImplemented
1463 return self.__origin__ == other.__origin__
1465 class ParamSpecKwargs(_Immutable):
1466 """The kwargs for a ParamSpec object.
1468 Given a ParamSpec object P, P.kwargs is an instance of ParamSpecKwargs.
1470 ParamSpecKwargs objects have a reference back to their ParamSpec:
1472 P.kwargs.__origin__ is P
1474 This type is meant for runtime introspection and has no special meaning to
1475 static type checkers.
1476 """
1477 def __init__(self, origin):
1478 self.__origin__ = origin
1480 def __repr__(self):
1481 return f"{self.__origin__.__name__}.kwargs"
1483 def __eq__(self, other):
1484 if not isinstance(other, ParamSpecKwargs):
1485 return NotImplemented
1486 return self.__origin__ == other.__origin__
1488# 3.10+
1489if hasattr(typing, 'ParamSpec'):
1491 # Add default parameter - PEP 696
1492 class ParamSpec(metaclass=_TypeVarLikeMeta):
1493 """Parameter specification."""
1495 _backported_typevarlike = typing.ParamSpec
1497 def __new__(cls, name, *, bound=None,
1498 covariant=False, contravariant=False,
1499 infer_variance=False, default=_marker):
1500 if hasattr(typing, "TypeAliasType"):
1501 # PEP 695 implemented, can pass infer_variance to typing.TypeVar
1502 paramspec = typing.ParamSpec(name, bound=bound,
1503 covariant=covariant,
1504 contravariant=contravariant,
1505 infer_variance=infer_variance)
1506 else:
1507 paramspec = typing.ParamSpec(name, bound=bound,
1508 covariant=covariant,
1509 contravariant=contravariant)
1510 paramspec.__infer_variance__ = infer_variance
1512 _set_default(paramspec, default)
1513 _set_module(paramspec)
1514 return paramspec
1516 def __init_subclass__(cls) -> None:
1517 raise TypeError(f"type '{__name__}.ParamSpec' is not an acceptable base type")
1519# 3.8-3.9
1520else:
1522 # Inherits from list as a workaround for Callable checks in Python < 3.9.2.
1523 class ParamSpec(list, _DefaultMixin):
1524 """Parameter specification variable.
1526 Usage::
1528 P = ParamSpec('P')
1530 Parameter specification variables exist primarily for the benefit of static
1531 type checkers. They are used to forward the parameter types of one
1532 callable to another callable, a pattern commonly found in higher order
1533 functions and decorators. They are only valid when used in ``Concatenate``,
1534 or s the first argument to ``Callable``. In Python 3.10 and higher,
1535 they are also supported in user-defined Generics at runtime.
1536 See class Generic for more information on generic types. An
1537 example for annotating a decorator::
1539 T = TypeVar('T')
1540 P = ParamSpec('P')
1542 def add_logging(f: Callable[P, T]) -> Callable[P, T]:
1543 '''A type-safe decorator to add logging to a function.'''
1544 def inner(*args: P.args, **kwargs: P.kwargs) -> T:
1545 logging.info(f'{f.__name__} was called')
1546 return f(*args, **kwargs)
1547 return inner
1549 @add_logging
1550 def add_two(x: float, y: float) -> float:
1551 '''Add two numbers together.'''
1552 return x + y
1554 Parameter specification variables defined with covariant=True or
1555 contravariant=True can be used to declare covariant or contravariant
1556 generic types. These keyword arguments are valid, but their actual semantics
1557 are yet to be decided. See PEP 612 for details.
1559 Parameter specification variables can be introspected. e.g.:
1561 P.__name__ == 'T'
1562 P.__bound__ == None
1563 P.__covariant__ == False
1564 P.__contravariant__ == False
1566 Note that only parameter specification variables defined in global scope can
1567 be pickled.
1568 """
1570 # Trick Generic __parameters__.
1571 __class__ = typing.TypeVar
1573 @property
1574 def args(self):
1575 return ParamSpecArgs(self)
1577 @property
1578 def kwargs(self):
1579 return ParamSpecKwargs(self)
1581 def __init__(self, name, *, bound=None, covariant=False, contravariant=False,
1582 infer_variance=False, default=_marker):
1583 super().__init__([self])
1584 self.__name__ = name
1585 self.__covariant__ = bool(covariant)
1586 self.__contravariant__ = bool(contravariant)
1587 self.__infer_variance__ = bool(infer_variance)
1588 if bound:
1589 self.__bound__ = typing._type_check(bound, 'Bound must be a type.')
1590 else:
1591 self.__bound__ = None
1592 _DefaultMixin.__init__(self, default)
1594 # for pickling:
1595 def_mod = _caller()
1596 if def_mod != 'typing_extensions':
1597 self.__module__ = def_mod
1599 def __repr__(self):
1600 if self.__infer_variance__:
1601 prefix = ''
1602 elif self.__covariant__:
1603 prefix = '+'
1604 elif self.__contravariant__:
1605 prefix = '-'
1606 else:
1607 prefix = '~'
1608 return prefix + self.__name__
1610 def __hash__(self):
1611 return object.__hash__(self)
1613 def __eq__(self, other):
1614 return self is other
1616 def __reduce__(self):
1617 return self.__name__
1619 # Hack to get typing._type_check to pass.
1620 def __call__(self, *args, **kwargs):
1621 pass
1624# 3.8-3.9
1625if not hasattr(typing, 'Concatenate'):
1626 # Inherits from list as a workaround for Callable checks in Python < 3.9.2.
1627 class _ConcatenateGenericAlias(list):
1629 # Trick Generic into looking into this for __parameters__.
1630 __class__ = typing._GenericAlias
1632 # Flag in 3.8.
1633 _special = False
1635 def __init__(self, origin, args):
1636 super().__init__(args)
1637 self.__origin__ = origin
1638 self.__args__ = args
1640 def __repr__(self):
1641 _type_repr = typing._type_repr
1642 return (f'{_type_repr(self.__origin__)}'
1643 f'[{", ".join(_type_repr(arg) for arg in self.__args__)}]')
1645 def __hash__(self):
1646 return hash((self.__origin__, self.__args__))
1648 # Hack to get typing._type_check to pass in Generic.
1649 def __call__(self, *args, **kwargs):
1650 pass
1652 @property
1653 def __parameters__(self):
1654 return tuple(
1655 tp for tp in self.__args__ if isinstance(tp, (typing.TypeVar, ParamSpec))
1656 )
1659# 3.8-3.9
1660@typing._tp_cache
1661def _concatenate_getitem(self, parameters):
1662 if parameters == ():
1663 raise TypeError("Cannot take a Concatenate of no types.")
1664 if not isinstance(parameters, tuple):
1665 parameters = (parameters,)
1666 if not isinstance(parameters[-1], ParamSpec):
1667 raise TypeError("The last parameter to Concatenate should be a "
1668 "ParamSpec variable.")
1669 msg = "Concatenate[arg, ...]: each arg must be a type."
1670 parameters = tuple(typing._type_check(p, msg) for p in parameters)
1671 return _ConcatenateGenericAlias(self, parameters)
1674# 3.10+
1675if hasattr(typing, 'Concatenate'):
1676 Concatenate = typing.Concatenate
1677 _ConcatenateGenericAlias = typing._ConcatenateGenericAlias # noqa: F811
1678# 3.9
1679elif sys.version_info[:2] >= (3, 9):
1680 @_ExtensionsSpecialForm
1681 def Concatenate(self, parameters):
1682 """Used in conjunction with ``ParamSpec`` and ``Callable`` to represent a
1683 higher order function which adds, removes or transforms parameters of a
1684 callable.
1686 For example::
1688 Callable[Concatenate[int, P], int]
1690 See PEP 612 for detailed information.
1691 """
1692 return _concatenate_getitem(self, parameters)
1693# 3.8
1694else:
1695 class _ConcatenateForm(_ExtensionsSpecialForm, _root=True):
1696 def __getitem__(self, parameters):
1697 return _concatenate_getitem(self, parameters)
1699 Concatenate = _ConcatenateForm(
1700 'Concatenate',
1701 doc="""Used in conjunction with ``ParamSpec`` and ``Callable`` to represent a
1702 higher order function which adds, removes or transforms parameters of a
1703 callable.
1705 For example::
1707 Callable[Concatenate[int, P], int]
1709 See PEP 612 for detailed information.
1710 """)
1712# 3.10+
1713if hasattr(typing, 'TypeGuard'):
1714 TypeGuard = typing.TypeGuard
1715# 3.9
1716elif sys.version_info[:2] >= (3, 9):
1717 @_ExtensionsSpecialForm
1718 def TypeGuard(self, parameters):
1719 """Special typing form used to annotate the return type of a user-defined
1720 type guard function. ``TypeGuard`` only accepts a single type argument.
1721 At runtime, functions marked this way should return a boolean.
1723 ``TypeGuard`` aims to benefit *type narrowing* -- a technique used by static
1724 type checkers to determine a more precise type of an expression within a
1725 program's code flow. Usually type narrowing is done by analyzing
1726 conditional code flow and applying the narrowing to a block of code. The
1727 conditional expression here is sometimes referred to as a "type guard".
1729 Sometimes it would be convenient to use a user-defined boolean function
1730 as a type guard. Such a function should use ``TypeGuard[...]`` as its
1731 return type to alert static type checkers to this intention.
1733 Using ``-> TypeGuard`` tells the static type checker that for a given
1734 function:
1736 1. The return value is a boolean.
1737 2. If the return value is ``True``, the type of its argument
1738 is the type inside ``TypeGuard``.
1740 For example::
1742 def is_str(val: Union[str, float]):
1743 # "isinstance" type guard
1744 if isinstance(val, str):
1745 # Type of ``val`` is narrowed to ``str``
1746 ...
1747 else:
1748 # Else, type of ``val`` is narrowed to ``float``.
1749 ...
1751 Strict type narrowing is not enforced -- ``TypeB`` need not be a narrower
1752 form of ``TypeA`` (it can even be a wider form) and this may lead to
1753 type-unsafe results. The main reason is to allow for things like
1754 narrowing ``List[object]`` to ``List[str]`` even though the latter is not
1755 a subtype of the former, since ``List`` is invariant. The responsibility of
1756 writing type-safe type guards is left to the user.
1758 ``TypeGuard`` also works with type variables. For more information, see
1759 PEP 647 (User-Defined Type Guards).
1760 """
1761 item = typing._type_check(parameters, f'{self} accepts only a single type.')
1762 return typing._GenericAlias(self, (item,))
1763# 3.8
1764else:
1765 class _TypeGuardForm(_ExtensionsSpecialForm, _root=True):
1766 def __getitem__(self, parameters):
1767 item = typing._type_check(parameters,
1768 f'{self._name} accepts only a single type')
1769 return typing._GenericAlias(self, (item,))
1771 TypeGuard = _TypeGuardForm(
1772 'TypeGuard',
1773 doc="""Special typing form used to annotate the return type of a user-defined
1774 type guard function. ``TypeGuard`` only accepts a single type argument.
1775 At runtime, functions marked this way should return a boolean.
1777 ``TypeGuard`` aims to benefit *type narrowing* -- a technique used by static
1778 type checkers to determine a more precise type of an expression within a
1779 program's code flow. Usually type narrowing is done by analyzing
1780 conditional code flow and applying the narrowing to a block of code. The
1781 conditional expression here is sometimes referred to as a "type guard".
1783 Sometimes it would be convenient to use a user-defined boolean function
1784 as a type guard. Such a function should use ``TypeGuard[...]`` as its
1785 return type to alert static type checkers to this intention.
1787 Using ``-> TypeGuard`` tells the static type checker that for a given
1788 function:
1790 1. The return value is a boolean.
1791 2. If the return value is ``True``, the type of its argument
1792 is the type inside ``TypeGuard``.
1794 For example::
1796 def is_str(val: Union[str, float]):
1797 # "isinstance" type guard
1798 if isinstance(val, str):
1799 # Type of ``val`` is narrowed to ``str``
1800 ...
1801 else:
1802 # Else, type of ``val`` is narrowed to ``float``.
1803 ...
1805 Strict type narrowing is not enforced -- ``TypeB`` need not be a narrower
1806 form of ``TypeA`` (it can even be a wider form) and this may lead to
1807 type-unsafe results. The main reason is to allow for things like
1808 narrowing ``List[object]`` to ``List[str]`` even though the latter is not
1809 a subtype of the former, since ``List`` is invariant. The responsibility of
1810 writing type-safe type guards is left to the user.
1812 ``TypeGuard`` also works with type variables. For more information, see
1813 PEP 647 (User-Defined Type Guards).
1814 """)
1816# 3.13+
1817if hasattr(typing, 'TypeIs'):
1818 TypeIs = typing.TypeIs
1819# 3.9
1820elif sys.version_info[:2] >= (3, 9):
1821 @_ExtensionsSpecialForm
1822 def TypeIs(self, parameters):
1823 """Special typing form used to annotate the return type of a user-defined
1824 type narrower function. ``TypeIs`` only accepts a single type argument.
1825 At runtime, functions marked this way should return a boolean.
1827 ``TypeIs`` aims to benefit *type narrowing* -- a technique used by static
1828 type checkers to determine a more precise type of an expression within a
1829 program's code flow. Usually type narrowing is done by analyzing
1830 conditional code flow and applying the narrowing to a block of code. The
1831 conditional expression here is sometimes referred to as a "type guard".
1833 Sometimes it would be convenient to use a user-defined boolean function
1834 as a type guard. Such a function should use ``TypeIs[...]`` as its
1835 return type to alert static type checkers to this intention.
1837 Using ``-> TypeIs`` tells the static type checker that for a given
1838 function:
1840 1. The return value is a boolean.
1841 2. If the return value is ``True``, the type of its argument
1842 is the intersection of the type inside ``TypeGuard`` and the argument's
1843 previously known type.
1845 For example::
1847 def is_awaitable(val: object) -> TypeIs[Awaitable[Any]]:
1848 return hasattr(val, '__await__')
1850 def f(val: Union[int, Awaitable[int]]) -> int:
1851 if is_awaitable(val):
1852 assert_type(val, Awaitable[int])
1853 else:
1854 assert_type(val, int)
1856 ``TypeIs`` also works with type variables. For more information, see
1857 PEP 742 (Narrowing types with TypeIs).
1858 """
1859 item = typing._type_check(parameters, f'{self} accepts only a single type.')
1860 return typing._GenericAlias(self, (item,))
1861# 3.8
1862else:
1863 class _TypeIsForm(_ExtensionsSpecialForm, _root=True):
1864 def __getitem__(self, parameters):
1865 item = typing._type_check(parameters,
1866 f'{self._name} accepts only a single type')
1867 return typing._GenericAlias(self, (item,))
1869 TypeIs = _TypeIsForm(
1870 'TypeIs',
1871 doc="""Special typing form used to annotate the return type of a user-defined
1872 type narrower function. ``TypeIs`` only accepts a single type argument.
1873 At runtime, functions marked this way should return a boolean.
1875 ``TypeIs`` aims to benefit *type narrowing* -- a technique used by static
1876 type checkers to determine a more precise type of an expression within a
1877 program's code flow. Usually type narrowing is done by analyzing
1878 conditional code flow and applying the narrowing to a block of code. The
1879 conditional expression here is sometimes referred to as a "type guard".
1881 Sometimes it would be convenient to use a user-defined boolean function
1882 as a type guard. Such a function should use ``TypeIs[...]`` as its
1883 return type to alert static type checkers to this intention.
1885 Using ``-> TypeIs`` tells the static type checker that for a given
1886 function:
1888 1. The return value is a boolean.
1889 2. If the return value is ``True``, the type of its argument
1890 is the intersection of the type inside ``TypeGuard`` and the argument's
1891 previously known type.
1893 For example::
1895 def is_awaitable(val: object) -> TypeIs[Awaitable[Any]]:
1896 return hasattr(val, '__await__')
1898 def f(val: Union[int, Awaitable[int]]) -> int:
1899 if is_awaitable(val):
1900 assert_type(val, Awaitable[int])
1901 else:
1902 assert_type(val, int)
1904 ``TypeIs`` also works with type variables. For more information, see
1905 PEP 742 (Narrowing types with TypeIs).
1906 """)
1909# Vendored from cpython typing._SpecialFrom
1910class _SpecialForm(typing._Final, _root=True):
1911 __slots__ = ('_name', '__doc__', '_getitem')
1913 def __init__(self, getitem):
1914 self._getitem = getitem
1915 self._name = getitem.__name__
1916 self.__doc__ = getitem.__doc__
1918 def __getattr__(self, item):
1919 if item in {'__name__', '__qualname__'}:
1920 return self._name
1922 raise AttributeError(item)
1924 def __mro_entries__(self, bases):
1925 raise TypeError(f"Cannot subclass {self!r}")
1927 def __repr__(self):
1928 return f'typing_extensions.{self._name}'
1930 def __reduce__(self):
1931 return self._name
1933 def __call__(self, *args, **kwds):
1934 raise TypeError(f"Cannot instantiate {self!r}")
1936 def __or__(self, other):
1937 return typing.Union[self, other]
1939 def __ror__(self, other):
1940 return typing.Union[other, self]
1942 def __instancecheck__(self, obj):
1943 raise TypeError(f"{self} cannot be used with isinstance()")
1945 def __subclasscheck__(self, cls):
1946 raise TypeError(f"{self} cannot be used with issubclass()")
1948 @typing._tp_cache
1949 def __getitem__(self, parameters):
1950 return self._getitem(self, parameters)
1953if hasattr(typing, "LiteralString"): # 3.11+
1954 LiteralString = typing.LiteralString
1955else:
1956 @_SpecialForm
1957 def LiteralString(self, params):
1958 """Represents an arbitrary literal string.
1960 Example::
1962 from typing_extensions import LiteralString
1964 def query(sql: LiteralString) -> ...:
1965 ...
1967 query("SELECT * FROM table") # ok
1968 query(f"SELECT * FROM {input()}") # not ok
1970 See PEP 675 for details.
1972 """
1973 raise TypeError(f"{self} is not subscriptable")
1976if hasattr(typing, "Self"): # 3.11+
1977 Self = typing.Self
1978else:
1979 @_SpecialForm
1980 def Self(self, params):
1981 """Used to spell the type of "self" in classes.
1983 Example::
1985 from typing import Self
1987 class ReturnsSelf:
1988 def parse(self, data: bytes) -> Self:
1989 ...
1990 return self
1992 """
1994 raise TypeError(f"{self} is not subscriptable")
1997if hasattr(typing, "Never"): # 3.11+
1998 Never = typing.Never
1999else:
2000 @_SpecialForm
2001 def Never(self, params):
2002 """The bottom type, a type that has no members.
2004 This can be used to define a function that should never be
2005 called, or a function that never returns::
2007 from typing_extensions import Never
2009 def never_call_me(arg: Never) -> None:
2010 pass
2012 def int_or_str(arg: int | str) -> None:
2013 never_call_me(arg) # type checker error
2014 match arg:
2015 case int():
2016 print("It's an int")
2017 case str():
2018 print("It's a str")
2019 case _:
2020 never_call_me(arg) # ok, arg is of type Never
2022 """
2024 raise TypeError(f"{self} is not subscriptable")
2027if hasattr(typing, 'Required'): # 3.11+
2028 Required = typing.Required
2029 NotRequired = typing.NotRequired
2030elif sys.version_info[:2] >= (3, 9): # 3.9-3.10
2031 @_ExtensionsSpecialForm
2032 def Required(self, parameters):
2033 """A special typing construct to mark a key of a total=False TypedDict
2034 as required. For example:
2036 class Movie(TypedDict, total=False):
2037 title: Required[str]
2038 year: int
2040 m = Movie(
2041 title='The Matrix', # typechecker error if key is omitted
2042 year=1999,
2043 )
2045 There is no runtime checking that a required key is actually provided
2046 when instantiating a related TypedDict.
2047 """
2048 item = typing._type_check(parameters, f'{self._name} accepts only a single type.')
2049 return typing._GenericAlias(self, (item,))
2051 @_ExtensionsSpecialForm
2052 def NotRequired(self, parameters):
2053 """A special typing construct to mark a key of a TypedDict as
2054 potentially missing. For example:
2056 class Movie(TypedDict):
2057 title: str
2058 year: NotRequired[int]
2060 m = Movie(
2061 title='The Matrix', # typechecker error if key is omitted
2062 year=1999,
2063 )
2064 """
2065 item = typing._type_check(parameters, f'{self._name} accepts only a single type.')
2066 return typing._GenericAlias(self, (item,))
2068else: # 3.8
2069 class _RequiredForm(_ExtensionsSpecialForm, _root=True):
2070 def __getitem__(self, parameters):
2071 item = typing._type_check(parameters,
2072 f'{self._name} accepts only a single type.')
2073 return typing._GenericAlias(self, (item,))
2075 Required = _RequiredForm(
2076 'Required',
2077 doc="""A special typing construct to mark a key of a total=False TypedDict
2078 as required. For example:
2080 class Movie(TypedDict, total=False):
2081 title: Required[str]
2082 year: int
2084 m = Movie(
2085 title='The Matrix', # typechecker error if key is omitted
2086 year=1999,
2087 )
2089 There is no runtime checking that a required key is actually provided
2090 when instantiating a related TypedDict.
2091 """)
2092 NotRequired = _RequiredForm(
2093 'NotRequired',
2094 doc="""A special typing construct to mark a key of a TypedDict as
2095 potentially missing. For example:
2097 class Movie(TypedDict):
2098 title: str
2099 year: NotRequired[int]
2101 m = Movie(
2102 title='The Matrix', # typechecker error if key is omitted
2103 year=1999,
2104 )
2105 """)
2108if hasattr(typing, 'ReadOnly'):
2109 ReadOnly = typing.ReadOnly
2110elif sys.version_info[:2] >= (3, 9): # 3.9-3.12
2111 @_ExtensionsSpecialForm
2112 def ReadOnly(self, parameters):
2113 """A special typing construct to mark an item of a TypedDict as read-only.
2115 For example:
2117 class Movie(TypedDict):
2118 title: ReadOnly[str]
2119 year: int
2121 def mutate_movie(m: Movie) -> None:
2122 m["year"] = 1992 # allowed
2123 m["title"] = "The Matrix" # typechecker error
2125 There is no runtime checking for this property.
2126 """
2127 item = typing._type_check(parameters, f'{self._name} accepts only a single type.')
2128 return typing._GenericAlias(self, (item,))
2130else: # 3.8
2131 class _ReadOnlyForm(_ExtensionsSpecialForm, _root=True):
2132 def __getitem__(self, parameters):
2133 item = typing._type_check(parameters,
2134 f'{self._name} accepts only a single type.')
2135 return typing._GenericAlias(self, (item,))
2137 ReadOnly = _ReadOnlyForm(
2138 'ReadOnly',
2139 doc="""A special typing construct to mark a key of a TypedDict as read-only.
2141 For example:
2143 class Movie(TypedDict):
2144 title: ReadOnly[str]
2145 year: int
2147 def mutate_movie(m: Movie) -> None:
2148 m["year"] = 1992 # allowed
2149 m["title"] = "The Matrix" # typechecker error
2151 There is no runtime checking for this propery.
2152 """)
2155_UNPACK_DOC = """\
2156Type unpack operator.
2158The type unpack operator takes the child types from some container type,
2159such as `tuple[int, str]` or a `TypeVarTuple`, and 'pulls them out'. For
2160example:
2162 # For some generic class `Foo`:
2163 Foo[Unpack[tuple[int, str]]] # Equivalent to Foo[int, str]
2165 Ts = TypeVarTuple('Ts')
2166 # Specifies that `Bar` is generic in an arbitrary number of types.
2167 # (Think of `Ts` as a tuple of an arbitrary number of individual
2168 # `TypeVar`s, which the `Unpack` is 'pulling out' directly into the
2169 # `Generic[]`.)
2170 class Bar(Generic[Unpack[Ts]]): ...
2171 Bar[int] # Valid
2172 Bar[int, str] # Also valid
2174From Python 3.11, this can also be done using the `*` operator:
2176 Foo[*tuple[int, str]]
2177 class Bar(Generic[*Ts]): ...
2179The operator can also be used along with a `TypedDict` to annotate
2180`**kwargs` in a function signature. For instance:
2182 class Movie(TypedDict):
2183 name: str
2184 year: int
2186 # This function expects two keyword arguments - *name* of type `str` and
2187 # *year* of type `int`.
2188 def foo(**kwargs: Unpack[Movie]): ...
2190Note that there is only some runtime checking of this operator. Not
2191everything the runtime allows may be accepted by static type checkers.
2193For more information, see PEP 646 and PEP 692.
2194"""
2197if sys.version_info >= (3, 12): # PEP 692 changed the repr of Unpack[]
2198 Unpack = typing.Unpack
2200 def _is_unpack(obj):
2201 return get_origin(obj) is Unpack
2203elif sys.version_info[:2] >= (3, 9): # 3.9+
2204 class _UnpackSpecialForm(_ExtensionsSpecialForm, _root=True):
2205 def __init__(self, getitem):
2206 super().__init__(getitem)
2207 self.__doc__ = _UNPACK_DOC
2209 class _UnpackAlias(typing._GenericAlias, _root=True):
2210 __class__ = typing.TypeVar
2212 @_UnpackSpecialForm
2213 def Unpack(self, parameters):
2214 item = typing._type_check(parameters, f'{self._name} accepts only a single type.')
2215 return _UnpackAlias(self, (item,))
2217 def _is_unpack(obj):
2218 return isinstance(obj, _UnpackAlias)
2220else: # 3.8
2221 class _UnpackAlias(typing._GenericAlias, _root=True):
2222 __class__ = typing.TypeVar
2224 class _UnpackForm(_ExtensionsSpecialForm, _root=True):
2225 def __getitem__(self, parameters):
2226 item = typing._type_check(parameters,
2227 f'{self._name} accepts only a single type.')
2228 return _UnpackAlias(self, (item,))
2230 Unpack = _UnpackForm('Unpack', doc=_UNPACK_DOC)
2232 def _is_unpack(obj):
2233 return isinstance(obj, _UnpackAlias)
2236if hasattr(typing, "TypeVarTuple"): # 3.11+
2238 # Add default parameter - PEP 696
2239 class TypeVarTuple(metaclass=_TypeVarLikeMeta):
2240 """Type variable tuple."""
2242 _backported_typevarlike = typing.TypeVarTuple
2244 def __new__(cls, name, *, default=_marker):
2245 tvt = typing.TypeVarTuple(name)
2246 _set_default(tvt, default)
2247 _set_module(tvt)
2248 return tvt
2250 def __init_subclass__(self, *args, **kwds):
2251 raise TypeError("Cannot subclass special typing classes")
2253else: # <=3.10
2254 class TypeVarTuple(_DefaultMixin):
2255 """Type variable tuple.
2257 Usage::
2259 Ts = TypeVarTuple('Ts')
2261 In the same way that a normal type variable is a stand-in for a single
2262 type such as ``int``, a type variable *tuple* is a stand-in for a *tuple*
2263 type such as ``Tuple[int, str]``.
2265 Type variable tuples can be used in ``Generic`` declarations.
2266 Consider the following example::
2268 class Array(Generic[*Ts]): ...
2270 The ``Ts`` type variable tuple here behaves like ``tuple[T1, T2]``,
2271 where ``T1`` and ``T2`` are type variables. To use these type variables
2272 as type parameters of ``Array``, we must *unpack* the type variable tuple using
2273 the star operator: ``*Ts``. The signature of ``Array`` then behaves
2274 as if we had simply written ``class Array(Generic[T1, T2]): ...``.
2275 In contrast to ``Generic[T1, T2]``, however, ``Generic[*Shape]`` allows
2276 us to parameterise the class with an *arbitrary* number of type parameters.
2278 Type variable tuples can be used anywhere a normal ``TypeVar`` can.
2279 This includes class definitions, as shown above, as well as function
2280 signatures and variable annotations::
2282 class Array(Generic[*Ts]):
2284 def __init__(self, shape: Tuple[*Ts]):
2285 self._shape: Tuple[*Ts] = shape
2287 def get_shape(self) -> Tuple[*Ts]:
2288 return self._shape
2290 shape = (Height(480), Width(640))
2291 x: Array[Height, Width] = Array(shape)
2292 y = abs(x) # Inferred type is Array[Height, Width]
2293 z = x + x # ... is Array[Height, Width]
2294 x.get_shape() # ... is tuple[Height, Width]
2296 """
2298 # Trick Generic __parameters__.
2299 __class__ = typing.TypeVar
2301 def __iter__(self):
2302 yield self.__unpacked__
2304 def __init__(self, name, *, default=_marker):
2305 self.__name__ = name
2306 _DefaultMixin.__init__(self, default)
2308 # for pickling:
2309 def_mod = _caller()
2310 if def_mod != 'typing_extensions':
2311 self.__module__ = def_mod
2313 self.__unpacked__ = Unpack[self]
2315 def __repr__(self):
2316 return self.__name__
2318 def __hash__(self):
2319 return object.__hash__(self)
2321 def __eq__(self, other):
2322 return self is other
2324 def __reduce__(self):
2325 return self.__name__
2327 def __init_subclass__(self, *args, **kwds):
2328 if '_root' not in kwds:
2329 raise TypeError("Cannot subclass special typing classes")
2332if hasattr(typing, "reveal_type"): # 3.11+
2333 reveal_type = typing.reveal_type
2334else: # <=3.10
2335 def reveal_type(obj: T, /) -> T:
2336 """Reveal the inferred type of a variable.
2338 When a static type checker encounters a call to ``reveal_type()``,
2339 it will emit the inferred type of the argument::
2341 x: int = 1
2342 reveal_type(x)
2344 Running a static type checker (e.g., ``mypy``) on this example
2345 will produce output similar to 'Revealed type is "builtins.int"'.
2347 At runtime, the function prints the runtime type of the
2348 argument and returns it unchanged.
2350 """
2351 print(f"Runtime type is {type(obj).__name__!r}", file=sys.stderr)
2352 return obj
2355if hasattr(typing, "assert_never"): # 3.11+
2356 assert_never = typing.assert_never
2357else: # <=3.10
2358 def assert_never(arg: Never, /) -> Never:
2359 """Assert to the type checker that a line of code is unreachable.
2361 Example::
2363 def int_or_str(arg: int | str) -> None:
2364 match arg:
2365 case int():
2366 print("It's an int")
2367 case str():
2368 print("It's a str")
2369 case _:
2370 assert_never(arg)
2372 If a type checker finds that a call to assert_never() is
2373 reachable, it will emit an error.
2375 At runtime, this throws an exception when called.
2377 """
2378 raise AssertionError("Expected code to be unreachable")
2381if sys.version_info >= (3, 12): # 3.12+
2382 # dataclass_transform exists in 3.11 but lacks the frozen_default parameter
2383 dataclass_transform = typing.dataclass_transform
2384else: # <=3.11
2385 def dataclass_transform(
2386 *,
2387 eq_default: bool = True,
2388 order_default: bool = False,
2389 kw_only_default: bool = False,
2390 frozen_default: bool = False,
2391 field_specifiers: typing.Tuple[
2392 typing.Union[typing.Type[typing.Any], typing.Callable[..., typing.Any]],
2393 ...
2394 ] = (),
2395 **kwargs: typing.Any,
2396 ) -> typing.Callable[[T], T]:
2397 """Decorator that marks a function, class, or metaclass as providing
2398 dataclass-like behavior.
2400 Example:
2402 from typing_extensions import dataclass_transform
2404 _T = TypeVar("_T")
2406 # Used on a decorator function
2407 @dataclass_transform()
2408 def create_model(cls: type[_T]) -> type[_T]:
2409 ...
2410 return cls
2412 @create_model
2413 class CustomerModel:
2414 id: int
2415 name: str
2417 # Used on a base class
2418 @dataclass_transform()
2419 class ModelBase: ...
2421 class CustomerModel(ModelBase):
2422 id: int
2423 name: str
2425 # Used on a metaclass
2426 @dataclass_transform()
2427 class ModelMeta(type): ...
2429 class ModelBase(metaclass=ModelMeta): ...
2431 class CustomerModel(ModelBase):
2432 id: int
2433 name: str
2435 Each of the ``CustomerModel`` classes defined in this example will now
2436 behave similarly to a dataclass created with the ``@dataclasses.dataclass``
2437 decorator. For example, the type checker will synthesize an ``__init__``
2438 method.
2440 The arguments to this decorator can be used to customize this behavior:
2441 - ``eq_default`` indicates whether the ``eq`` parameter is assumed to be
2442 True or False if it is omitted by the caller.
2443 - ``order_default`` indicates whether the ``order`` parameter is
2444 assumed to be True or False if it is omitted by the caller.
2445 - ``kw_only_default`` indicates whether the ``kw_only`` parameter is
2446 assumed to be True or False if it is omitted by the caller.
2447 - ``frozen_default`` indicates whether the ``frozen`` parameter is
2448 assumed to be True or False if it is omitted by the caller.
2449 - ``field_specifiers`` specifies a static list of supported classes
2450 or functions that describe fields, similar to ``dataclasses.field()``.
2452 At runtime, this decorator records its arguments in the
2453 ``__dataclass_transform__`` attribute on the decorated object.
2455 See PEP 681 for details.
2457 """
2458 def decorator(cls_or_fn):
2459 cls_or_fn.__dataclass_transform__ = {
2460 "eq_default": eq_default,
2461 "order_default": order_default,
2462 "kw_only_default": kw_only_default,
2463 "frozen_default": frozen_default,
2464 "field_specifiers": field_specifiers,
2465 "kwargs": kwargs,
2466 }
2467 return cls_or_fn
2468 return decorator
2471if hasattr(typing, "override"): # 3.12+
2472 override = typing.override
2473else: # <=3.11
2474 _F = typing.TypeVar("_F", bound=typing.Callable[..., typing.Any])
2476 def override(arg: _F, /) -> _F:
2477 """Indicate that a method is intended to override a method in a base class.
2479 Usage:
2481 class Base:
2482 def method(self) -> None:
2483 pass
2485 class Child(Base):
2486 @override
2487 def method(self) -> None:
2488 super().method()
2490 When this decorator is applied to a method, the type checker will
2491 validate that it overrides a method with the same name on a base class.
2492 This helps prevent bugs that may occur when a base class is changed
2493 without an equivalent change to a child class.
2495 There is no runtime checking of these properties. The decorator
2496 sets the ``__override__`` attribute to ``True`` on the decorated object
2497 to allow runtime introspection.
2499 See PEP 698 for details.
2501 """
2502 try:
2503 arg.__override__ = True
2504 except (AttributeError, TypeError):
2505 # Skip the attribute silently if it is not writable.
2506 # AttributeError happens if the object has __slots__ or a
2507 # read-only property, TypeError if it's a builtin class.
2508 pass
2509 return arg
2512if hasattr(warnings, "deprecated"):
2513 deprecated = warnings.deprecated
2514else:
2515 _T = typing.TypeVar("_T")
2517 class deprecated:
2518 """Indicate that a class, function or overload is deprecated.
2520 When this decorator is applied to an object, the type checker
2521 will generate a diagnostic on usage of the deprecated object.
2523 Usage:
2525 @deprecated("Use B instead")
2526 class A:
2527 pass
2529 @deprecated("Use g instead")
2530 def f():
2531 pass
2533 @overload
2534 @deprecated("int support is deprecated")
2535 def g(x: int) -> int: ...
2536 @overload
2537 def g(x: str) -> int: ...
2539 The warning specified by *category* will be emitted at runtime
2540 on use of deprecated objects. For functions, that happens on calls;
2541 for classes, on instantiation and on creation of subclasses.
2542 If the *category* is ``None``, no warning is emitted at runtime.
2543 The *stacklevel* determines where the
2544 warning is emitted. If it is ``1`` (the default), the warning
2545 is emitted at the direct caller of the deprecated object; if it
2546 is higher, it is emitted further up the stack.
2547 Static type checker behavior is not affected by the *category*
2548 and *stacklevel* arguments.
2550 The deprecation message passed to the decorator is saved in the
2551 ``__deprecated__`` attribute on the decorated object.
2552 If applied to an overload, the decorator
2553 must be after the ``@overload`` decorator for the attribute to
2554 exist on the overload as returned by ``get_overloads()``.
2556 See PEP 702 for details.
2558 """
2559 def __init__(
2560 self,
2561 message: str,
2562 /,
2563 *,
2564 category: typing.Optional[typing.Type[Warning]] = DeprecationWarning,
2565 stacklevel: int = 1,
2566 ) -> None:
2567 if not isinstance(message, str):
2568 raise TypeError(
2569 "Expected an object of type str for 'message', not "
2570 f"{type(message).__name__!r}"
2571 )
2572 self.message = message
2573 self.category = category
2574 self.stacklevel = stacklevel
2576 def __call__(self, arg: _T, /) -> _T:
2577 # Make sure the inner functions created below don't
2578 # retain a reference to self.
2579 msg = self.message
2580 category = self.category
2581 stacklevel = self.stacklevel
2582 if category is None:
2583 arg.__deprecated__ = msg
2584 return arg
2585 elif isinstance(arg, type):
2586 import functools
2587 from types import MethodType
2589 original_new = arg.__new__
2591 @functools.wraps(original_new)
2592 def __new__(cls, *args, **kwargs):
2593 if cls is arg:
2594 warnings.warn(msg, category=category, stacklevel=stacklevel + 1)
2595 if original_new is not object.__new__:
2596 return original_new(cls, *args, **kwargs)
2597 # Mirrors a similar check in object.__new__.
2598 elif cls.__init__ is object.__init__ and (args or kwargs):
2599 raise TypeError(f"{cls.__name__}() takes no arguments")
2600 else:
2601 return original_new(cls)
2603 arg.__new__ = staticmethod(__new__)
2605 original_init_subclass = arg.__init_subclass__
2606 # We need slightly different behavior if __init_subclass__
2607 # is a bound method (likely if it was implemented in Python)
2608 if isinstance(original_init_subclass, MethodType):
2609 original_init_subclass = original_init_subclass.__func__
2611 @functools.wraps(original_init_subclass)
2612 def __init_subclass__(*args, **kwargs):
2613 warnings.warn(msg, category=category, stacklevel=stacklevel + 1)
2614 return original_init_subclass(*args, **kwargs)
2616 arg.__init_subclass__ = classmethod(__init_subclass__)
2617 # Or otherwise, which likely means it's a builtin such as
2618 # object's implementation of __init_subclass__.
2619 else:
2620 @functools.wraps(original_init_subclass)
2621 def __init_subclass__(*args, **kwargs):
2622 warnings.warn(msg, category=category, stacklevel=stacklevel + 1)
2623 return original_init_subclass(*args, **kwargs)
2625 arg.__init_subclass__ = __init_subclass__
2627 arg.__deprecated__ = __new__.__deprecated__ = msg
2628 __init_subclass__.__deprecated__ = msg
2629 return arg
2630 elif callable(arg):
2631 import functools
2633 @functools.wraps(arg)
2634 def wrapper(*args, **kwargs):
2635 warnings.warn(msg, category=category, stacklevel=stacklevel + 1)
2636 return arg(*args, **kwargs)
2638 arg.__deprecated__ = wrapper.__deprecated__ = msg
2639 return wrapper
2640 else:
2641 raise TypeError(
2642 "@deprecated decorator with non-None category must be applied to "
2643 f"a class or callable, not {arg!r}"
2644 )
2647# We have to do some monkey patching to deal with the dual nature of
2648# Unpack/TypeVarTuple:
2649# - We want Unpack to be a kind of TypeVar so it gets accepted in
2650# Generic[Unpack[Ts]]
2651# - We want it to *not* be treated as a TypeVar for the purposes of
2652# counting generic parameters, so that when we subscript a generic,
2653# the runtime doesn't try to substitute the Unpack with the subscripted type.
2654if not hasattr(typing, "TypeVarTuple"):
2655 def _check_generic(cls, parameters, elen=_marker):
2656 """Check correct count for parameters of a generic cls (internal helper).
2658 This gives a nice error message in case of count mismatch.
2659 """
2660 if not elen:
2661 raise TypeError(f"{cls} is not a generic class")
2662 if elen is _marker:
2663 if not hasattr(cls, "__parameters__") or not cls.__parameters__:
2664 raise TypeError(f"{cls} is not a generic class")
2665 elen = len(cls.__parameters__)
2666 alen = len(parameters)
2667 if alen != elen:
2668 expect_val = elen
2669 if hasattr(cls, "__parameters__"):
2670 parameters = [p for p in cls.__parameters__ if not _is_unpack(p)]
2671 num_tv_tuples = sum(isinstance(p, TypeVarTuple) for p in parameters)
2672 if (num_tv_tuples > 0) and (alen >= elen - num_tv_tuples):
2673 return
2675 # deal with TypeVarLike defaults
2676 # required TypeVarLikes cannot appear after a defaulted one.
2677 if alen < elen:
2678 # since we validate TypeVarLike default in _collect_type_vars
2679 # or _collect_parameters we can safely check parameters[alen]
2680 if getattr(parameters[alen], '__default__', None) is not None:
2681 return
2683 num_default_tv = sum(getattr(p, '__default__', None)
2684 is not None for p in parameters)
2686 elen -= num_default_tv
2688 expect_val = f"at least {elen}"
2690 things = "arguments" if sys.version_info >= (3, 10) else "parameters"
2691 raise TypeError(f"Too {'many' if alen > elen else 'few'} {things}"
2692 f" for {cls}; actual {alen}, expected {expect_val}")
2693else:
2694 # Python 3.11+
2696 def _check_generic(cls, parameters, elen):
2697 """Check correct count for parameters of a generic cls (internal helper).
2699 This gives a nice error message in case of count mismatch.
2700 """
2701 if not elen:
2702 raise TypeError(f"{cls} is not a generic class")
2703 alen = len(parameters)
2704 if alen != elen:
2705 expect_val = elen
2706 if hasattr(cls, "__parameters__"):
2707 parameters = [p for p in cls.__parameters__ if not _is_unpack(p)]
2709 # deal with TypeVarLike defaults
2710 # required TypeVarLikes cannot appear after a defaulted one.
2711 if alen < elen:
2712 # since we validate TypeVarLike default in _collect_type_vars
2713 # or _collect_parameters we can safely check parameters[alen]
2714 if getattr(parameters[alen], '__default__', None) is not None:
2715 return
2717 num_default_tv = sum(getattr(p, '__default__', None)
2718 is not None for p in parameters)
2720 elen -= num_default_tv
2722 expect_val = f"at least {elen}"
2724 raise TypeError(f"Too {'many' if alen > elen else 'few'} arguments"
2725 f" for {cls}; actual {alen}, expected {expect_val}")
2727typing._check_generic = _check_generic
2729# Python 3.11+ _collect_type_vars was renamed to _collect_parameters
2730if hasattr(typing, '_collect_type_vars'):
2731 def _collect_type_vars(types, typevar_types=None):
2732 """Collect all type variable contained in types in order of
2733 first appearance (lexicographic order). For example::
2735 _collect_type_vars((T, List[S, T])) == (T, S)
2736 """
2737 if typevar_types is None:
2738 typevar_types = typing.TypeVar
2739 tvars = []
2740 # required TypeVarLike cannot appear after TypeVarLike with default
2741 default_encountered = False
2742 for t in types:
2743 if (
2744 isinstance(t, typevar_types) and
2745 t not in tvars and
2746 not _is_unpack(t)
2747 ):
2748 if getattr(t, '__default__', None) is not None:
2749 default_encountered = True
2750 elif default_encountered:
2751 raise TypeError(f'Type parameter {t!r} without a default'
2752 ' follows type parameter with a default')
2754 tvars.append(t)
2755 if _should_collect_from_parameters(t):
2756 tvars.extend([t for t in t.__parameters__ if t not in tvars])
2757 return tuple(tvars)
2759 typing._collect_type_vars = _collect_type_vars
2760else:
2761 def _collect_parameters(args):
2762 """Collect all type variables and parameter specifications in args
2763 in order of first appearance (lexicographic order).
2765 For example::
2767 assert _collect_parameters((T, Callable[P, T])) == (T, P)
2768 """
2769 parameters = []
2770 # required TypeVarLike cannot appear after TypeVarLike with default
2771 default_encountered = False
2772 for t in args:
2773 if isinstance(t, type):
2774 # We don't want __parameters__ descriptor of a bare Python class.
2775 pass
2776 elif isinstance(t, tuple):
2777 # `t` might be a tuple, when `ParamSpec` is substituted with
2778 # `[T, int]`, or `[int, *Ts]`, etc.
2779 for x in t:
2780 for collected in _collect_parameters([x]):
2781 if collected not in parameters:
2782 parameters.append(collected)
2783 elif hasattr(t, '__typing_subst__'):
2784 if t not in parameters:
2785 if getattr(t, '__default__', None) is not None:
2786 default_encountered = True
2787 elif default_encountered:
2788 raise TypeError(f'Type parameter {t!r} without a default'
2789 ' follows type parameter with a default')
2791 parameters.append(t)
2792 else:
2793 for x in getattr(t, '__parameters__', ()):
2794 if x not in parameters:
2795 parameters.append(x)
2797 return tuple(parameters)
2799 typing._collect_parameters = _collect_parameters
2801# Backport typing.NamedTuple as it exists in Python 3.13.
2802# In 3.11, the ability to define generic `NamedTuple`s was supported.
2803# This was explicitly disallowed in 3.9-3.10, and only half-worked in <=3.8.
2804# On 3.12, we added __orig_bases__ to call-based NamedTuples
2805# On 3.13, we deprecated kwargs-based NamedTuples
2806if sys.version_info >= (3, 13):
2807 NamedTuple = typing.NamedTuple
2808else:
2809 def _make_nmtuple(name, types, module, defaults=()):
2810 fields = [n for n, t in types]
2811 annotations = {n: typing._type_check(t, f"field {n} annotation must be a type")
2812 for n, t in types}
2813 nm_tpl = collections.namedtuple(name, fields,
2814 defaults=defaults, module=module)
2815 nm_tpl.__annotations__ = nm_tpl.__new__.__annotations__ = annotations
2816 # The `_field_types` attribute was removed in 3.9;
2817 # in earlier versions, it is the same as the `__annotations__` attribute
2818 if sys.version_info < (3, 9):
2819 nm_tpl._field_types = annotations
2820 return nm_tpl
2822 _prohibited_namedtuple_fields = typing._prohibited
2823 _special_namedtuple_fields = frozenset({'__module__', '__name__', '__annotations__'})
2825 class _NamedTupleMeta(type):
2826 def __new__(cls, typename, bases, ns):
2827 assert _NamedTuple in bases
2828 for base in bases:
2829 if base is not _NamedTuple and base is not typing.Generic:
2830 raise TypeError(
2831 'can only inherit from a NamedTuple type and Generic')
2832 bases = tuple(tuple if base is _NamedTuple else base for base in bases)
2833 types = ns.get('__annotations__', {})
2834 default_names = []
2835 for field_name in types:
2836 if field_name in ns:
2837 default_names.append(field_name)
2838 elif default_names:
2839 raise TypeError(f"Non-default namedtuple field {field_name} "
2840 f"cannot follow default field"
2841 f"{'s' if len(default_names) > 1 else ''} "
2842 f"{', '.join(default_names)}")
2843 nm_tpl = _make_nmtuple(
2844 typename, types.items(),
2845 defaults=[ns[n] for n in default_names],
2846 module=ns['__module__']
2847 )
2848 nm_tpl.__bases__ = bases
2849 if typing.Generic in bases:
2850 if hasattr(typing, '_generic_class_getitem'): # 3.12+
2851 nm_tpl.__class_getitem__ = classmethod(typing._generic_class_getitem)
2852 else:
2853 class_getitem = typing.Generic.__class_getitem__.__func__
2854 nm_tpl.__class_getitem__ = classmethod(class_getitem)
2855 # update from user namespace without overriding special namedtuple attributes
2856 for key, val in ns.items():
2857 if key in _prohibited_namedtuple_fields:
2858 raise AttributeError("Cannot overwrite NamedTuple attribute " + key)
2859 elif key not in _special_namedtuple_fields:
2860 if key not in nm_tpl._fields:
2861 setattr(nm_tpl, key, ns[key])
2862 try:
2863 set_name = type(val).__set_name__
2864 except AttributeError:
2865 pass
2866 else:
2867 try:
2868 set_name(val, nm_tpl, key)
2869 except BaseException as e:
2870 msg = (
2871 f"Error calling __set_name__ on {type(val).__name__!r} "
2872 f"instance {key!r} in {typename!r}"
2873 )
2874 # BaseException.add_note() existed on py311,
2875 # but the __set_name__ machinery didn't start
2876 # using add_note() until py312.
2877 # Making sure exceptions are raised in the same way
2878 # as in "normal" classes seems most important here.
2879 if sys.version_info >= (3, 12):
2880 e.add_note(msg)
2881 raise
2882 else:
2883 raise RuntimeError(msg) from e
2885 if typing.Generic in bases:
2886 nm_tpl.__init_subclass__()
2887 return nm_tpl
2889 _NamedTuple = type.__new__(_NamedTupleMeta, 'NamedTuple', (), {})
2891 def _namedtuple_mro_entries(bases):
2892 assert NamedTuple in bases
2893 return (_NamedTuple,)
2895 @_ensure_subclassable(_namedtuple_mro_entries)
2896 def NamedTuple(typename, fields=_marker, /, **kwargs):
2897 """Typed version of namedtuple.
2899 Usage::
2901 class Employee(NamedTuple):
2902 name: str
2903 id: int
2905 This is equivalent to::
2907 Employee = collections.namedtuple('Employee', ['name', 'id'])
2909 The resulting class has an extra __annotations__ attribute, giving a
2910 dict that maps field names to types. (The field names are also in
2911 the _fields attribute, which is part of the namedtuple API.)
2912 An alternative equivalent functional syntax is also accepted::
2914 Employee = NamedTuple('Employee', [('name', str), ('id', int)])
2915 """
2916 if fields is _marker:
2917 if kwargs:
2918 deprecated_thing = "Creating NamedTuple classes using keyword arguments"
2919 deprecation_msg = (
2920 "{name} is deprecated and will be disallowed in Python {remove}. "
2921 "Use the class-based or functional syntax instead."
2922 )
2923 else:
2924 deprecated_thing = "Failing to pass a value for the 'fields' parameter"
2925 example = f"`{typename} = NamedTuple({typename!r}, [])`"
2926 deprecation_msg = (
2927 "{name} is deprecated and will be disallowed in Python {remove}. "
2928 "To create a NamedTuple class with 0 fields "
2929 "using the functional syntax, "
2930 "pass an empty list, e.g. "
2931 ) + example + "."
2932 elif fields is None:
2933 if kwargs:
2934 raise TypeError(
2935 "Cannot pass `None` as the 'fields' parameter "
2936 "and also specify fields using keyword arguments"
2937 )
2938 else:
2939 deprecated_thing = "Passing `None` as the 'fields' parameter"
2940 example = f"`{typename} = NamedTuple({typename!r}, [])`"
2941 deprecation_msg = (
2942 "{name} is deprecated and will be disallowed in Python {remove}. "
2943 "To create a NamedTuple class with 0 fields "
2944 "using the functional syntax, "
2945 "pass an empty list, e.g. "
2946 ) + example + "."
2947 elif kwargs:
2948 raise TypeError("Either list of fields or keywords"
2949 " can be provided to NamedTuple, not both")
2950 if fields is _marker or fields is None:
2951 warnings.warn(
2952 deprecation_msg.format(name=deprecated_thing, remove="3.15"),
2953 DeprecationWarning,
2954 stacklevel=2,
2955 )
2956 fields = kwargs.items()
2957 nt = _make_nmtuple(typename, fields, module=_caller())
2958 nt.__orig_bases__ = (NamedTuple,)
2959 return nt
2962if hasattr(collections.abc, "Buffer"):
2963 Buffer = collections.abc.Buffer
2964else:
2965 class Buffer(abc.ABC):
2966 """Base class for classes that implement the buffer protocol.
2968 The buffer protocol allows Python objects to expose a low-level
2969 memory buffer interface. Before Python 3.12, it is not possible
2970 to implement the buffer protocol in pure Python code, or even
2971 to check whether a class implements the buffer protocol. In
2972 Python 3.12 and higher, the ``__buffer__`` method allows access
2973 to the buffer protocol from Python code, and the
2974 ``collections.abc.Buffer`` ABC allows checking whether a class
2975 implements the buffer protocol.
2977 To indicate support for the buffer protocol in earlier versions,
2978 inherit from this ABC, either in a stub file or at runtime,
2979 or use ABC registration. This ABC provides no methods, because
2980 there is no Python-accessible methods shared by pre-3.12 buffer
2981 classes. It is useful primarily for static checks.
2983 """
2985 # As a courtesy, register the most common stdlib buffer classes.
2986 Buffer.register(memoryview)
2987 Buffer.register(bytearray)
2988 Buffer.register(bytes)
2991# Backport of types.get_original_bases, available on 3.12+ in CPython
2992if hasattr(_types, "get_original_bases"):
2993 get_original_bases = _types.get_original_bases
2994else:
2995 def get_original_bases(cls, /):
2996 """Return the class's "original" bases prior to modification by `__mro_entries__`.
2998 Examples::
3000 from typing import TypeVar, Generic
3001 from typing_extensions import NamedTuple, TypedDict
3003 T = TypeVar("T")
3004 class Foo(Generic[T]): ...
3005 class Bar(Foo[int], float): ...
3006 class Baz(list[str]): ...
3007 Eggs = NamedTuple("Eggs", [("a", int), ("b", str)])
3008 Spam = TypedDict("Spam", {"a": int, "b": str})
3010 assert get_original_bases(Bar) == (Foo[int], float)
3011 assert get_original_bases(Baz) == (list[str],)
3012 assert get_original_bases(Eggs) == (NamedTuple,)
3013 assert get_original_bases(Spam) == (TypedDict,)
3014 assert get_original_bases(int) == (object,)
3015 """
3016 try:
3017 return cls.__dict__.get("__orig_bases__", cls.__bases__)
3018 except AttributeError:
3019 raise TypeError(
3020 f'Expected an instance of type, not {type(cls).__name__!r}'
3021 ) from None
3024# NewType is a class on Python 3.10+, making it pickleable
3025# The error message for subclassing instances of NewType was improved on 3.11+
3026if sys.version_info >= (3, 11):
3027 NewType = typing.NewType
3028else:
3029 class NewType:
3030 """NewType creates simple unique types with almost zero
3031 runtime overhead. NewType(name, tp) is considered a subtype of tp
3032 by static type checkers. At runtime, NewType(name, tp) returns
3033 a dummy callable that simply returns its argument. Usage::
3034 UserId = NewType('UserId', int)
3035 def name_by_id(user_id: UserId) -> str:
3036 ...
3037 UserId('user') # Fails type check
3038 name_by_id(42) # Fails type check
3039 name_by_id(UserId(42)) # OK
3040 num = UserId(5) + 1 # type: int
3041 """
3043 def __call__(self, obj, /):
3044 return obj
3046 def __init__(self, name, tp):
3047 self.__qualname__ = name
3048 if '.' in name:
3049 name = name.rpartition('.')[-1]
3050 self.__name__ = name
3051 self.__supertype__ = tp
3052 def_mod = _caller()
3053 if def_mod != 'typing_extensions':
3054 self.__module__ = def_mod
3056 def __mro_entries__(self, bases):
3057 # We defined __mro_entries__ to get a better error message
3058 # if a user attempts to subclass a NewType instance. bpo-46170
3059 supercls_name = self.__name__
3061 class Dummy:
3062 def __init_subclass__(cls):
3063 subcls_name = cls.__name__
3064 raise TypeError(
3065 f"Cannot subclass an instance of NewType. "
3066 f"Perhaps you were looking for: "
3067 f"`{subcls_name} = NewType({subcls_name!r}, {supercls_name})`"
3068 )
3070 return (Dummy,)
3072 def __repr__(self):
3073 return f'{self.__module__}.{self.__qualname__}'
3075 def __reduce__(self):
3076 return self.__qualname__
3078 if sys.version_info >= (3, 10):
3079 # PEP 604 methods
3080 # It doesn't make sense to have these methods on Python <3.10
3082 def __or__(self, other):
3083 return typing.Union[self, other]
3085 def __ror__(self, other):
3086 return typing.Union[other, self]
3089if hasattr(typing, "TypeAliasType"):
3090 TypeAliasType = typing.TypeAliasType
3091else:
3092 def _is_unionable(obj):
3093 """Corresponds to is_unionable() in unionobject.c in CPython."""
3094 return obj is None or isinstance(obj, (
3095 type,
3096 _types.GenericAlias,
3097 _types.UnionType,
3098 TypeAliasType,
3099 ))
3101 class TypeAliasType:
3102 """Create named, parameterized type aliases.
3104 This provides a backport of the new `type` statement in Python 3.12:
3106 type ListOrSet[T] = list[T] | set[T]
3108 is equivalent to:
3110 T = TypeVar("T")
3111 ListOrSet = TypeAliasType("ListOrSet", list[T] | set[T], type_params=(T,))
3113 The name ListOrSet can then be used as an alias for the type it refers to.
3115 The type_params argument should contain all the type parameters used
3116 in the value of the type alias. If the alias is not generic, this
3117 argument is omitted.
3119 Static type checkers should only support type aliases declared using
3120 TypeAliasType that follow these rules:
3122 - The first argument (the name) must be a string literal.
3123 - The TypeAliasType instance must be immediately assigned to a variable
3124 of the same name. (For example, 'X = TypeAliasType("Y", int)' is invalid,
3125 as is 'X, Y = TypeAliasType("X", int), TypeAliasType("Y", int)').
3127 """
3129 def __init__(self, name: str, value, *, type_params=()):
3130 if not isinstance(name, str):
3131 raise TypeError("TypeAliasType name must be a string")
3132 self.__value__ = value
3133 self.__type_params__ = type_params
3135 parameters = []
3136 for type_param in type_params:
3137 if isinstance(type_param, TypeVarTuple):
3138 parameters.extend(type_param)
3139 else:
3140 parameters.append(type_param)
3141 self.__parameters__ = tuple(parameters)
3142 def_mod = _caller()
3143 if def_mod != 'typing_extensions':
3144 self.__module__ = def_mod
3145 # Setting this attribute closes the TypeAliasType from further modification
3146 self.__name__ = name
3148 def __setattr__(self, name: str, value: object, /) -> None:
3149 if hasattr(self, "__name__"):
3150 self._raise_attribute_error(name)
3151 super().__setattr__(name, value)
3153 def __delattr__(self, name: str, /) -> Never:
3154 self._raise_attribute_error(name)
3156 def _raise_attribute_error(self, name: str) -> Never:
3157 # Match the Python 3.12 error messages exactly
3158 if name == "__name__":
3159 raise AttributeError("readonly attribute")
3160 elif name in {"__value__", "__type_params__", "__parameters__", "__module__"}:
3161 raise AttributeError(
3162 f"attribute '{name}' of 'typing.TypeAliasType' objects "
3163 "is not writable"
3164 )
3165 else:
3166 raise AttributeError(
3167 f"'typing.TypeAliasType' object has no attribute '{name}'"
3168 )
3170 def __repr__(self) -> str:
3171 return self.__name__
3173 def __getitem__(self, parameters):
3174 if not isinstance(parameters, tuple):
3175 parameters = (parameters,)
3176 parameters = [
3177 typing._type_check(
3178 item, f'Subscripting {self.__name__} requires a type.'
3179 )
3180 for item in parameters
3181 ]
3182 return typing._GenericAlias(self, tuple(parameters))
3184 def __reduce__(self):
3185 return self.__name__
3187 def __init_subclass__(cls, *args, **kwargs):
3188 raise TypeError(
3189 "type 'typing_extensions.TypeAliasType' is not an acceptable base type"
3190 )
3192 # The presence of this method convinces typing._type_check
3193 # that TypeAliasTypes are types.
3194 def __call__(self):
3195 raise TypeError("Type alias is not callable")
3197 if sys.version_info >= (3, 10):
3198 def __or__(self, right):
3199 # For forward compatibility with 3.12, reject Unions
3200 # that are not accepted by the built-in Union.
3201 if not _is_unionable(right):
3202 return NotImplemented
3203 return typing.Union[self, right]
3205 def __ror__(self, left):
3206 if not _is_unionable(left):
3207 return NotImplemented
3208 return typing.Union[left, self]
3211if hasattr(typing, "is_protocol"):
3212 is_protocol = typing.is_protocol
3213 get_protocol_members = typing.get_protocol_members
3214else:
3215 def is_protocol(tp: type, /) -> bool:
3216 """Return True if the given type is a Protocol.
3218 Example::
3220 >>> from typing_extensions import Protocol, is_protocol
3221 >>> class P(Protocol):
3222 ... def a(self) -> str: ...
3223 ... b: int
3224 >>> is_protocol(P)
3225 True
3226 >>> is_protocol(int)
3227 False
3228 """
3229 return (
3230 isinstance(tp, type)
3231 and getattr(tp, '_is_protocol', False)
3232 and tp is not Protocol
3233 and tp is not typing.Protocol
3234 )
3236 def get_protocol_members(tp: type, /) -> typing.FrozenSet[str]:
3237 """Return the set of members defined in a Protocol.
3239 Example::
3241 >>> from typing_extensions import Protocol, get_protocol_members
3242 >>> class P(Protocol):
3243 ... def a(self) -> str: ...
3244 ... b: int
3245 >>> get_protocol_members(P)
3246 frozenset({'a', 'b'})
3248 Raise a TypeError for arguments that are not Protocols.
3249 """
3250 if not is_protocol(tp):
3251 raise TypeError(f'{tp!r} is not a Protocol')
3252 if hasattr(tp, '__protocol_attrs__'):
3253 return frozenset(tp.__protocol_attrs__)
3254 return frozenset(_get_protocol_attrs(tp))
3257if hasattr(typing, "Doc"):
3258 Doc = typing.Doc
3259else:
3260 class Doc:
3261 """Define the documentation of a type annotation using ``Annotated``, to be
3262 used in class attributes, function and method parameters, return values,
3263 and variables.
3265 The value should be a positional-only string literal to allow static tools
3266 like editors and documentation generators to use it.
3268 This complements docstrings.
3270 The string value passed is available in the attribute ``documentation``.
3272 Example::
3274 >>> from typing_extensions import Annotated, Doc
3275 >>> def hi(to: Annotated[str, Doc("Who to say hi to")]) -> None: ...
3276 """
3277 def __init__(self, documentation: str, /) -> None:
3278 self.documentation = documentation
3280 def __repr__(self) -> str:
3281 return f"Doc({self.documentation!r})"
3283 def __hash__(self) -> int:
3284 return hash(self.documentation)
3286 def __eq__(self, other: object) -> bool:
3287 if not isinstance(other, Doc):
3288 return NotImplemented
3289 return self.documentation == other.documentation
3292# Aliases for items that have always been in typing.
3293# Explicitly assign these (rather than using `from typing import *` at the top),
3294# so that we get a CI error if one of these is deleted from typing.py
3295# in a future version of Python
3296AbstractSet = typing.AbstractSet
3297AnyStr = typing.AnyStr
3298BinaryIO = typing.BinaryIO
3299Callable = typing.Callable
3300Collection = typing.Collection
3301Container = typing.Container
3302Dict = typing.Dict
3303ForwardRef = typing.ForwardRef
3304FrozenSet = typing.FrozenSet
3305Generator = typing.Generator
3306Generic = typing.Generic
3307Hashable = typing.Hashable
3308IO = typing.IO
3309ItemsView = typing.ItemsView
3310Iterable = typing.Iterable
3311Iterator = typing.Iterator
3312KeysView = typing.KeysView
3313List = typing.List
3314Mapping = typing.Mapping
3315MappingView = typing.MappingView
3316Match = typing.Match
3317MutableMapping = typing.MutableMapping
3318MutableSequence = typing.MutableSequence
3319MutableSet = typing.MutableSet
3320Optional = typing.Optional
3321Pattern = typing.Pattern
3322Reversible = typing.Reversible
3323Sequence = typing.Sequence
3324Set = typing.Set
3325Sized = typing.Sized
3326TextIO = typing.TextIO
3327Tuple = typing.Tuple
3328Union = typing.Union
3329ValuesView = typing.ValuesView
3330cast = typing.cast
3331no_type_check = typing.no_type_check
3332no_type_check_decorator = typing.no_type_check_decorator