1import abc
2import builtins
3import collections
4import collections.abc
5import contextlib
6import enum
7import functools
8import inspect
9import keyword
10import operator
11import sys
12import types as _types
13import typing
14import warnings
15
16__all__ = [
17 # Super-special typing primitives.
18 'Any',
19 'ClassVar',
20 'Concatenate',
21 'Final',
22 'LiteralString',
23 'ParamSpec',
24 'ParamSpecArgs',
25 'ParamSpecKwargs',
26 'Self',
27 'Type',
28 'TypeVar',
29 'TypeVarTuple',
30 'Unpack',
31
32 # ABCs (from collections.abc).
33 'Awaitable',
34 'AsyncIterator',
35 'AsyncIterable',
36 'Coroutine',
37 'AsyncGenerator',
38 'AsyncContextManager',
39 'Buffer',
40 'ChainMap',
41
42 # Concrete collection types.
43 'ContextManager',
44 'Counter',
45 'Deque',
46 'DefaultDict',
47 'NamedTuple',
48 'OrderedDict',
49 'TypedDict',
50
51 # Structural checks, a.k.a. protocols.
52 'SupportsAbs',
53 'SupportsBytes',
54 'SupportsComplex',
55 'SupportsFloat',
56 'SupportsIndex',
57 'SupportsInt',
58 'SupportsRound',
59
60 # One-off things.
61 'Annotated',
62 'assert_never',
63 'assert_type',
64 'clear_overloads',
65 'dataclass_transform',
66 'deprecated',
67 'Doc',
68 'evaluate_forward_ref',
69 'get_overloads',
70 'final',
71 'Format',
72 'get_annotations',
73 'get_args',
74 'get_origin',
75 'get_original_bases',
76 'get_protocol_members',
77 'get_type_hints',
78 'IntVar',
79 'is_protocol',
80 'is_typeddict',
81 'Literal',
82 'NewType',
83 'overload',
84 'override',
85 'Protocol',
86 'reveal_type',
87 'runtime',
88 'runtime_checkable',
89 'Text',
90 'TypeAlias',
91 'TypeAliasType',
92 'TypeForm',
93 'TypeGuard',
94 'TypeIs',
95 'TYPE_CHECKING',
96 'Never',
97 'NoReturn',
98 'ReadOnly',
99 'Required',
100 'NotRequired',
101 'NoDefault',
102 'NoExtraItems',
103
104 # Pure aliases, have always been in typing
105 'AbstractSet',
106 'AnyStr',
107 'BinaryIO',
108 'Callable',
109 'Collection',
110 'Container',
111 'Dict',
112 'ForwardRef',
113 'FrozenSet',
114 'Generator',
115 'Generic',
116 'Hashable',
117 'IO',
118 'ItemsView',
119 'Iterable',
120 'Iterator',
121 'KeysView',
122 'List',
123 'Mapping',
124 'MappingView',
125 'Match',
126 'MutableMapping',
127 'MutableSequence',
128 'MutableSet',
129 'Optional',
130 'Pattern',
131 'Reversible',
132 'Sequence',
133 'Set',
134 'Sized',
135 'TextIO',
136 'Tuple',
137 'Union',
138 'ValuesView',
139 'cast',
140 'no_type_check',
141 'no_type_check_decorator',
142]
143
144# for backward compatibility
145PEP_560 = True
146GenericMeta = type
147_PEP_696_IMPLEMENTED = sys.version_info >= (3, 13, 0, "beta")
148
149# Added with bpo-45166 to 3.10.1+ and some 3.9 versions
150_FORWARD_REF_HAS_CLASS = "__forward_is_class__" in typing.ForwardRef.__slots__
151
152# The functions below are modified copies of typing internal helpers.
153# They are needed by _ProtocolMeta and they provide support for PEP 646.
154
155
156class _Sentinel:
157 def __repr__(self):
158 return "<sentinel>"
159
160
161_marker = _Sentinel()
162
163
164if sys.version_info >= (3, 10):
165 def _should_collect_from_parameters(t):
166 return isinstance(
167 t, (typing._GenericAlias, _types.GenericAlias, _types.UnionType)
168 )
169elif sys.version_info >= (3, 9):
170 def _should_collect_from_parameters(t):
171 return isinstance(t, (typing._GenericAlias, _types.GenericAlias))
172else:
173 def _should_collect_from_parameters(t):
174 return isinstance(t, typing._GenericAlias) and not t._special
175
176
177NoReturn = typing.NoReturn
178
179# Some unconstrained type variables. These are used by the container types.
180# (These are not for export.)
181T = typing.TypeVar('T') # Any type.
182KT = typing.TypeVar('KT') # Key type.
183VT = typing.TypeVar('VT') # Value type.
184T_co = typing.TypeVar('T_co', covariant=True) # Any type covariant containers.
185T_contra = typing.TypeVar('T_contra', contravariant=True) # Ditto contravariant.
186
187
188if sys.version_info >= (3, 11):
189 from typing import Any
190else:
191
192 class _AnyMeta(type):
193 def __instancecheck__(self, obj):
194 if self is Any:
195 raise TypeError("typing_extensions.Any cannot be used with isinstance()")
196 return super().__instancecheck__(obj)
197
198 def __repr__(self):
199 if self is Any:
200 return "typing_extensions.Any"
201 return super().__repr__()
202
203 class Any(metaclass=_AnyMeta):
204 """Special type indicating an unconstrained type.
205 - Any is compatible with every type.
206 - Any assumed to have all methods.
207 - All values assumed to be instances of Any.
208 Note that all the above statements are true from the point of view of
209 static type checkers. At runtime, Any should not be used with instance
210 checks.
211 """
212 def __new__(cls, *args, **kwargs):
213 if cls is Any:
214 raise TypeError("Any cannot be instantiated")
215 return super().__new__(cls, *args, **kwargs)
216
217
218ClassVar = typing.ClassVar
219
220
221class _ExtensionsSpecialForm(typing._SpecialForm, _root=True):
222 def __repr__(self):
223 return 'typing_extensions.' + self._name
224
225
226Final = typing.Final
227
228if sys.version_info >= (3, 11):
229 final = typing.final
230else:
231 # @final exists in 3.8+, but we backport it for all versions
232 # before 3.11 to keep support for the __final__ attribute.
233 # See https://bugs.python.org/issue46342
234 def final(f):
235 """This decorator can be used to indicate to type checkers that
236 the decorated method cannot be overridden, and decorated class
237 cannot be subclassed. For example:
238
239 class Base:
240 @final
241 def done(self) -> None:
242 ...
243 class Sub(Base):
244 def done(self) -> None: # Error reported by type checker
245 ...
246 @final
247 class Leaf:
248 ...
249 class Other(Leaf): # Error reported by type checker
250 ...
251
252 There is no runtime checking of these properties. The decorator
253 sets the ``__final__`` attribute to ``True`` on the decorated object
254 to allow runtime introspection.
255 """
256 try:
257 f.__final__ = True
258 except (AttributeError, TypeError):
259 # Skip the attribute silently if it is not writable.
260 # AttributeError happens if the object has __slots__ or a
261 # read-only property, TypeError if it's a builtin class.
262 pass
263 return f
264
265
266def IntVar(name):
267 return typing.TypeVar(name)
268
269
270# A Literal bug was fixed in 3.11.0, 3.10.1 and 3.9.8
271if sys.version_info >= (3, 10, 1):
272 Literal = typing.Literal
273else:
274 def _flatten_literal_params(parameters):
275 """An internal helper for Literal creation: flatten Literals among parameters"""
276 params = []
277 for p in parameters:
278 if isinstance(p, _LiteralGenericAlias):
279 params.extend(p.__args__)
280 else:
281 params.append(p)
282 return tuple(params)
283
284 def _value_and_type_iter(params):
285 for p in params:
286 yield p, type(p)
287
288 class _LiteralGenericAlias(typing._GenericAlias, _root=True):
289 def __eq__(self, other):
290 if not isinstance(other, _LiteralGenericAlias):
291 return NotImplemented
292 these_args_deduped = set(_value_and_type_iter(self.__args__))
293 other_args_deduped = set(_value_and_type_iter(other.__args__))
294 return these_args_deduped == other_args_deduped
295
296 def __hash__(self):
297 return hash(frozenset(_value_and_type_iter(self.__args__)))
298
299 class _LiteralForm(_ExtensionsSpecialForm, _root=True):
300 def __init__(self, doc: str):
301 self._name = 'Literal'
302 self._doc = self.__doc__ = doc
303
304 def __getitem__(self, parameters):
305 if not isinstance(parameters, tuple):
306 parameters = (parameters,)
307
308 parameters = _flatten_literal_params(parameters)
309
310 val_type_pairs = list(_value_and_type_iter(parameters))
311 try:
312 deduped_pairs = set(val_type_pairs)
313 except TypeError:
314 # unhashable parameters
315 pass
316 else:
317 # similar logic to typing._deduplicate on Python 3.9+
318 if len(deduped_pairs) < len(val_type_pairs):
319 new_parameters = []
320 for pair in val_type_pairs:
321 if pair in deduped_pairs:
322 new_parameters.append(pair[0])
323 deduped_pairs.remove(pair)
324 assert not deduped_pairs, deduped_pairs
325 parameters = tuple(new_parameters)
326
327 return _LiteralGenericAlias(self, parameters)
328
329 Literal = _LiteralForm(doc="""\
330 A type that can be used to indicate to type checkers
331 that the corresponding value has a value literally equivalent
332 to the provided parameter. For example:
333
334 var: Literal[4] = 4
335
336 The type checker understands that 'var' is literally equal to
337 the value 4 and no other value.
338
339 Literal[...] cannot be subclassed. There is no runtime
340 checking verifying that the parameter is actually a value
341 instead of a type.""")
342
343
344_overload_dummy = typing._overload_dummy
345
346
347if hasattr(typing, "get_overloads"): # 3.11+
348 overload = typing.overload
349 get_overloads = typing.get_overloads
350 clear_overloads = typing.clear_overloads
351else:
352 # {module: {qualname: {firstlineno: func}}}
353 _overload_registry = collections.defaultdict(
354 functools.partial(collections.defaultdict, dict)
355 )
356
357 def overload(func):
358 """Decorator for overloaded functions/methods.
359
360 In a stub file, place two or more stub definitions for the same
361 function in a row, each decorated with @overload. For example:
362
363 @overload
364 def utf8(value: None) -> None: ...
365 @overload
366 def utf8(value: bytes) -> bytes: ...
367 @overload
368 def utf8(value: str) -> bytes: ...
369
370 In a non-stub file (i.e. a regular .py file), do the same but
371 follow it with an implementation. The implementation should *not*
372 be decorated with @overload. For example:
373
374 @overload
375 def utf8(value: None) -> None: ...
376 @overload
377 def utf8(value: bytes) -> bytes: ...
378 @overload
379 def utf8(value: str) -> bytes: ...
380 def utf8(value):
381 # implementation goes here
382
383 The overloads for a function can be retrieved at runtime using the
384 get_overloads() function.
385 """
386 # classmethod and staticmethod
387 f = getattr(func, "__func__", func)
388 try:
389 _overload_registry[f.__module__][f.__qualname__][
390 f.__code__.co_firstlineno
391 ] = func
392 except AttributeError:
393 # Not a normal function; ignore.
394 pass
395 return _overload_dummy
396
397 def get_overloads(func):
398 """Return all defined overloads for *func* as a sequence."""
399 # classmethod and staticmethod
400 f = getattr(func, "__func__", func)
401 if f.__module__ not in _overload_registry:
402 return []
403 mod_dict = _overload_registry[f.__module__]
404 if f.__qualname__ not in mod_dict:
405 return []
406 return list(mod_dict[f.__qualname__].values())
407
408 def clear_overloads():
409 """Clear all overloads in the registry."""
410 _overload_registry.clear()
411
412
413# This is not a real generic class. Don't use outside annotations.
414Type = typing.Type
415
416# Various ABCs mimicking those in collections.abc.
417# A few are simply re-exported for completeness.
418Awaitable = typing.Awaitable
419Coroutine = typing.Coroutine
420AsyncIterable = typing.AsyncIterable
421AsyncIterator = typing.AsyncIterator
422Deque = typing.Deque
423DefaultDict = typing.DefaultDict
424OrderedDict = typing.OrderedDict
425Counter = typing.Counter
426ChainMap = typing.ChainMap
427Text = typing.Text
428TYPE_CHECKING = typing.TYPE_CHECKING
429
430
431if sys.version_info >= (3, 13, 0, "beta"):
432 from typing import AsyncContextManager, AsyncGenerator, ContextManager, Generator
433else:
434 def _is_dunder(attr):
435 return attr.startswith('__') and attr.endswith('__')
436
437 # Python <3.9 doesn't have typing._SpecialGenericAlias
438 _special_generic_alias_base = getattr(
439 typing, "_SpecialGenericAlias", typing._GenericAlias
440 )
441
442 class _SpecialGenericAlias(_special_generic_alias_base, _root=True):
443 def __init__(self, origin, nparams, *, inst=True, name=None, defaults=()):
444 if _special_generic_alias_base is typing._GenericAlias:
445 # Python <3.9
446 self.__origin__ = origin
447 self._nparams = nparams
448 super().__init__(origin, nparams, special=True, inst=inst, name=name)
449 else:
450 # Python >= 3.9
451 super().__init__(origin, nparams, inst=inst, name=name)
452 self._defaults = defaults
453
454 def __setattr__(self, attr, val):
455 allowed_attrs = {'_name', '_inst', '_nparams', '_defaults'}
456 if _special_generic_alias_base is typing._GenericAlias:
457 # Python <3.9
458 allowed_attrs.add("__origin__")
459 if _is_dunder(attr) or attr in allowed_attrs:
460 object.__setattr__(self, attr, val)
461 else:
462 setattr(self.__origin__, attr, val)
463
464 @typing._tp_cache
465 def __getitem__(self, params):
466 if not isinstance(params, tuple):
467 params = (params,)
468 msg = "Parameters to generic types must be types."
469 params = tuple(typing._type_check(p, msg) for p in params)
470 if (
471 self._defaults
472 and len(params) < self._nparams
473 and len(params) + len(self._defaults) >= self._nparams
474 ):
475 params = (*params, *self._defaults[len(params) - self._nparams:])
476 actual_len = len(params)
477
478 if actual_len != self._nparams:
479 if self._defaults:
480 expected = f"at least {self._nparams - len(self._defaults)}"
481 else:
482 expected = str(self._nparams)
483 if not self._nparams:
484 raise TypeError(f"{self} is not a generic class")
485 raise TypeError(
486 f"Too {'many' if actual_len > self._nparams else 'few'}"
487 f" arguments for {self};"
488 f" actual {actual_len}, expected {expected}"
489 )
490 return self.copy_with(params)
491
492 _NoneType = type(None)
493 Generator = _SpecialGenericAlias(
494 collections.abc.Generator, 3, defaults=(_NoneType, _NoneType)
495 )
496 AsyncGenerator = _SpecialGenericAlias(
497 collections.abc.AsyncGenerator, 2, defaults=(_NoneType,)
498 )
499 ContextManager = _SpecialGenericAlias(
500 contextlib.AbstractContextManager,
501 2,
502 name="ContextManager",
503 defaults=(typing.Optional[bool],)
504 )
505 AsyncContextManager = _SpecialGenericAlias(
506 contextlib.AbstractAsyncContextManager,
507 2,
508 name="AsyncContextManager",
509 defaults=(typing.Optional[bool],)
510 )
511
512
513_PROTO_ALLOWLIST = {
514 'collections.abc': [
515 'Callable', 'Awaitable', 'Iterable', 'Iterator', 'AsyncIterable',
516 'Hashable', 'Sized', 'Container', 'Collection', 'Reversible', 'Buffer',
517 ],
518 'contextlib': ['AbstractContextManager', 'AbstractAsyncContextManager'],
519 'typing_extensions': ['Buffer'],
520}
521
522
523_EXCLUDED_ATTRS = frozenset(typing.EXCLUDED_ATTRIBUTES) | {
524 "__match_args__", "__protocol_attrs__", "__non_callable_proto_members__",
525 "__final__",
526}
527
528
529def _get_protocol_attrs(cls):
530 attrs = set()
531 for base in cls.__mro__[:-1]: # without object
532 if base.__name__ in {'Protocol', 'Generic'}:
533 continue
534 annotations = getattr(base, '__annotations__', {})
535 for attr in (*base.__dict__, *annotations):
536 if (not attr.startswith('_abc_') and attr not in _EXCLUDED_ATTRS):
537 attrs.add(attr)
538 return attrs
539
540
541def _caller(depth=2):
542 try:
543 return sys._getframe(depth).f_globals.get('__name__', '__main__')
544 except (AttributeError, ValueError): # For platforms without _getframe()
545 return None
546
547
548# `__match_args__` attribute was removed from protocol members in 3.13,
549# we want to backport this change to older Python versions.
550if sys.version_info >= (3, 13):
551 Protocol = typing.Protocol
552else:
553 def _allow_reckless_class_checks(depth=3):
554 """Allow instance and class checks for special stdlib modules.
555 The abc and functools modules indiscriminately call isinstance() and
556 issubclass() on the whole MRO of a user class, which may contain protocols.
557 """
558 return _caller(depth) in {'abc', 'functools', None}
559
560 def _no_init(self, *args, **kwargs):
561 if type(self)._is_protocol:
562 raise TypeError('Protocols cannot be instantiated')
563
564 def _type_check_issubclass_arg_1(arg):
565 """Raise TypeError if `arg` is not an instance of `type`
566 in `issubclass(arg, <protocol>)`.
567
568 In most cases, this is verified by type.__subclasscheck__.
569 Checking it again unnecessarily would slow down issubclass() checks,
570 so, we don't perform this check unless we absolutely have to.
571
572 For various error paths, however,
573 we want to ensure that *this* error message is shown to the user
574 where relevant, rather than a typing.py-specific error message.
575 """
576 if not isinstance(arg, type):
577 # Same error message as for issubclass(1, int).
578 raise TypeError('issubclass() arg 1 must be a class')
579
580 # Inheriting from typing._ProtocolMeta isn't actually desirable,
581 # but is necessary to allow typing.Protocol and typing_extensions.Protocol
582 # to mix without getting TypeErrors about "metaclass conflict"
583 class _ProtocolMeta(type(typing.Protocol)):
584 # This metaclass is somewhat unfortunate,
585 # but is necessary for several reasons...
586 #
587 # NOTE: DO NOT call super() in any methods in this class
588 # That would call the methods on typing._ProtocolMeta on Python 3.8-3.11
589 # and those are slow
590 def __new__(mcls, name, bases, namespace, **kwargs):
591 if name == "Protocol" and len(bases) < 2:
592 pass
593 elif {Protocol, typing.Protocol} & set(bases):
594 for base in bases:
595 if not (
596 base in {object, typing.Generic, Protocol, typing.Protocol}
597 or base.__name__ in _PROTO_ALLOWLIST.get(base.__module__, [])
598 or is_protocol(base)
599 ):
600 raise TypeError(
601 f"Protocols can only inherit from other protocols, "
602 f"got {base!r}"
603 )
604 return abc.ABCMeta.__new__(mcls, name, bases, namespace, **kwargs)
605
606 def __init__(cls, *args, **kwargs):
607 abc.ABCMeta.__init__(cls, *args, **kwargs)
608 if getattr(cls, "_is_protocol", False):
609 cls.__protocol_attrs__ = _get_protocol_attrs(cls)
610
611 def __subclasscheck__(cls, other):
612 if cls is Protocol:
613 return type.__subclasscheck__(cls, other)
614 if (
615 getattr(cls, '_is_protocol', False)
616 and not _allow_reckless_class_checks()
617 ):
618 if not getattr(cls, '_is_runtime_protocol', False):
619 _type_check_issubclass_arg_1(other)
620 raise TypeError(
621 "Instance and class checks can only be used with "
622 "@runtime_checkable protocols"
623 )
624 if (
625 # this attribute is set by @runtime_checkable:
626 cls.__non_callable_proto_members__
627 and cls.__dict__.get("__subclasshook__") is _proto_hook
628 ):
629 _type_check_issubclass_arg_1(other)
630 non_method_attrs = sorted(cls.__non_callable_proto_members__)
631 raise TypeError(
632 "Protocols with non-method members don't support issubclass()."
633 f" Non-method members: {str(non_method_attrs)[1:-1]}."
634 )
635 return abc.ABCMeta.__subclasscheck__(cls, other)
636
637 def __instancecheck__(cls, instance):
638 # We need this method for situations where attributes are
639 # assigned in __init__.
640 if cls is Protocol:
641 return type.__instancecheck__(cls, instance)
642 if not getattr(cls, "_is_protocol", False):
643 # i.e., it's a concrete subclass of a protocol
644 return abc.ABCMeta.__instancecheck__(cls, instance)
645
646 if (
647 not getattr(cls, '_is_runtime_protocol', False) and
648 not _allow_reckless_class_checks()
649 ):
650 raise TypeError("Instance and class checks can only be used with"
651 " @runtime_checkable protocols")
652
653 if abc.ABCMeta.__instancecheck__(cls, instance):
654 return True
655
656 for attr in cls.__protocol_attrs__:
657 try:
658 val = inspect.getattr_static(instance, attr)
659 except AttributeError:
660 break
661 # this attribute is set by @runtime_checkable:
662 if val is None and attr not in cls.__non_callable_proto_members__:
663 break
664 else:
665 return True
666
667 return False
668
669 def __eq__(cls, other):
670 # Hack so that typing.Generic.__class_getitem__
671 # treats typing_extensions.Protocol
672 # as equivalent to typing.Protocol
673 if abc.ABCMeta.__eq__(cls, other) is True:
674 return True
675 return cls is Protocol and other is typing.Protocol
676
677 # This has to be defined, or the abc-module cache
678 # complains about classes with this metaclass being unhashable,
679 # if we define only __eq__!
680 def __hash__(cls) -> int:
681 return type.__hash__(cls)
682
683 @classmethod
684 def _proto_hook(cls, other):
685 if not cls.__dict__.get('_is_protocol', False):
686 return NotImplemented
687
688 for attr in cls.__protocol_attrs__:
689 for base in other.__mro__:
690 # Check if the members appears in the class dictionary...
691 if attr in base.__dict__:
692 if base.__dict__[attr] is None:
693 return NotImplemented
694 break
695
696 # ...or in annotations, if it is a sub-protocol.
697 annotations = getattr(base, '__annotations__', {})
698 if (
699 isinstance(annotations, collections.abc.Mapping)
700 and attr in annotations
701 and is_protocol(other)
702 ):
703 break
704 else:
705 return NotImplemented
706 return True
707
708 class Protocol(typing.Generic, metaclass=_ProtocolMeta):
709 __doc__ = typing.Protocol.__doc__
710 __slots__ = ()
711 _is_protocol = True
712 _is_runtime_protocol = False
713
714 def __init_subclass__(cls, *args, **kwargs):
715 super().__init_subclass__(*args, **kwargs)
716
717 # Determine if this is a protocol or a concrete subclass.
718 if not cls.__dict__.get('_is_protocol', False):
719 cls._is_protocol = any(b is Protocol for b in cls.__bases__)
720
721 # Set (or override) the protocol subclass hook.
722 if '__subclasshook__' not in cls.__dict__:
723 cls.__subclasshook__ = _proto_hook
724
725 # Prohibit instantiation for protocol classes
726 if cls._is_protocol and cls.__init__ is Protocol.__init__:
727 cls.__init__ = _no_init
728
729
730if sys.version_info >= (3, 13):
731 runtime_checkable = typing.runtime_checkable
732else:
733 def runtime_checkable(cls):
734 """Mark a protocol class as a runtime protocol.
735
736 Such protocol can be used with isinstance() and issubclass().
737 Raise TypeError if applied to a non-protocol class.
738 This allows a simple-minded structural check very similar to
739 one trick ponies in collections.abc such as Iterable.
740
741 For example::
742
743 @runtime_checkable
744 class Closable(Protocol):
745 def close(self): ...
746
747 assert isinstance(open('/some/file'), Closable)
748
749 Warning: this will check only the presence of the required methods,
750 not their type signatures!
751 """
752 if not issubclass(cls, typing.Generic) or not getattr(cls, '_is_protocol', False):
753 raise TypeError(f'@runtime_checkable can be only applied to protocol classes,'
754 f' got {cls!r}')
755 cls._is_runtime_protocol = True
756
757 # typing.Protocol classes on <=3.11 break if we execute this block,
758 # because typing.Protocol classes on <=3.11 don't have a
759 # `__protocol_attrs__` attribute, and this block relies on the
760 # `__protocol_attrs__` attribute. Meanwhile, typing.Protocol classes on 3.12.2+
761 # break if we *don't* execute this block, because *they* assume that all
762 # protocol classes have a `__non_callable_proto_members__` attribute
763 # (which this block sets)
764 if isinstance(cls, _ProtocolMeta) or sys.version_info >= (3, 12, 2):
765 # PEP 544 prohibits using issubclass()
766 # with protocols that have non-method members.
767 # See gh-113320 for why we compute this attribute here,
768 # rather than in `_ProtocolMeta.__init__`
769 cls.__non_callable_proto_members__ = set()
770 for attr in cls.__protocol_attrs__:
771 try:
772 is_callable = callable(getattr(cls, attr, None))
773 except Exception as e:
774 raise TypeError(
775 f"Failed to determine whether protocol member {attr!r} "
776 "is a method member"
777 ) from e
778 else:
779 if not is_callable:
780 cls.__non_callable_proto_members__.add(attr)
781
782 return cls
783
784
785# The "runtime" alias exists for backwards compatibility.
786runtime = runtime_checkable
787
788
789# Our version of runtime-checkable protocols is faster on Python 3.8-3.11
790if sys.version_info >= (3, 12):
791 SupportsInt = typing.SupportsInt
792 SupportsFloat = typing.SupportsFloat
793 SupportsComplex = typing.SupportsComplex
794 SupportsBytes = typing.SupportsBytes
795 SupportsIndex = typing.SupportsIndex
796 SupportsAbs = typing.SupportsAbs
797 SupportsRound = typing.SupportsRound
798else:
799 @runtime_checkable
800 class SupportsInt(Protocol):
801 """An ABC with one abstract method __int__."""
802 __slots__ = ()
803
804 @abc.abstractmethod
805 def __int__(self) -> int:
806 pass
807
808 @runtime_checkable
809 class SupportsFloat(Protocol):
810 """An ABC with one abstract method __float__."""
811 __slots__ = ()
812
813 @abc.abstractmethod
814 def __float__(self) -> float:
815 pass
816
817 @runtime_checkable
818 class SupportsComplex(Protocol):
819 """An ABC with one abstract method __complex__."""
820 __slots__ = ()
821
822 @abc.abstractmethod
823 def __complex__(self) -> complex:
824 pass
825
826 @runtime_checkable
827 class SupportsBytes(Protocol):
828 """An ABC with one abstract method __bytes__."""
829 __slots__ = ()
830
831 @abc.abstractmethod
832 def __bytes__(self) -> bytes:
833 pass
834
835 @runtime_checkable
836 class SupportsIndex(Protocol):
837 __slots__ = ()
838
839 @abc.abstractmethod
840 def __index__(self) -> int:
841 pass
842
843 @runtime_checkable
844 class SupportsAbs(Protocol[T_co]):
845 """
846 An ABC with one abstract method __abs__ that is covariant in its return type.
847 """
848 __slots__ = ()
849
850 @abc.abstractmethod
851 def __abs__(self) -> T_co:
852 pass
853
854 @runtime_checkable
855 class SupportsRound(Protocol[T_co]):
856 """
857 An ABC with one abstract method __round__ that is covariant in its return type.
858 """
859 __slots__ = ()
860
861 @abc.abstractmethod
862 def __round__(self, ndigits: int = 0) -> T_co:
863 pass
864
865
866def _ensure_subclassable(mro_entries):
867 def inner(func):
868 if sys.implementation.name == "pypy" and sys.version_info < (3, 9):
869 cls_dict = {
870 "__call__": staticmethod(func),
871 "__mro_entries__": staticmethod(mro_entries)
872 }
873 t = type(func.__name__, (), cls_dict)
874 return functools.update_wrapper(t(), func)
875 else:
876 func.__mro_entries__ = mro_entries
877 return func
878 return inner
879
880
881_NEEDS_SINGLETONMETA = (
882 not hasattr(typing, "NoDefault") or not hasattr(typing, "NoExtraItems")
883)
884
885if _NEEDS_SINGLETONMETA:
886 class SingletonMeta(type):
887 def __setattr__(cls, attr, value):
888 # TypeError is consistent with the behavior of NoneType
889 raise TypeError(
890 f"cannot set {attr!r} attribute of immutable type {cls.__name__!r}"
891 )
892
893
894if hasattr(typing, "NoDefault"):
895 NoDefault = typing.NoDefault
896else:
897 class NoDefaultType(metaclass=SingletonMeta):
898 """The type of the NoDefault singleton."""
899
900 __slots__ = ()
901
902 def __new__(cls):
903 return globals().get("NoDefault") or object.__new__(cls)
904
905 def __repr__(self):
906 return "typing_extensions.NoDefault"
907
908 def __reduce__(self):
909 return "NoDefault"
910
911 NoDefault = NoDefaultType()
912 del NoDefaultType
913
914if hasattr(typing, "NoExtraItems"):
915 NoExtraItems = typing.NoExtraItems
916else:
917 class NoExtraItemsType(metaclass=SingletonMeta):
918 """The type of the NoExtraItems singleton."""
919
920 __slots__ = ()
921
922 def __new__(cls):
923 return globals().get("NoExtraItems") or object.__new__(cls)
924
925 def __repr__(self):
926 return "typing_extensions.NoExtraItems"
927
928 def __reduce__(self):
929 return "NoExtraItems"
930
931 NoExtraItems = NoExtraItemsType()
932 del NoExtraItemsType
933
934if _NEEDS_SINGLETONMETA:
935 del SingletonMeta
936
937
938# Update this to something like >=3.13.0b1 if and when
939# PEP 728 is implemented in CPython
940_PEP_728_IMPLEMENTED = False
941
942if _PEP_728_IMPLEMENTED:
943 # The standard library TypedDict in Python 3.8 does not store runtime information
944 # about which (if any) keys are optional. See https://bugs.python.org/issue38834
945 # The standard library TypedDict in Python 3.9.0/1 does not honour the "total"
946 # keyword with old-style TypedDict(). See https://bugs.python.org/issue42059
947 # The standard library TypedDict below Python 3.11 does not store runtime
948 # information about optional and required keys when using Required or NotRequired.
949 # Generic TypedDicts are also impossible using typing.TypedDict on Python <3.11.
950 # Aaaand on 3.12 we add __orig_bases__ to TypedDict
951 # to enable better runtime introspection.
952 # On 3.13 we deprecate some odd ways of creating TypedDicts.
953 # Also on 3.13, PEP 705 adds the ReadOnly[] qualifier.
954 # PEP 728 (still pending) makes more changes.
955 TypedDict = typing.TypedDict
956 _TypedDictMeta = typing._TypedDictMeta
957 is_typeddict = typing.is_typeddict
958else:
959 # 3.10.0 and later
960 _TAKES_MODULE = "module" in inspect.signature(typing._type_check).parameters
961
962 def _get_typeddict_qualifiers(annotation_type):
963 while True:
964 annotation_origin = get_origin(annotation_type)
965 if annotation_origin is Annotated:
966 annotation_args = get_args(annotation_type)
967 if annotation_args:
968 annotation_type = annotation_args[0]
969 else:
970 break
971 elif annotation_origin is Required:
972 yield Required
973 annotation_type, = get_args(annotation_type)
974 elif annotation_origin is NotRequired:
975 yield NotRequired
976 annotation_type, = get_args(annotation_type)
977 elif annotation_origin is ReadOnly:
978 yield ReadOnly
979 annotation_type, = get_args(annotation_type)
980 else:
981 break
982
983 class _TypedDictMeta(type):
984
985 def __new__(cls, name, bases, ns, *, total=True, closed=None,
986 extra_items=NoExtraItems):
987 """Create new typed dict class object.
988
989 This method is called when TypedDict is subclassed,
990 or when TypedDict is instantiated. This way
991 TypedDict supports all three syntax forms described in its docstring.
992 Subclasses and instances of TypedDict return actual dictionaries.
993 """
994 for base in bases:
995 if type(base) is not _TypedDictMeta and base is not typing.Generic:
996 raise TypeError('cannot inherit from both a TypedDict type '
997 'and a non-TypedDict base class')
998 if closed is not None and extra_items is not NoExtraItems:
999 raise TypeError(f"Cannot combine closed={closed!r} and extra_items")
1000
1001 if any(issubclass(b, typing.Generic) for b in bases):
1002 generic_base = (typing.Generic,)
1003 else:
1004 generic_base = ()
1005
1006 # typing.py generally doesn't let you inherit from plain Generic, unless
1007 # the name of the class happens to be "Protocol"
1008 tp_dict = type.__new__(_TypedDictMeta, "Protocol", (*generic_base, dict), ns)
1009 tp_dict.__name__ = name
1010 if tp_dict.__qualname__ == "Protocol":
1011 tp_dict.__qualname__ = name
1012
1013 if not hasattr(tp_dict, '__orig_bases__'):
1014 tp_dict.__orig_bases__ = bases
1015
1016 annotations = {}
1017 if "__annotations__" in ns:
1018 own_annotations = ns["__annotations__"]
1019 elif "__annotate__" in ns:
1020 # TODO: Use inspect.VALUE here, and make the annotations lazily evaluated
1021 own_annotations = ns["__annotate__"](1)
1022 else:
1023 own_annotations = {}
1024 msg = "TypedDict('Name', {f0: t0, f1: t1, ...}); each t must be a type"
1025 if _TAKES_MODULE:
1026 own_annotations = {
1027 n: typing._type_check(tp, msg, module=tp_dict.__module__)
1028 for n, tp in own_annotations.items()
1029 }
1030 else:
1031 own_annotations = {
1032 n: typing._type_check(tp, msg)
1033 for n, tp in own_annotations.items()
1034 }
1035 required_keys = set()
1036 optional_keys = set()
1037 readonly_keys = set()
1038 mutable_keys = set()
1039 extra_items_type = extra_items
1040
1041 for base in bases:
1042 base_dict = base.__dict__
1043
1044 annotations.update(base_dict.get('__annotations__', {}))
1045 required_keys.update(base_dict.get('__required_keys__', ()))
1046 optional_keys.update(base_dict.get('__optional_keys__', ()))
1047 readonly_keys.update(base_dict.get('__readonly_keys__', ()))
1048 mutable_keys.update(base_dict.get('__mutable_keys__', ()))
1049
1050 # This was specified in an earlier version of PEP 728. Support
1051 # is retained for backwards compatibility, but only for Python
1052 # 3.13 and lower.
1053 if (closed and sys.version_info < (3, 14)
1054 and "__extra_items__" in own_annotations):
1055 annotation_type = own_annotations.pop("__extra_items__")
1056 qualifiers = set(_get_typeddict_qualifiers(annotation_type))
1057 if Required in qualifiers:
1058 raise TypeError(
1059 "Special key __extra_items__ does not support "
1060 "Required"
1061 )
1062 if NotRequired in qualifiers:
1063 raise TypeError(
1064 "Special key __extra_items__ does not support "
1065 "NotRequired"
1066 )
1067 extra_items_type = annotation_type
1068
1069 annotations.update(own_annotations)
1070 for annotation_key, annotation_type in own_annotations.items():
1071 qualifiers = set(_get_typeddict_qualifiers(annotation_type))
1072
1073 if Required in qualifiers:
1074 required_keys.add(annotation_key)
1075 elif NotRequired in qualifiers:
1076 optional_keys.add(annotation_key)
1077 elif total:
1078 required_keys.add(annotation_key)
1079 else:
1080 optional_keys.add(annotation_key)
1081 if ReadOnly in qualifiers:
1082 mutable_keys.discard(annotation_key)
1083 readonly_keys.add(annotation_key)
1084 else:
1085 mutable_keys.add(annotation_key)
1086 readonly_keys.discard(annotation_key)
1087
1088 tp_dict.__annotations__ = annotations
1089 tp_dict.__required_keys__ = frozenset(required_keys)
1090 tp_dict.__optional_keys__ = frozenset(optional_keys)
1091 tp_dict.__readonly_keys__ = frozenset(readonly_keys)
1092 tp_dict.__mutable_keys__ = frozenset(mutable_keys)
1093 tp_dict.__total__ = total
1094 tp_dict.__closed__ = closed
1095 tp_dict.__extra_items__ = extra_items_type
1096 return tp_dict
1097
1098 __call__ = dict # static method
1099
1100 def __subclasscheck__(cls, other):
1101 # Typed dicts are only for static structural subtyping.
1102 raise TypeError('TypedDict does not support instance and class checks')
1103
1104 __instancecheck__ = __subclasscheck__
1105
1106 _TypedDict = type.__new__(_TypedDictMeta, 'TypedDict', (), {})
1107
1108 @_ensure_subclassable(lambda bases: (_TypedDict,))
1109 def TypedDict(
1110 typename,
1111 fields=_marker,
1112 /,
1113 *,
1114 total=True,
1115 closed=None,
1116 extra_items=NoExtraItems,
1117 **kwargs
1118 ):
1119 """A simple typed namespace. At runtime it is equivalent to a plain dict.
1120
1121 TypedDict creates a dictionary type such that a type checker will expect all
1122 instances to have a certain set of keys, where each key is
1123 associated with a value of a consistent type. This expectation
1124 is not checked at runtime.
1125
1126 Usage::
1127
1128 class Point2D(TypedDict):
1129 x: int
1130 y: int
1131 label: str
1132
1133 a: Point2D = {'x': 1, 'y': 2, 'label': 'good'} # OK
1134 b: Point2D = {'z': 3, 'label': 'bad'} # Fails type check
1135
1136 assert Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first')
1137
1138 The type info can be accessed via the Point2D.__annotations__ dict, and
1139 the Point2D.__required_keys__ and Point2D.__optional_keys__ frozensets.
1140 TypedDict supports an additional equivalent form::
1141
1142 Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str})
1143
1144 By default, all keys must be present in a TypedDict. It is possible
1145 to override this by specifying totality::
1146
1147 class Point2D(TypedDict, total=False):
1148 x: int
1149 y: int
1150
1151 This means that a Point2D TypedDict can have any of the keys omitted. A type
1152 checker is only expected to support a literal False or True as the value of
1153 the total argument. True is the default, and makes all items defined in the
1154 class body be required.
1155
1156 The Required and NotRequired special forms can also be used to mark
1157 individual keys as being required or not required::
1158
1159 class Point2D(TypedDict):
1160 x: int # the "x" key must always be present (Required is the default)
1161 y: NotRequired[int] # the "y" key can be omitted
1162
1163 See PEP 655 for more details on Required and NotRequired.
1164 """
1165 if fields is _marker or fields is None:
1166 if fields is _marker:
1167 deprecated_thing = "Failing to pass a value for the 'fields' parameter"
1168 else:
1169 deprecated_thing = "Passing `None` as the 'fields' parameter"
1170
1171 example = f"`{typename} = TypedDict({typename!r}, {{}})`"
1172 deprecation_msg = (
1173 f"{deprecated_thing} is deprecated and will be disallowed in "
1174 "Python 3.15. To create a TypedDict class with 0 fields "
1175 "using the functional syntax, pass an empty dictionary, e.g. "
1176 ) + example + "."
1177 warnings.warn(deprecation_msg, DeprecationWarning, stacklevel=2)
1178 # Support a field called "closed"
1179 if closed is not False and closed is not True and closed is not None:
1180 kwargs["closed"] = closed
1181 closed = None
1182 # Or "extra_items"
1183 if extra_items is not NoExtraItems:
1184 kwargs["extra_items"] = extra_items
1185 extra_items = NoExtraItems
1186 fields = kwargs
1187 elif kwargs:
1188 raise TypeError("TypedDict takes either a dict or keyword arguments,"
1189 " but not both")
1190 if kwargs:
1191 if sys.version_info >= (3, 13):
1192 raise TypeError("TypedDict takes no keyword arguments")
1193 warnings.warn(
1194 "The kwargs-based syntax for TypedDict definitions is deprecated "
1195 "in Python 3.11, will be removed in Python 3.13, and may not be "
1196 "understood by third-party type checkers.",
1197 DeprecationWarning,
1198 stacklevel=2,
1199 )
1200
1201 ns = {'__annotations__': dict(fields)}
1202 module = _caller()
1203 if module is not None:
1204 # Setting correct module is necessary to make typed dict classes pickleable.
1205 ns['__module__'] = module
1206
1207 td = _TypedDictMeta(typename, (), ns, total=total, closed=closed,
1208 extra_items=extra_items)
1209 td.__orig_bases__ = (TypedDict,)
1210 return td
1211
1212 if hasattr(typing, "_TypedDictMeta"):
1213 _TYPEDDICT_TYPES = (typing._TypedDictMeta, _TypedDictMeta)
1214 else:
1215 _TYPEDDICT_TYPES = (_TypedDictMeta,)
1216
1217 def is_typeddict(tp):
1218 """Check if an annotation is a TypedDict class
1219
1220 For example::
1221 class Film(TypedDict):
1222 title: str
1223 year: int
1224
1225 is_typeddict(Film) # => True
1226 is_typeddict(Union[list, str]) # => False
1227 """
1228 # On 3.8, this would otherwise return True
1229 if hasattr(typing, "TypedDict") and tp is typing.TypedDict:
1230 return False
1231 return isinstance(tp, _TYPEDDICT_TYPES)
1232
1233
1234if hasattr(typing, "assert_type"):
1235 assert_type = typing.assert_type
1236
1237else:
1238 def assert_type(val, typ, /):
1239 """Assert (to the type checker) that the value is of the given type.
1240
1241 When the type checker encounters a call to assert_type(), it
1242 emits an error if the value is not of the specified type::
1243
1244 def greet(name: str) -> None:
1245 assert_type(name, str) # ok
1246 assert_type(name, int) # type checker error
1247
1248 At runtime this returns the first argument unchanged and otherwise
1249 does nothing.
1250 """
1251 return val
1252
1253
1254if hasattr(typing, "ReadOnly"): # 3.13+
1255 get_type_hints = typing.get_type_hints
1256else: # <=3.13
1257 # replaces _strip_annotations()
1258 def _strip_extras(t):
1259 """Strips Annotated, Required and NotRequired from a given type."""
1260 if isinstance(t, _AnnotatedAlias):
1261 return _strip_extras(t.__origin__)
1262 if hasattr(t, "__origin__") and t.__origin__ in (Required, NotRequired, ReadOnly):
1263 return _strip_extras(t.__args__[0])
1264 if isinstance(t, typing._GenericAlias):
1265 stripped_args = tuple(_strip_extras(a) for a in t.__args__)
1266 if stripped_args == t.__args__:
1267 return t
1268 return t.copy_with(stripped_args)
1269 if hasattr(_types, "GenericAlias") and isinstance(t, _types.GenericAlias):
1270 stripped_args = tuple(_strip_extras(a) for a in t.__args__)
1271 if stripped_args == t.__args__:
1272 return t
1273 return _types.GenericAlias(t.__origin__, stripped_args)
1274 if hasattr(_types, "UnionType") and isinstance(t, _types.UnionType):
1275 stripped_args = tuple(_strip_extras(a) for a in t.__args__)
1276 if stripped_args == t.__args__:
1277 return t
1278 return functools.reduce(operator.or_, stripped_args)
1279
1280 return t
1281
1282 def get_type_hints(obj, globalns=None, localns=None, include_extras=False):
1283 """Return type hints for an object.
1284
1285 This is often the same as obj.__annotations__, but it handles
1286 forward references encoded as string literals, adds Optional[t] if a
1287 default value equal to None is set and recursively replaces all
1288 'Annotated[T, ...]', 'Required[T]' or 'NotRequired[T]' with 'T'
1289 (unless 'include_extras=True').
1290
1291 The argument may be a module, class, method, or function. The annotations
1292 are returned as a dictionary. For classes, annotations include also
1293 inherited members.
1294
1295 TypeError is raised if the argument is not of a type that can contain
1296 annotations, and an empty dictionary is returned if no annotations are
1297 present.
1298
1299 BEWARE -- the behavior of globalns and localns is counterintuitive
1300 (unless you are familiar with how eval() and exec() work). The
1301 search order is locals first, then globals.
1302
1303 - If no dict arguments are passed, an attempt is made to use the
1304 globals from obj (or the respective module's globals for classes),
1305 and these are also used as the locals. If the object does not appear
1306 to have globals, an empty dictionary is used.
1307
1308 - If one dict argument is passed, it is used for both globals and
1309 locals.
1310
1311 - If two dict arguments are passed, they specify globals and
1312 locals, respectively.
1313 """
1314 if hasattr(typing, "Annotated"): # 3.9+
1315 hint = typing.get_type_hints(
1316 obj, globalns=globalns, localns=localns, include_extras=True
1317 )
1318 else: # 3.8
1319 hint = typing.get_type_hints(obj, globalns=globalns, localns=localns)
1320 if sys.version_info < (3, 11):
1321 _clean_optional(obj, hint, globalns, localns)
1322 if sys.version_info < (3, 9):
1323 # In 3.8 eval_type does not flatten Optional[ForwardRef] correctly
1324 # This will recreate and and cache Unions.
1325 hint = {
1326 k: (t
1327 if get_origin(t) != Union
1328 else Union[t.__args__])
1329 for k, t in hint.items()
1330 }
1331 if include_extras:
1332 return hint
1333 return {k: _strip_extras(t) for k, t in hint.items()}
1334
1335 _NoneType = type(None)
1336
1337 def _could_be_inserted_optional(t):
1338 """detects Union[..., None] pattern"""
1339 # 3.8+ compatible checking before _UnionGenericAlias
1340 if get_origin(t) is not Union:
1341 return False
1342 # Assume if last argument is not None they are user defined
1343 if t.__args__[-1] is not _NoneType:
1344 return False
1345 return True
1346
1347 # < 3.11
1348 def _clean_optional(obj, hints, globalns=None, localns=None):
1349 # reverts injected Union[..., None] cases from typing.get_type_hints
1350 # when a None default value is used.
1351 # see https://github.com/python/typing_extensions/issues/310
1352 if not hints or isinstance(obj, type):
1353 return
1354 defaults = typing._get_defaults(obj) # avoid accessing __annotations___
1355 if not defaults:
1356 return
1357 original_hints = obj.__annotations__
1358 for name, value in hints.items():
1359 # Not a Union[..., None] or replacement conditions not fullfilled
1360 if (not _could_be_inserted_optional(value)
1361 or name not in defaults
1362 or defaults[name] is not None
1363 ):
1364 continue
1365 original_value = original_hints[name]
1366 # value=NoneType should have caused a skip above but check for safety
1367 if original_value is None:
1368 original_value = _NoneType
1369 # Forward reference
1370 if isinstance(original_value, str):
1371 if globalns is None:
1372 if isinstance(obj, _types.ModuleType):
1373 globalns = obj.__dict__
1374 else:
1375 nsobj = obj
1376 # Find globalns for the unwrapped object.
1377 while hasattr(nsobj, '__wrapped__'):
1378 nsobj = nsobj.__wrapped__
1379 globalns = getattr(nsobj, '__globals__', {})
1380 if localns is None:
1381 localns = globalns
1382 elif localns is None:
1383 localns = globalns
1384 if sys.version_info < (3, 9):
1385 original_value = ForwardRef(original_value)
1386 else:
1387 original_value = ForwardRef(
1388 original_value,
1389 is_argument=not isinstance(obj, _types.ModuleType)
1390 )
1391 original_evaluated = typing._eval_type(original_value, globalns, localns)
1392 if sys.version_info < (3, 9) and get_origin(original_evaluated) is Union:
1393 # Union[str, None, "str"] is not reduced to Union[str, None]
1394 original_evaluated = Union[original_evaluated.__args__]
1395 # Compare if values differ. Note that even if equal
1396 # value might be cached by typing._tp_cache contrary to original_evaluated
1397 if original_evaluated != value or (
1398 # 3.10: ForwardRefs of UnionType might be turned into _UnionGenericAlias
1399 hasattr(_types, "UnionType")
1400 and isinstance(original_evaluated, _types.UnionType)
1401 and not isinstance(value, _types.UnionType)
1402 ):
1403 hints[name] = original_evaluated
1404
1405# Python 3.9+ has PEP 593 (Annotated)
1406if hasattr(typing, 'Annotated'):
1407 Annotated = typing.Annotated
1408 # Not exported and not a public API, but needed for get_origin() and get_args()
1409 # to work.
1410 _AnnotatedAlias = typing._AnnotatedAlias
1411# 3.8
1412else:
1413 class _AnnotatedAlias(typing._GenericAlias, _root=True):
1414 """Runtime representation of an annotated type.
1415
1416 At its core 'Annotated[t, dec1, dec2, ...]' is an alias for the type 't'
1417 with extra annotations. The alias behaves like a normal typing alias,
1418 instantiating is the same as instantiating the underlying type, binding
1419 it to types is also the same.
1420 """
1421 def __init__(self, origin, metadata):
1422 if isinstance(origin, _AnnotatedAlias):
1423 metadata = origin.__metadata__ + metadata
1424 origin = origin.__origin__
1425 super().__init__(origin, origin)
1426 self.__metadata__ = metadata
1427
1428 def copy_with(self, params):
1429 assert len(params) == 1
1430 new_type = params[0]
1431 return _AnnotatedAlias(new_type, self.__metadata__)
1432
1433 def __repr__(self):
1434 return (f"typing_extensions.Annotated[{typing._type_repr(self.__origin__)}, "
1435 f"{', '.join(repr(a) for a in self.__metadata__)}]")
1436
1437 def __reduce__(self):
1438 return operator.getitem, (
1439 Annotated, (self.__origin__, *self.__metadata__)
1440 )
1441
1442 def __eq__(self, other):
1443 if not isinstance(other, _AnnotatedAlias):
1444 return NotImplemented
1445 if self.__origin__ != other.__origin__:
1446 return False
1447 return self.__metadata__ == other.__metadata__
1448
1449 def __hash__(self):
1450 return hash((self.__origin__, self.__metadata__))
1451
1452 class Annotated:
1453 """Add context specific metadata to a type.
1454
1455 Example: Annotated[int, runtime_check.Unsigned] indicates to the
1456 hypothetical runtime_check module that this type is an unsigned int.
1457 Every other consumer of this type can ignore this metadata and treat
1458 this type as int.
1459
1460 The first argument to Annotated must be a valid type (and will be in
1461 the __origin__ field), the remaining arguments are kept as a tuple in
1462 the __extra__ field.
1463
1464 Details:
1465
1466 - It's an error to call `Annotated` with less than two arguments.
1467 - Nested Annotated are flattened::
1468
1469 Annotated[Annotated[T, Ann1, Ann2], Ann3] == Annotated[T, Ann1, Ann2, Ann3]
1470
1471 - Instantiating an annotated type is equivalent to instantiating the
1472 underlying type::
1473
1474 Annotated[C, Ann1](5) == C(5)
1475
1476 - Annotated can be used as a generic type alias::
1477
1478 Optimized = Annotated[T, runtime.Optimize()]
1479 Optimized[int] == Annotated[int, runtime.Optimize()]
1480
1481 OptimizedList = Annotated[List[T], runtime.Optimize()]
1482 OptimizedList[int] == Annotated[List[int], runtime.Optimize()]
1483 """
1484
1485 __slots__ = ()
1486
1487 def __new__(cls, *args, **kwargs):
1488 raise TypeError("Type Annotated cannot be instantiated.")
1489
1490 @typing._tp_cache
1491 def __class_getitem__(cls, params):
1492 if not isinstance(params, tuple) or len(params) < 2:
1493 raise TypeError("Annotated[...] should be used "
1494 "with at least two arguments (a type and an "
1495 "annotation).")
1496 allowed_special_forms = (ClassVar, Final)
1497 if get_origin(params[0]) in allowed_special_forms:
1498 origin = params[0]
1499 else:
1500 msg = "Annotated[t, ...]: t must be a type."
1501 origin = typing._type_check(params[0], msg)
1502 metadata = tuple(params[1:])
1503 return _AnnotatedAlias(origin, metadata)
1504
1505 def __init_subclass__(cls, *args, **kwargs):
1506 raise TypeError(
1507 f"Cannot subclass {cls.__module__}.Annotated"
1508 )
1509
1510# Python 3.8 has get_origin() and get_args() but those implementations aren't
1511# Annotated-aware, so we can't use those. Python 3.9's versions don't support
1512# ParamSpecArgs and ParamSpecKwargs, so only Python 3.10's versions will do.
1513if sys.version_info[:2] >= (3, 10):
1514 get_origin = typing.get_origin
1515 get_args = typing.get_args
1516# 3.8-3.9
1517else:
1518 try:
1519 # 3.9+
1520 from typing import _BaseGenericAlias
1521 except ImportError:
1522 _BaseGenericAlias = typing._GenericAlias
1523 try:
1524 # 3.9+
1525 from typing import GenericAlias as _typing_GenericAlias
1526 except ImportError:
1527 _typing_GenericAlias = typing._GenericAlias
1528
1529 def get_origin(tp):
1530 """Get the unsubscripted version of a type.
1531
1532 This supports generic types, Callable, Tuple, Union, Literal, Final, ClassVar
1533 and Annotated. Return None for unsupported types. Examples::
1534
1535 get_origin(Literal[42]) is Literal
1536 get_origin(int) is None
1537 get_origin(ClassVar[int]) is ClassVar
1538 get_origin(Generic) is Generic
1539 get_origin(Generic[T]) is Generic
1540 get_origin(Union[T, int]) is Union
1541 get_origin(List[Tuple[T, T]][int]) == list
1542 get_origin(P.args) is P
1543 """
1544 if isinstance(tp, _AnnotatedAlias):
1545 return Annotated
1546 if isinstance(tp, (typing._GenericAlias, _typing_GenericAlias, _BaseGenericAlias,
1547 ParamSpecArgs, ParamSpecKwargs)):
1548 return tp.__origin__
1549 if tp is typing.Generic:
1550 return typing.Generic
1551 return None
1552
1553 def get_args(tp):
1554 """Get type arguments with all substitutions performed.
1555
1556 For unions, basic simplifications used by Union constructor are performed.
1557 Examples::
1558 get_args(Dict[str, int]) == (str, int)
1559 get_args(int) == ()
1560 get_args(Union[int, Union[T, int], str][int]) == (int, str)
1561 get_args(Union[int, Tuple[T, int]][str]) == (int, Tuple[str, int])
1562 get_args(Callable[[], T][int]) == ([], int)
1563 """
1564 if isinstance(tp, _AnnotatedAlias):
1565 return (tp.__origin__, *tp.__metadata__)
1566 if isinstance(tp, (typing._GenericAlias, _typing_GenericAlias)):
1567 if getattr(tp, "_special", False):
1568 return ()
1569 res = tp.__args__
1570 if get_origin(tp) is collections.abc.Callable and res[0] is not Ellipsis:
1571 res = (list(res[:-1]), res[-1])
1572 return res
1573 return ()
1574
1575
1576# 3.10+
1577if hasattr(typing, 'TypeAlias'):
1578 TypeAlias = typing.TypeAlias
1579# 3.9
1580elif sys.version_info[:2] >= (3, 9):
1581 @_ExtensionsSpecialForm
1582 def TypeAlias(self, parameters):
1583 """Special marker indicating that an assignment should
1584 be recognized as a proper type alias definition by type
1585 checkers.
1586
1587 For example::
1588
1589 Predicate: TypeAlias = Callable[..., bool]
1590
1591 It's invalid when used anywhere except as in the example above.
1592 """
1593 raise TypeError(f"{self} is not subscriptable")
1594# 3.8
1595else:
1596 TypeAlias = _ExtensionsSpecialForm(
1597 'TypeAlias',
1598 doc="""Special marker indicating that an assignment should
1599 be recognized as a proper type alias definition by type
1600 checkers.
1601
1602 For example::
1603
1604 Predicate: TypeAlias = Callable[..., bool]
1605
1606 It's invalid when used anywhere except as in the example
1607 above."""
1608 )
1609
1610
1611def _set_default(type_param, default):
1612 type_param.has_default = lambda: default is not NoDefault
1613 type_param.__default__ = default
1614
1615
1616def _set_module(typevarlike):
1617 # for pickling:
1618 def_mod = _caller(depth=3)
1619 if def_mod != 'typing_extensions':
1620 typevarlike.__module__ = def_mod
1621
1622
1623class _DefaultMixin:
1624 """Mixin for TypeVarLike defaults."""
1625
1626 __slots__ = ()
1627 __init__ = _set_default
1628
1629
1630# Classes using this metaclass must provide a _backported_typevarlike ClassVar
1631class _TypeVarLikeMeta(type):
1632 def __instancecheck__(cls, __instance: Any) -> bool:
1633 return isinstance(__instance, cls._backported_typevarlike)
1634
1635
1636if _PEP_696_IMPLEMENTED:
1637 from typing import TypeVar
1638else:
1639 # Add default and infer_variance parameters from PEP 696 and 695
1640 class TypeVar(metaclass=_TypeVarLikeMeta):
1641 """Type variable."""
1642
1643 _backported_typevarlike = typing.TypeVar
1644
1645 def __new__(cls, name, *constraints, bound=None,
1646 covariant=False, contravariant=False,
1647 default=NoDefault, infer_variance=False):
1648 if hasattr(typing, "TypeAliasType"):
1649 # PEP 695 implemented (3.12+), can pass infer_variance to typing.TypeVar
1650 typevar = typing.TypeVar(name, *constraints, bound=bound,
1651 covariant=covariant, contravariant=contravariant,
1652 infer_variance=infer_variance)
1653 else:
1654 typevar = typing.TypeVar(name, *constraints, bound=bound,
1655 covariant=covariant, contravariant=contravariant)
1656 if infer_variance and (covariant or contravariant):
1657 raise ValueError("Variance cannot be specified with infer_variance.")
1658 typevar.__infer_variance__ = infer_variance
1659
1660 _set_default(typevar, default)
1661 _set_module(typevar)
1662
1663 def _tvar_prepare_subst(alias, args):
1664 if (
1665 typevar.has_default()
1666 and alias.__parameters__.index(typevar) == len(args)
1667 ):
1668 args += (typevar.__default__,)
1669 return args
1670
1671 typevar.__typing_prepare_subst__ = _tvar_prepare_subst
1672 return typevar
1673
1674 def __init_subclass__(cls) -> None:
1675 raise TypeError(f"type '{__name__}.TypeVar' is not an acceptable base type")
1676
1677
1678# Python 3.10+ has PEP 612
1679if hasattr(typing, 'ParamSpecArgs'):
1680 ParamSpecArgs = typing.ParamSpecArgs
1681 ParamSpecKwargs = typing.ParamSpecKwargs
1682# 3.8-3.9
1683else:
1684 class _Immutable:
1685 """Mixin to indicate that object should not be copied."""
1686 __slots__ = ()
1687
1688 def __copy__(self):
1689 return self
1690
1691 def __deepcopy__(self, memo):
1692 return self
1693
1694 class ParamSpecArgs(_Immutable):
1695 """The args for a ParamSpec object.
1696
1697 Given a ParamSpec object P, P.args is an instance of ParamSpecArgs.
1698
1699 ParamSpecArgs objects have a reference back to their ParamSpec:
1700
1701 P.args.__origin__ is P
1702
1703 This type is meant for runtime introspection and has no special meaning to
1704 static type checkers.
1705 """
1706 def __init__(self, origin):
1707 self.__origin__ = origin
1708
1709 def __repr__(self):
1710 return f"{self.__origin__.__name__}.args"
1711
1712 def __eq__(self, other):
1713 if not isinstance(other, ParamSpecArgs):
1714 return NotImplemented
1715 return self.__origin__ == other.__origin__
1716
1717 class ParamSpecKwargs(_Immutable):
1718 """The kwargs for a ParamSpec object.
1719
1720 Given a ParamSpec object P, P.kwargs is an instance of ParamSpecKwargs.
1721
1722 ParamSpecKwargs objects have a reference back to their ParamSpec:
1723
1724 P.kwargs.__origin__ is P
1725
1726 This type is meant for runtime introspection and has no special meaning to
1727 static type checkers.
1728 """
1729 def __init__(self, origin):
1730 self.__origin__ = origin
1731
1732 def __repr__(self):
1733 return f"{self.__origin__.__name__}.kwargs"
1734
1735 def __eq__(self, other):
1736 if not isinstance(other, ParamSpecKwargs):
1737 return NotImplemented
1738 return self.__origin__ == other.__origin__
1739
1740
1741if _PEP_696_IMPLEMENTED:
1742 from typing import ParamSpec
1743
1744# 3.10+
1745elif hasattr(typing, 'ParamSpec'):
1746
1747 # Add default parameter - PEP 696
1748 class ParamSpec(metaclass=_TypeVarLikeMeta):
1749 """Parameter specification."""
1750
1751 _backported_typevarlike = typing.ParamSpec
1752
1753 def __new__(cls, name, *, bound=None,
1754 covariant=False, contravariant=False,
1755 infer_variance=False, default=NoDefault):
1756 if hasattr(typing, "TypeAliasType"):
1757 # PEP 695 implemented, can pass infer_variance to typing.TypeVar
1758 paramspec = typing.ParamSpec(name, bound=bound,
1759 covariant=covariant,
1760 contravariant=contravariant,
1761 infer_variance=infer_variance)
1762 else:
1763 paramspec = typing.ParamSpec(name, bound=bound,
1764 covariant=covariant,
1765 contravariant=contravariant)
1766 paramspec.__infer_variance__ = infer_variance
1767
1768 _set_default(paramspec, default)
1769 _set_module(paramspec)
1770
1771 def _paramspec_prepare_subst(alias, args):
1772 params = alias.__parameters__
1773 i = params.index(paramspec)
1774 if i == len(args) and paramspec.has_default():
1775 args = [*args, paramspec.__default__]
1776 if i >= len(args):
1777 raise TypeError(f"Too few arguments for {alias}")
1778 # Special case where Z[[int, str, bool]] == Z[int, str, bool] in PEP 612.
1779 if len(params) == 1 and not typing._is_param_expr(args[0]):
1780 assert i == 0
1781 args = (args,)
1782 # Convert lists to tuples to help other libraries cache the results.
1783 elif isinstance(args[i], list):
1784 args = (*args[:i], tuple(args[i]), *args[i + 1:])
1785 return args
1786
1787 paramspec.__typing_prepare_subst__ = _paramspec_prepare_subst
1788 return paramspec
1789
1790 def __init_subclass__(cls) -> None:
1791 raise TypeError(f"type '{__name__}.ParamSpec' is not an acceptable base type")
1792
1793# 3.8-3.9
1794else:
1795
1796 # Inherits from list as a workaround for Callable checks in Python < 3.9.2.
1797 class ParamSpec(list, _DefaultMixin):
1798 """Parameter specification variable.
1799
1800 Usage::
1801
1802 P = ParamSpec('P')
1803
1804 Parameter specification variables exist primarily for the benefit of static
1805 type checkers. They are used to forward the parameter types of one
1806 callable to another callable, a pattern commonly found in higher order
1807 functions and decorators. They are only valid when used in ``Concatenate``,
1808 or s the first argument to ``Callable``. In Python 3.10 and higher,
1809 they are also supported in user-defined Generics at runtime.
1810 See class Generic for more information on generic types. An
1811 example for annotating a decorator::
1812
1813 T = TypeVar('T')
1814 P = ParamSpec('P')
1815
1816 def add_logging(f: Callable[P, T]) -> Callable[P, T]:
1817 '''A type-safe decorator to add logging to a function.'''
1818 def inner(*args: P.args, **kwargs: P.kwargs) -> T:
1819 logging.info(f'{f.__name__} was called')
1820 return f(*args, **kwargs)
1821 return inner
1822
1823 @add_logging
1824 def add_two(x: float, y: float) -> float:
1825 '''Add two numbers together.'''
1826 return x + y
1827
1828 Parameter specification variables defined with covariant=True or
1829 contravariant=True can be used to declare covariant or contravariant
1830 generic types. These keyword arguments are valid, but their actual semantics
1831 are yet to be decided. See PEP 612 for details.
1832
1833 Parameter specification variables can be introspected. e.g.:
1834
1835 P.__name__ == 'T'
1836 P.__bound__ == None
1837 P.__covariant__ == False
1838 P.__contravariant__ == False
1839
1840 Note that only parameter specification variables defined in global scope can
1841 be pickled.
1842 """
1843
1844 # Trick Generic __parameters__.
1845 __class__ = typing.TypeVar
1846
1847 @property
1848 def args(self):
1849 return ParamSpecArgs(self)
1850
1851 @property
1852 def kwargs(self):
1853 return ParamSpecKwargs(self)
1854
1855 def __init__(self, name, *, bound=None, covariant=False, contravariant=False,
1856 infer_variance=False, default=NoDefault):
1857 list.__init__(self, [self])
1858 self.__name__ = name
1859 self.__covariant__ = bool(covariant)
1860 self.__contravariant__ = bool(contravariant)
1861 self.__infer_variance__ = bool(infer_variance)
1862 if bound:
1863 self.__bound__ = typing._type_check(bound, 'Bound must be a type.')
1864 else:
1865 self.__bound__ = None
1866 _DefaultMixin.__init__(self, default)
1867
1868 # for pickling:
1869 def_mod = _caller()
1870 if def_mod != 'typing_extensions':
1871 self.__module__ = def_mod
1872
1873 def __repr__(self):
1874 if self.__infer_variance__:
1875 prefix = ''
1876 elif self.__covariant__:
1877 prefix = '+'
1878 elif self.__contravariant__:
1879 prefix = '-'
1880 else:
1881 prefix = '~'
1882 return prefix + self.__name__
1883
1884 def __hash__(self):
1885 return object.__hash__(self)
1886
1887 def __eq__(self, other):
1888 return self is other
1889
1890 def __reduce__(self):
1891 return self.__name__
1892
1893 # Hack to get typing._type_check to pass.
1894 def __call__(self, *args, **kwargs):
1895 pass
1896
1897
1898# 3.8-3.9
1899if not hasattr(typing, 'Concatenate'):
1900 # Inherits from list as a workaround for Callable checks in Python < 3.9.2.
1901
1902 # 3.9.0-1
1903 if not hasattr(typing, '_type_convert'):
1904 def _type_convert(arg, module=None, *, allow_special_forms=False):
1905 """For converting None to type(None), and strings to ForwardRef."""
1906 if arg is None:
1907 return type(None)
1908 if isinstance(arg, str):
1909 if sys.version_info <= (3, 9, 6):
1910 return ForwardRef(arg)
1911 if sys.version_info <= (3, 9, 7):
1912 return ForwardRef(arg, module=module)
1913 return ForwardRef(arg, module=module, is_class=allow_special_forms)
1914 return arg
1915 else:
1916 _type_convert = typing._type_convert
1917
1918 class _ConcatenateGenericAlias(list):
1919
1920 # Trick Generic into looking into this for __parameters__.
1921 __class__ = typing._GenericAlias
1922
1923 # Flag in 3.8.
1924 _special = False
1925
1926 def __init__(self, origin, args):
1927 super().__init__(args)
1928 self.__origin__ = origin
1929 self.__args__ = args
1930
1931 def __repr__(self):
1932 _type_repr = typing._type_repr
1933 return (f'{_type_repr(self.__origin__)}'
1934 f'[{", ".join(_type_repr(arg) for arg in self.__args__)}]')
1935
1936 def __hash__(self):
1937 return hash((self.__origin__, self.__args__))
1938
1939 # Hack to get typing._type_check to pass in Generic.
1940 def __call__(self, *args, **kwargs):
1941 pass
1942
1943 @property
1944 def __parameters__(self):
1945 return tuple(
1946 tp for tp in self.__args__ if isinstance(tp, (typing.TypeVar, ParamSpec))
1947 )
1948
1949 # 3.8; needed for typing._subst_tvars
1950 # 3.9 used by __getitem__ below
1951 def copy_with(self, params):
1952 if isinstance(params[-1], _ConcatenateGenericAlias):
1953 params = (*params[:-1], *params[-1].__args__)
1954 elif isinstance(params[-1], (list, tuple)):
1955 return (*params[:-1], *params[-1])
1956 elif (not (params[-1] is ... or isinstance(params[-1], ParamSpec))):
1957 raise TypeError("The last parameter to Concatenate should be a "
1958 "ParamSpec variable or ellipsis.")
1959 return self.__class__(self.__origin__, params)
1960
1961 # 3.9; accessed during GenericAlias.__getitem__ when substituting
1962 def __getitem__(self, args):
1963 if self.__origin__ in (Generic, Protocol):
1964 # Can't subscript Generic[...] or Protocol[...].
1965 raise TypeError(f"Cannot subscript already-subscripted {self}")
1966 if not self.__parameters__:
1967 raise TypeError(f"{self} is not a generic class")
1968
1969 if not isinstance(args, tuple):
1970 args = (args,)
1971 args = _unpack_args(*(_type_convert(p) for p in args))
1972 params = self.__parameters__
1973 for param in params:
1974 prepare = getattr(param, "__typing_prepare_subst__", None)
1975 if prepare is not None:
1976 args = prepare(self, args)
1977 # 3.8 - 3.9 & typing.ParamSpec
1978 elif isinstance(param, ParamSpec):
1979 i = params.index(param)
1980 if (
1981 i == len(args)
1982 and getattr(param, '__default__', NoDefault) is not NoDefault
1983 ):
1984 args = [*args, param.__default__]
1985 if i >= len(args):
1986 raise TypeError(f"Too few arguments for {self}")
1987 # Special case for Z[[int, str, bool]] == Z[int, str, bool]
1988 if len(params) == 1 and not _is_param_expr(args[0]):
1989 assert i == 0
1990 args = (args,)
1991 elif (
1992 isinstance(args[i], list)
1993 # 3.8 - 3.9
1994 # This class inherits from list do not convert
1995 and not isinstance(args[i], _ConcatenateGenericAlias)
1996 ):
1997 args = (*args[:i], tuple(args[i]), *args[i + 1:])
1998
1999 alen = len(args)
2000 plen = len(params)
2001 if alen != plen:
2002 raise TypeError(
2003 f"Too {'many' if alen > plen else 'few'} arguments for {self};"
2004 f" actual {alen}, expected {plen}"
2005 )
2006
2007 subst = dict(zip(self.__parameters__, args))
2008 # determine new args
2009 new_args = []
2010 for arg in self.__args__:
2011 if isinstance(arg, type):
2012 new_args.append(arg)
2013 continue
2014 if isinstance(arg, TypeVar):
2015 arg = subst[arg]
2016 if (
2017 (isinstance(arg, typing._GenericAlias) and _is_unpack(arg))
2018 or (
2019 hasattr(_types, "GenericAlias")
2020 and isinstance(arg, _types.GenericAlias)
2021 and getattr(arg, "__unpacked__", False)
2022 )
2023 ):
2024 raise TypeError(f"{arg} is not valid as type argument")
2025
2026 elif isinstance(arg,
2027 typing._GenericAlias
2028 if not hasattr(_types, "GenericAlias") else
2029 (typing._GenericAlias, _types.GenericAlias)
2030 ):
2031 subparams = arg.__parameters__
2032 if subparams:
2033 subargs = tuple(subst[x] for x in subparams)
2034 arg = arg[subargs]
2035 new_args.append(arg)
2036 return self.copy_with(tuple(new_args))
2037
2038# 3.10+
2039else:
2040 _ConcatenateGenericAlias = typing._ConcatenateGenericAlias
2041
2042 # 3.10
2043 if sys.version_info < (3, 11):
2044
2045 class _ConcatenateGenericAlias(typing._ConcatenateGenericAlias, _root=True):
2046 # needed for checks in collections.abc.Callable to accept this class
2047 __module__ = "typing"
2048
2049 def copy_with(self, params):
2050 if isinstance(params[-1], (list, tuple)):
2051 return (*params[:-1], *params[-1])
2052 if isinstance(params[-1], typing._ConcatenateGenericAlias):
2053 params = (*params[:-1], *params[-1].__args__)
2054 elif not (params[-1] is ... or isinstance(params[-1], ParamSpec)):
2055 raise TypeError("The last parameter to Concatenate should be a "
2056 "ParamSpec variable or ellipsis.")
2057 return super(typing._ConcatenateGenericAlias, self).copy_with(params)
2058
2059 def __getitem__(self, args):
2060 value = super().__getitem__(args)
2061 if isinstance(value, tuple) and any(_is_unpack(t) for t in value):
2062 return tuple(_unpack_args(*(n for n in value)))
2063 return value
2064
2065
2066# 3.8-3.9.2
2067class _EllipsisDummy: ...
2068
2069
2070# 3.8-3.10
2071def _create_concatenate_alias(origin, parameters):
2072 if parameters[-1] is ... and sys.version_info < (3, 9, 2):
2073 # Hack: Arguments must be types, replace it with one.
2074 parameters = (*parameters[:-1], _EllipsisDummy)
2075 if sys.version_info >= (3, 10, 3):
2076 concatenate = _ConcatenateGenericAlias(origin, parameters,
2077 _typevar_types=(TypeVar, ParamSpec),
2078 _paramspec_tvars=True)
2079 else:
2080 concatenate = _ConcatenateGenericAlias(origin, parameters)
2081 if parameters[-1] is not _EllipsisDummy:
2082 return concatenate
2083 # Remove dummy again
2084 concatenate.__args__ = tuple(p if p is not _EllipsisDummy else ...
2085 for p in concatenate.__args__)
2086 if sys.version_info < (3, 10):
2087 # backport needs __args__ adjustment only
2088 return concatenate
2089 concatenate.__parameters__ = tuple(p for p in concatenate.__parameters__
2090 if p is not _EllipsisDummy)
2091 return concatenate
2092
2093
2094# 3.8-3.10
2095@typing._tp_cache
2096def _concatenate_getitem(self, parameters):
2097 if parameters == ():
2098 raise TypeError("Cannot take a Concatenate of no types.")
2099 if not isinstance(parameters, tuple):
2100 parameters = (parameters,)
2101 if not (parameters[-1] is ... or isinstance(parameters[-1], ParamSpec)):
2102 raise TypeError("The last parameter to Concatenate should be a "
2103 "ParamSpec variable or ellipsis.")
2104 msg = "Concatenate[arg, ...]: each arg must be a type."
2105 parameters = (*(typing._type_check(p, msg) for p in parameters[:-1]),
2106 parameters[-1])
2107 return _create_concatenate_alias(self, parameters)
2108
2109
2110# 3.11+; Concatenate does not accept ellipsis in 3.10
2111if sys.version_info >= (3, 11):
2112 Concatenate = typing.Concatenate
2113# 3.9-3.10
2114elif sys.version_info[:2] >= (3, 9):
2115 @_ExtensionsSpecialForm
2116 def Concatenate(self, parameters):
2117 """Used in conjunction with ``ParamSpec`` and ``Callable`` to represent a
2118 higher order function which adds, removes or transforms parameters of a
2119 callable.
2120
2121 For example::
2122
2123 Callable[Concatenate[int, P], int]
2124
2125 See PEP 612 for detailed information.
2126 """
2127 return _concatenate_getitem(self, parameters)
2128# 3.8
2129else:
2130 class _ConcatenateForm(_ExtensionsSpecialForm, _root=True):
2131 def __getitem__(self, parameters):
2132 return _concatenate_getitem(self, parameters)
2133
2134 Concatenate = _ConcatenateForm(
2135 'Concatenate',
2136 doc="""Used in conjunction with ``ParamSpec`` and ``Callable`` to represent a
2137 higher order function which adds, removes or transforms parameters of a
2138 callable.
2139
2140 For example::
2141
2142 Callable[Concatenate[int, P], int]
2143
2144 See PEP 612 for detailed information.
2145 """)
2146
2147# 3.10+
2148if hasattr(typing, 'TypeGuard'):
2149 TypeGuard = typing.TypeGuard
2150# 3.9
2151elif sys.version_info[:2] >= (3, 9):
2152 @_ExtensionsSpecialForm
2153 def TypeGuard(self, parameters):
2154 """Special typing form used to annotate the return type of a user-defined
2155 type guard function. ``TypeGuard`` only accepts a single type argument.
2156 At runtime, functions marked this way should return a boolean.
2157
2158 ``TypeGuard`` aims to benefit *type narrowing* -- a technique used by static
2159 type checkers to determine a more precise type of an expression within a
2160 program's code flow. Usually type narrowing is done by analyzing
2161 conditional code flow and applying the narrowing to a block of code. The
2162 conditional expression here is sometimes referred to as a "type guard".
2163
2164 Sometimes it would be convenient to use a user-defined boolean function
2165 as a type guard. Such a function should use ``TypeGuard[...]`` as its
2166 return type to alert static type checkers to this intention.
2167
2168 Using ``-> TypeGuard`` tells the static type checker that for a given
2169 function:
2170
2171 1. The return value is a boolean.
2172 2. If the return value is ``True``, the type of its argument
2173 is the type inside ``TypeGuard``.
2174
2175 For example::
2176
2177 def is_str(val: Union[str, float]):
2178 # "isinstance" type guard
2179 if isinstance(val, str):
2180 # Type of ``val`` is narrowed to ``str``
2181 ...
2182 else:
2183 # Else, type of ``val`` is narrowed to ``float``.
2184 ...
2185
2186 Strict type narrowing is not enforced -- ``TypeB`` need not be a narrower
2187 form of ``TypeA`` (it can even be a wider form) and this may lead to
2188 type-unsafe results. The main reason is to allow for things like
2189 narrowing ``List[object]`` to ``List[str]`` even though the latter is not
2190 a subtype of the former, since ``List`` is invariant. The responsibility of
2191 writing type-safe type guards is left to the user.
2192
2193 ``TypeGuard`` also works with type variables. For more information, see
2194 PEP 647 (User-Defined Type Guards).
2195 """
2196 item = typing._type_check(parameters, f'{self} accepts only a single type.')
2197 return typing._GenericAlias(self, (item,))
2198# 3.8
2199else:
2200 class _TypeGuardForm(_ExtensionsSpecialForm, _root=True):
2201 def __getitem__(self, parameters):
2202 item = typing._type_check(parameters,
2203 f'{self._name} accepts only a single type')
2204 return typing._GenericAlias(self, (item,))
2205
2206 TypeGuard = _TypeGuardForm(
2207 'TypeGuard',
2208 doc="""Special typing form used to annotate the return type of a user-defined
2209 type guard function. ``TypeGuard`` only accepts a single type argument.
2210 At runtime, functions marked this way should return a boolean.
2211
2212 ``TypeGuard`` aims to benefit *type narrowing* -- a technique used by static
2213 type checkers to determine a more precise type of an expression within a
2214 program's code flow. Usually type narrowing is done by analyzing
2215 conditional code flow and applying the narrowing to a block of code. The
2216 conditional expression here is sometimes referred to as a "type guard".
2217
2218 Sometimes it would be convenient to use a user-defined boolean function
2219 as a type guard. Such a function should use ``TypeGuard[...]`` as its
2220 return type to alert static type checkers to this intention.
2221
2222 Using ``-> TypeGuard`` tells the static type checker that for a given
2223 function:
2224
2225 1. The return value is a boolean.
2226 2. If the return value is ``True``, the type of its argument
2227 is the type inside ``TypeGuard``.
2228
2229 For example::
2230
2231 def is_str(val: Union[str, float]):
2232 # "isinstance" type guard
2233 if isinstance(val, str):
2234 # Type of ``val`` is narrowed to ``str``
2235 ...
2236 else:
2237 # Else, type of ``val`` is narrowed to ``float``.
2238 ...
2239
2240 Strict type narrowing is not enforced -- ``TypeB`` need not be a narrower
2241 form of ``TypeA`` (it can even be a wider form) and this may lead to
2242 type-unsafe results. The main reason is to allow for things like
2243 narrowing ``List[object]`` to ``List[str]`` even though the latter is not
2244 a subtype of the former, since ``List`` is invariant. The responsibility of
2245 writing type-safe type guards is left to the user.
2246
2247 ``TypeGuard`` also works with type variables. For more information, see
2248 PEP 647 (User-Defined Type Guards).
2249 """)
2250
2251# 3.13+
2252if hasattr(typing, 'TypeIs'):
2253 TypeIs = typing.TypeIs
2254# 3.9
2255elif sys.version_info[:2] >= (3, 9):
2256 @_ExtensionsSpecialForm
2257 def TypeIs(self, parameters):
2258 """Special typing form used to annotate the return type of a user-defined
2259 type narrower function. ``TypeIs`` only accepts a single type argument.
2260 At runtime, functions marked this way should return a boolean.
2261
2262 ``TypeIs`` aims to benefit *type narrowing* -- a technique used by static
2263 type checkers to determine a more precise type of an expression within a
2264 program's code flow. Usually type narrowing is done by analyzing
2265 conditional code flow and applying the narrowing to a block of code. The
2266 conditional expression here is sometimes referred to as a "type guard".
2267
2268 Sometimes it would be convenient to use a user-defined boolean function
2269 as a type guard. Such a function should use ``TypeIs[...]`` as its
2270 return type to alert static type checkers to this intention.
2271
2272 Using ``-> TypeIs`` tells the static type checker that for a given
2273 function:
2274
2275 1. The return value is a boolean.
2276 2. If the return value is ``True``, the type of its argument
2277 is the intersection of the type inside ``TypeIs`` and the argument's
2278 previously known type.
2279
2280 For example::
2281
2282 def is_awaitable(val: object) -> TypeIs[Awaitable[Any]]:
2283 return hasattr(val, '__await__')
2284
2285 def f(val: Union[int, Awaitable[int]]) -> int:
2286 if is_awaitable(val):
2287 assert_type(val, Awaitable[int])
2288 else:
2289 assert_type(val, int)
2290
2291 ``TypeIs`` also works with type variables. For more information, see
2292 PEP 742 (Narrowing types with TypeIs).
2293 """
2294 item = typing._type_check(parameters, f'{self} accepts only a single type.')
2295 return typing._GenericAlias(self, (item,))
2296# 3.8
2297else:
2298 class _TypeIsForm(_ExtensionsSpecialForm, _root=True):
2299 def __getitem__(self, parameters):
2300 item = typing._type_check(parameters,
2301 f'{self._name} accepts only a single type')
2302 return typing._GenericAlias(self, (item,))
2303
2304 TypeIs = _TypeIsForm(
2305 'TypeIs',
2306 doc="""Special typing form used to annotate the return type of a user-defined
2307 type narrower function. ``TypeIs`` only accepts a single type argument.
2308 At runtime, functions marked this way should return a boolean.
2309
2310 ``TypeIs`` aims to benefit *type narrowing* -- a technique used by static
2311 type checkers to determine a more precise type of an expression within a
2312 program's code flow. Usually type narrowing is done by analyzing
2313 conditional code flow and applying the narrowing to a block of code. The
2314 conditional expression here is sometimes referred to as a "type guard".
2315
2316 Sometimes it would be convenient to use a user-defined boolean function
2317 as a type guard. Such a function should use ``TypeIs[...]`` as its
2318 return type to alert static type checkers to this intention.
2319
2320 Using ``-> TypeIs`` tells the static type checker that for a given
2321 function:
2322
2323 1. The return value is a boolean.
2324 2. If the return value is ``True``, the type of its argument
2325 is the intersection of the type inside ``TypeIs`` and the argument's
2326 previously known type.
2327
2328 For example::
2329
2330 def is_awaitable(val: object) -> TypeIs[Awaitable[Any]]:
2331 return hasattr(val, '__await__')
2332
2333 def f(val: Union[int, Awaitable[int]]) -> int:
2334 if is_awaitable(val):
2335 assert_type(val, Awaitable[int])
2336 else:
2337 assert_type(val, int)
2338
2339 ``TypeIs`` also works with type variables. For more information, see
2340 PEP 742 (Narrowing types with TypeIs).
2341 """)
2342
2343# 3.14+?
2344if hasattr(typing, 'TypeForm'):
2345 TypeForm = typing.TypeForm
2346# 3.9
2347elif sys.version_info[:2] >= (3, 9):
2348 class _TypeFormForm(_ExtensionsSpecialForm, _root=True):
2349 # TypeForm(X) is equivalent to X but indicates to the type checker
2350 # that the object is a TypeForm.
2351 def __call__(self, obj, /):
2352 return obj
2353
2354 @_TypeFormForm
2355 def TypeForm(self, parameters):
2356 """A special form representing the value that results from the evaluation
2357 of a type expression. This value encodes the information supplied in the
2358 type expression, and it represents the type described by that type expression.
2359
2360 When used in a type expression, TypeForm describes a set of type form objects.
2361 It accepts a single type argument, which must be a valid type expression.
2362 ``TypeForm[T]`` describes the set of all type form objects that represent
2363 the type T or types that are assignable to T.
2364
2365 Usage:
2366
2367 def cast[T](typ: TypeForm[T], value: Any) -> T: ...
2368
2369 reveal_type(cast(int, "x")) # int
2370
2371 See PEP 747 for more information.
2372 """
2373 item = typing._type_check(parameters, f'{self} accepts only a single type.')
2374 return typing._GenericAlias(self, (item,))
2375# 3.8
2376else:
2377 class _TypeFormForm(_ExtensionsSpecialForm, _root=True):
2378 def __getitem__(self, parameters):
2379 item = typing._type_check(parameters,
2380 f'{self._name} accepts only a single type')
2381 return typing._GenericAlias(self, (item,))
2382
2383 def __call__(self, obj, /):
2384 return obj
2385
2386 TypeForm = _TypeFormForm(
2387 'TypeForm',
2388 doc="""A special form representing the value that results from the evaluation
2389 of a type expression. This value encodes the information supplied in the
2390 type expression, and it represents the type described by that type expression.
2391
2392 When used in a type expression, TypeForm describes a set of type form objects.
2393 It accepts a single type argument, which must be a valid type expression.
2394 ``TypeForm[T]`` describes the set of all type form objects that represent
2395 the type T or types that are assignable to T.
2396
2397 Usage:
2398
2399 def cast[T](typ: TypeForm[T], value: Any) -> T: ...
2400
2401 reveal_type(cast(int, "x")) # int
2402
2403 See PEP 747 for more information.
2404 """)
2405
2406
2407# Vendored from cpython typing._SpecialFrom
2408class _SpecialForm(typing._Final, _root=True):
2409 __slots__ = ('_name', '__doc__', '_getitem')
2410
2411 def __init__(self, getitem):
2412 self._getitem = getitem
2413 self._name = getitem.__name__
2414 self.__doc__ = getitem.__doc__
2415
2416 def __getattr__(self, item):
2417 if item in {'__name__', '__qualname__'}:
2418 return self._name
2419
2420 raise AttributeError(item)
2421
2422 def __mro_entries__(self, bases):
2423 raise TypeError(f"Cannot subclass {self!r}")
2424
2425 def __repr__(self):
2426 return f'typing_extensions.{self._name}'
2427
2428 def __reduce__(self):
2429 return self._name
2430
2431 def __call__(self, *args, **kwds):
2432 raise TypeError(f"Cannot instantiate {self!r}")
2433
2434 def __or__(self, other):
2435 return typing.Union[self, other]
2436
2437 def __ror__(self, other):
2438 return typing.Union[other, self]
2439
2440 def __instancecheck__(self, obj):
2441 raise TypeError(f"{self} cannot be used with isinstance()")
2442
2443 def __subclasscheck__(self, cls):
2444 raise TypeError(f"{self} cannot be used with issubclass()")
2445
2446 @typing._tp_cache
2447 def __getitem__(self, parameters):
2448 return self._getitem(self, parameters)
2449
2450
2451if hasattr(typing, "LiteralString"): # 3.11+
2452 LiteralString = typing.LiteralString
2453else:
2454 @_SpecialForm
2455 def LiteralString(self, params):
2456 """Represents an arbitrary literal string.
2457
2458 Example::
2459
2460 from typing_extensions import LiteralString
2461
2462 def query(sql: LiteralString) -> ...:
2463 ...
2464
2465 query("SELECT * FROM table") # ok
2466 query(f"SELECT * FROM {input()}") # not ok
2467
2468 See PEP 675 for details.
2469
2470 """
2471 raise TypeError(f"{self} is not subscriptable")
2472
2473
2474if hasattr(typing, "Self"): # 3.11+
2475 Self = typing.Self
2476else:
2477 @_SpecialForm
2478 def Self(self, params):
2479 """Used to spell the type of "self" in classes.
2480
2481 Example::
2482
2483 from typing import Self
2484
2485 class ReturnsSelf:
2486 def parse(self, data: bytes) -> Self:
2487 ...
2488 return self
2489
2490 """
2491
2492 raise TypeError(f"{self} is not subscriptable")
2493
2494
2495if hasattr(typing, "Never"): # 3.11+
2496 Never = typing.Never
2497else:
2498 @_SpecialForm
2499 def Never(self, params):
2500 """The bottom type, a type that has no members.
2501
2502 This can be used to define a function that should never be
2503 called, or a function that never returns::
2504
2505 from typing_extensions import Never
2506
2507 def never_call_me(arg: Never) -> None:
2508 pass
2509
2510 def int_or_str(arg: int | str) -> None:
2511 never_call_me(arg) # type checker error
2512 match arg:
2513 case int():
2514 print("It's an int")
2515 case str():
2516 print("It's a str")
2517 case _:
2518 never_call_me(arg) # ok, arg is of type Never
2519
2520 """
2521
2522 raise TypeError(f"{self} is not subscriptable")
2523
2524
2525if hasattr(typing, 'Required'): # 3.11+
2526 Required = typing.Required
2527 NotRequired = typing.NotRequired
2528elif sys.version_info[:2] >= (3, 9): # 3.9-3.10
2529 @_ExtensionsSpecialForm
2530 def Required(self, parameters):
2531 """A special typing construct to mark a key of a total=False TypedDict
2532 as required. For example:
2533
2534 class Movie(TypedDict, total=False):
2535 title: Required[str]
2536 year: int
2537
2538 m = Movie(
2539 title='The Matrix', # typechecker error if key is omitted
2540 year=1999,
2541 )
2542
2543 There is no runtime checking that a required key is actually provided
2544 when instantiating a related TypedDict.
2545 """
2546 item = typing._type_check(parameters, f'{self._name} accepts only a single type.')
2547 return typing._GenericAlias(self, (item,))
2548
2549 @_ExtensionsSpecialForm
2550 def NotRequired(self, parameters):
2551 """A special typing construct to mark a key of a TypedDict as
2552 potentially missing. For example:
2553
2554 class Movie(TypedDict):
2555 title: str
2556 year: NotRequired[int]
2557
2558 m = Movie(
2559 title='The Matrix', # typechecker error if key is omitted
2560 year=1999,
2561 )
2562 """
2563 item = typing._type_check(parameters, f'{self._name} accepts only a single type.')
2564 return typing._GenericAlias(self, (item,))
2565
2566else: # 3.8
2567 class _RequiredForm(_ExtensionsSpecialForm, _root=True):
2568 def __getitem__(self, parameters):
2569 item = typing._type_check(parameters,
2570 f'{self._name} accepts only a single type.')
2571 return typing._GenericAlias(self, (item,))
2572
2573 Required = _RequiredForm(
2574 'Required',
2575 doc="""A special typing construct to mark a key of a total=False TypedDict
2576 as required. For example:
2577
2578 class Movie(TypedDict, total=False):
2579 title: Required[str]
2580 year: int
2581
2582 m = Movie(
2583 title='The Matrix', # typechecker error if key is omitted
2584 year=1999,
2585 )
2586
2587 There is no runtime checking that a required key is actually provided
2588 when instantiating a related TypedDict.
2589 """)
2590 NotRequired = _RequiredForm(
2591 'NotRequired',
2592 doc="""A special typing construct to mark a key of a TypedDict as
2593 potentially missing. For example:
2594
2595 class Movie(TypedDict):
2596 title: str
2597 year: NotRequired[int]
2598
2599 m = Movie(
2600 title='The Matrix', # typechecker error if key is omitted
2601 year=1999,
2602 )
2603 """)
2604
2605
2606if hasattr(typing, 'ReadOnly'):
2607 ReadOnly = typing.ReadOnly
2608elif sys.version_info[:2] >= (3, 9): # 3.9-3.12
2609 @_ExtensionsSpecialForm
2610 def ReadOnly(self, parameters):
2611 """A special typing construct to mark an item of a TypedDict as read-only.
2612
2613 For example:
2614
2615 class Movie(TypedDict):
2616 title: ReadOnly[str]
2617 year: int
2618
2619 def mutate_movie(m: Movie) -> None:
2620 m["year"] = 1992 # allowed
2621 m["title"] = "The Matrix" # typechecker error
2622
2623 There is no runtime checking for this property.
2624 """
2625 item = typing._type_check(parameters, f'{self._name} accepts only a single type.')
2626 return typing._GenericAlias(self, (item,))
2627
2628else: # 3.8
2629 class _ReadOnlyForm(_ExtensionsSpecialForm, _root=True):
2630 def __getitem__(self, parameters):
2631 item = typing._type_check(parameters,
2632 f'{self._name} accepts only a single type.')
2633 return typing._GenericAlias(self, (item,))
2634
2635 ReadOnly = _ReadOnlyForm(
2636 'ReadOnly',
2637 doc="""A special typing construct to mark a key of a TypedDict as read-only.
2638
2639 For example:
2640
2641 class Movie(TypedDict):
2642 title: ReadOnly[str]
2643 year: int
2644
2645 def mutate_movie(m: Movie) -> None:
2646 m["year"] = 1992 # allowed
2647 m["title"] = "The Matrix" # typechecker error
2648
2649 There is no runtime checking for this propery.
2650 """)
2651
2652
2653_UNPACK_DOC = """\
2654Type unpack operator.
2655
2656The type unpack operator takes the child types from some container type,
2657such as `tuple[int, str]` or a `TypeVarTuple`, and 'pulls them out'. For
2658example:
2659
2660 # For some generic class `Foo`:
2661 Foo[Unpack[tuple[int, str]]] # Equivalent to Foo[int, str]
2662
2663 Ts = TypeVarTuple('Ts')
2664 # Specifies that `Bar` is generic in an arbitrary number of types.
2665 # (Think of `Ts` as a tuple of an arbitrary number of individual
2666 # `TypeVar`s, which the `Unpack` is 'pulling out' directly into the
2667 # `Generic[]`.)
2668 class Bar(Generic[Unpack[Ts]]): ...
2669 Bar[int] # Valid
2670 Bar[int, str] # Also valid
2671
2672From Python 3.11, this can also be done using the `*` operator:
2673
2674 Foo[*tuple[int, str]]
2675 class Bar(Generic[*Ts]): ...
2676
2677The operator can also be used along with a `TypedDict` to annotate
2678`**kwargs` in a function signature. For instance:
2679
2680 class Movie(TypedDict):
2681 name: str
2682 year: int
2683
2684 # This function expects two keyword arguments - *name* of type `str` and
2685 # *year* of type `int`.
2686 def foo(**kwargs: Unpack[Movie]): ...
2687
2688Note that there is only some runtime checking of this operator. Not
2689everything the runtime allows may be accepted by static type checkers.
2690
2691For more information, see PEP 646 and PEP 692.
2692"""
2693
2694
2695if sys.version_info >= (3, 12): # PEP 692 changed the repr of Unpack[]
2696 Unpack = typing.Unpack
2697
2698 def _is_unpack(obj):
2699 return get_origin(obj) is Unpack
2700
2701elif sys.version_info[:2] >= (3, 9): # 3.9+
2702 class _UnpackSpecialForm(_ExtensionsSpecialForm, _root=True):
2703 def __init__(self, getitem):
2704 super().__init__(getitem)
2705 self.__doc__ = _UNPACK_DOC
2706
2707 class _UnpackAlias(typing._GenericAlias, _root=True):
2708 if sys.version_info < (3, 11):
2709 # needed for compatibility with Generic[Unpack[Ts]]
2710 __class__ = typing.TypeVar
2711
2712 @property
2713 def __typing_unpacked_tuple_args__(self):
2714 assert self.__origin__ is Unpack
2715 assert len(self.__args__) == 1
2716 arg, = self.__args__
2717 if isinstance(arg, (typing._GenericAlias, _types.GenericAlias)):
2718 if arg.__origin__ is not tuple:
2719 raise TypeError("Unpack[...] must be used with a tuple type")
2720 return arg.__args__
2721 return None
2722
2723 @property
2724 def __typing_is_unpacked_typevartuple__(self):
2725 assert self.__origin__ is Unpack
2726 assert len(self.__args__) == 1
2727 return isinstance(self.__args__[0], TypeVarTuple)
2728
2729 def __getitem__(self, args):
2730 if self.__typing_is_unpacked_typevartuple__:
2731 return args
2732 return super().__getitem__(args)
2733
2734 @_UnpackSpecialForm
2735 def Unpack(self, parameters):
2736 item = typing._type_check(parameters, f'{self._name} accepts only a single type.')
2737 return _UnpackAlias(self, (item,))
2738
2739 def _is_unpack(obj):
2740 return isinstance(obj, _UnpackAlias)
2741
2742else: # 3.8
2743 class _UnpackAlias(typing._GenericAlias, _root=True):
2744 __class__ = typing.TypeVar
2745
2746 @property
2747 def __typing_unpacked_tuple_args__(self):
2748 assert self.__origin__ is Unpack
2749 assert len(self.__args__) == 1
2750 arg, = self.__args__
2751 if isinstance(arg, typing._GenericAlias):
2752 if arg.__origin__ is not tuple:
2753 raise TypeError("Unpack[...] must be used with a tuple type")
2754 return arg.__args__
2755 return None
2756
2757 @property
2758 def __typing_is_unpacked_typevartuple__(self):
2759 assert self.__origin__ is Unpack
2760 assert len(self.__args__) == 1
2761 return isinstance(self.__args__[0], TypeVarTuple)
2762
2763 def __getitem__(self, args):
2764 if self.__typing_is_unpacked_typevartuple__:
2765 return args
2766 return super().__getitem__(args)
2767
2768 class _UnpackForm(_ExtensionsSpecialForm, _root=True):
2769 def __getitem__(self, parameters):
2770 item = typing._type_check(parameters,
2771 f'{self._name} accepts only a single type.')
2772 return _UnpackAlias(self, (item,))
2773
2774 Unpack = _UnpackForm('Unpack', doc=_UNPACK_DOC)
2775
2776 def _is_unpack(obj):
2777 return isinstance(obj, _UnpackAlias)
2778
2779
2780def _unpack_args(*args):
2781 newargs = []
2782 for arg in args:
2783 subargs = getattr(arg, '__typing_unpacked_tuple_args__', None)
2784 if subargs is not None and (not (subargs and subargs[-1] is ...)):
2785 newargs.extend(subargs)
2786 else:
2787 newargs.append(arg)
2788 return newargs
2789
2790
2791if _PEP_696_IMPLEMENTED:
2792 from typing import TypeVarTuple
2793
2794elif hasattr(typing, "TypeVarTuple"): # 3.11+
2795
2796 # Add default parameter - PEP 696
2797 class TypeVarTuple(metaclass=_TypeVarLikeMeta):
2798 """Type variable tuple."""
2799
2800 _backported_typevarlike = typing.TypeVarTuple
2801
2802 def __new__(cls, name, *, default=NoDefault):
2803 tvt = typing.TypeVarTuple(name)
2804 _set_default(tvt, default)
2805 _set_module(tvt)
2806
2807 def _typevartuple_prepare_subst(alias, args):
2808 params = alias.__parameters__
2809 typevartuple_index = params.index(tvt)
2810 for param in params[typevartuple_index + 1:]:
2811 if isinstance(param, TypeVarTuple):
2812 raise TypeError(
2813 f"More than one TypeVarTuple parameter in {alias}"
2814 )
2815
2816 alen = len(args)
2817 plen = len(params)
2818 left = typevartuple_index
2819 right = plen - typevartuple_index - 1
2820 var_tuple_index = None
2821 fillarg = None
2822 for k, arg in enumerate(args):
2823 if not isinstance(arg, type):
2824 subargs = getattr(arg, '__typing_unpacked_tuple_args__', None)
2825 if subargs and len(subargs) == 2 and subargs[-1] is ...:
2826 if var_tuple_index is not None:
2827 raise TypeError(
2828 "More than one unpacked "
2829 "arbitrary-length tuple argument"
2830 )
2831 var_tuple_index = k
2832 fillarg = subargs[0]
2833 if var_tuple_index is not None:
2834 left = min(left, var_tuple_index)
2835 right = min(right, alen - var_tuple_index - 1)
2836 elif left + right > alen:
2837 raise TypeError(f"Too few arguments for {alias};"
2838 f" actual {alen}, expected at least {plen - 1}")
2839 if left == alen - right and tvt.has_default():
2840 replacement = _unpack_args(tvt.__default__)
2841 else:
2842 replacement = args[left: alen - right]
2843
2844 return (
2845 *args[:left],
2846 *([fillarg] * (typevartuple_index - left)),
2847 replacement,
2848 *([fillarg] * (plen - right - left - typevartuple_index - 1)),
2849 *args[alen - right:],
2850 )
2851
2852 tvt.__typing_prepare_subst__ = _typevartuple_prepare_subst
2853 return tvt
2854
2855 def __init_subclass__(self, *args, **kwds):
2856 raise TypeError("Cannot subclass special typing classes")
2857
2858else: # <=3.10
2859 class TypeVarTuple(_DefaultMixin):
2860 """Type variable tuple.
2861
2862 Usage::
2863
2864 Ts = TypeVarTuple('Ts')
2865
2866 In the same way that a normal type variable is a stand-in for a single
2867 type such as ``int``, a type variable *tuple* is a stand-in for a *tuple*
2868 type such as ``Tuple[int, str]``.
2869
2870 Type variable tuples can be used in ``Generic`` declarations.
2871 Consider the following example::
2872
2873 class Array(Generic[*Ts]): ...
2874
2875 The ``Ts`` type variable tuple here behaves like ``tuple[T1, T2]``,
2876 where ``T1`` and ``T2`` are type variables. To use these type variables
2877 as type parameters of ``Array``, we must *unpack* the type variable tuple using
2878 the star operator: ``*Ts``. The signature of ``Array`` then behaves
2879 as if we had simply written ``class Array(Generic[T1, T2]): ...``.
2880 In contrast to ``Generic[T1, T2]``, however, ``Generic[*Shape]`` allows
2881 us to parameterise the class with an *arbitrary* number of type parameters.
2882
2883 Type variable tuples can be used anywhere a normal ``TypeVar`` can.
2884 This includes class definitions, as shown above, as well as function
2885 signatures and variable annotations::
2886
2887 class Array(Generic[*Ts]):
2888
2889 def __init__(self, shape: Tuple[*Ts]):
2890 self._shape: Tuple[*Ts] = shape
2891
2892 def get_shape(self) -> Tuple[*Ts]:
2893 return self._shape
2894
2895 shape = (Height(480), Width(640))
2896 x: Array[Height, Width] = Array(shape)
2897 y = abs(x) # Inferred type is Array[Height, Width]
2898 z = x + x # ... is Array[Height, Width]
2899 x.get_shape() # ... is tuple[Height, Width]
2900
2901 """
2902
2903 # Trick Generic __parameters__.
2904 __class__ = typing.TypeVar
2905
2906 def __iter__(self):
2907 yield self.__unpacked__
2908
2909 def __init__(self, name, *, default=NoDefault):
2910 self.__name__ = name
2911 _DefaultMixin.__init__(self, default)
2912
2913 # for pickling:
2914 def_mod = _caller()
2915 if def_mod != 'typing_extensions':
2916 self.__module__ = def_mod
2917
2918 self.__unpacked__ = Unpack[self]
2919
2920 def __repr__(self):
2921 return self.__name__
2922
2923 def __hash__(self):
2924 return object.__hash__(self)
2925
2926 def __eq__(self, other):
2927 return self is other
2928
2929 def __reduce__(self):
2930 return self.__name__
2931
2932 def __init_subclass__(self, *args, **kwds):
2933 if '_root' not in kwds:
2934 raise TypeError("Cannot subclass special typing classes")
2935
2936
2937if hasattr(typing, "reveal_type"): # 3.11+
2938 reveal_type = typing.reveal_type
2939else: # <=3.10
2940 def reveal_type(obj: T, /) -> T:
2941 """Reveal the inferred type of a variable.
2942
2943 When a static type checker encounters a call to ``reveal_type()``,
2944 it will emit the inferred type of the argument::
2945
2946 x: int = 1
2947 reveal_type(x)
2948
2949 Running a static type checker (e.g., ``mypy``) on this example
2950 will produce output similar to 'Revealed type is "builtins.int"'.
2951
2952 At runtime, the function prints the runtime type of the
2953 argument and returns it unchanged.
2954
2955 """
2956 print(f"Runtime type is {type(obj).__name__!r}", file=sys.stderr)
2957 return obj
2958
2959
2960if hasattr(typing, "_ASSERT_NEVER_REPR_MAX_LENGTH"): # 3.11+
2961 _ASSERT_NEVER_REPR_MAX_LENGTH = typing._ASSERT_NEVER_REPR_MAX_LENGTH
2962else: # <=3.10
2963 _ASSERT_NEVER_REPR_MAX_LENGTH = 100
2964
2965
2966if hasattr(typing, "assert_never"): # 3.11+
2967 assert_never = typing.assert_never
2968else: # <=3.10
2969 def assert_never(arg: Never, /) -> Never:
2970 """Assert to the type checker that a line of code is unreachable.
2971
2972 Example::
2973
2974 def int_or_str(arg: int | str) -> None:
2975 match arg:
2976 case int():
2977 print("It's an int")
2978 case str():
2979 print("It's a str")
2980 case _:
2981 assert_never(arg)
2982
2983 If a type checker finds that a call to assert_never() is
2984 reachable, it will emit an error.
2985
2986 At runtime, this throws an exception when called.
2987
2988 """
2989 value = repr(arg)
2990 if len(value) > _ASSERT_NEVER_REPR_MAX_LENGTH:
2991 value = value[:_ASSERT_NEVER_REPR_MAX_LENGTH] + '...'
2992 raise AssertionError(f"Expected code to be unreachable, but got: {value}")
2993
2994
2995if sys.version_info >= (3, 12): # 3.12+
2996 # dataclass_transform exists in 3.11 but lacks the frozen_default parameter
2997 dataclass_transform = typing.dataclass_transform
2998else: # <=3.11
2999 def dataclass_transform(
3000 *,
3001 eq_default: bool = True,
3002 order_default: bool = False,
3003 kw_only_default: bool = False,
3004 frozen_default: bool = False,
3005 field_specifiers: typing.Tuple[
3006 typing.Union[typing.Type[typing.Any], typing.Callable[..., typing.Any]],
3007 ...
3008 ] = (),
3009 **kwargs: typing.Any,
3010 ) -> typing.Callable[[T], T]:
3011 """Decorator that marks a function, class, or metaclass as providing
3012 dataclass-like behavior.
3013
3014 Example:
3015
3016 from typing_extensions import dataclass_transform
3017
3018 _T = TypeVar("_T")
3019
3020 # Used on a decorator function
3021 @dataclass_transform()
3022 def create_model(cls: type[_T]) -> type[_T]:
3023 ...
3024 return cls
3025
3026 @create_model
3027 class CustomerModel:
3028 id: int
3029 name: str
3030
3031 # Used on a base class
3032 @dataclass_transform()
3033 class ModelBase: ...
3034
3035 class CustomerModel(ModelBase):
3036 id: int
3037 name: str
3038
3039 # Used on a metaclass
3040 @dataclass_transform()
3041 class ModelMeta(type): ...
3042
3043 class ModelBase(metaclass=ModelMeta): ...
3044
3045 class CustomerModel(ModelBase):
3046 id: int
3047 name: str
3048
3049 Each of the ``CustomerModel`` classes defined in this example will now
3050 behave similarly to a dataclass created with the ``@dataclasses.dataclass``
3051 decorator. For example, the type checker will synthesize an ``__init__``
3052 method.
3053
3054 The arguments to this decorator can be used to customize this behavior:
3055 - ``eq_default`` indicates whether the ``eq`` parameter is assumed to be
3056 True or False if it is omitted by the caller.
3057 - ``order_default`` indicates whether the ``order`` parameter is
3058 assumed to be True or False if it is omitted by the caller.
3059 - ``kw_only_default`` indicates whether the ``kw_only`` parameter is
3060 assumed to be True or False if it is omitted by the caller.
3061 - ``frozen_default`` indicates whether the ``frozen`` parameter is
3062 assumed to be True or False if it is omitted by the caller.
3063 - ``field_specifiers`` specifies a static list of supported classes
3064 or functions that describe fields, similar to ``dataclasses.field()``.
3065
3066 At runtime, this decorator records its arguments in the
3067 ``__dataclass_transform__`` attribute on the decorated object.
3068
3069 See PEP 681 for details.
3070
3071 """
3072 def decorator(cls_or_fn):
3073 cls_or_fn.__dataclass_transform__ = {
3074 "eq_default": eq_default,
3075 "order_default": order_default,
3076 "kw_only_default": kw_only_default,
3077 "frozen_default": frozen_default,
3078 "field_specifiers": field_specifiers,
3079 "kwargs": kwargs,
3080 }
3081 return cls_or_fn
3082 return decorator
3083
3084
3085if hasattr(typing, "override"): # 3.12+
3086 override = typing.override
3087else: # <=3.11
3088 _F = typing.TypeVar("_F", bound=typing.Callable[..., typing.Any])
3089
3090 def override(arg: _F, /) -> _F:
3091 """Indicate that a method is intended to override a method in a base class.
3092
3093 Usage:
3094
3095 class Base:
3096 def method(self) -> None:
3097 pass
3098
3099 class Child(Base):
3100 @override
3101 def method(self) -> None:
3102 super().method()
3103
3104 When this decorator is applied to a method, the type checker will
3105 validate that it overrides a method with the same name on a base class.
3106 This helps prevent bugs that may occur when a base class is changed
3107 without an equivalent change to a child class.
3108
3109 There is no runtime checking of these properties. The decorator
3110 sets the ``__override__`` attribute to ``True`` on the decorated object
3111 to allow runtime introspection.
3112
3113 See PEP 698 for details.
3114
3115 """
3116 try:
3117 arg.__override__ = True
3118 except (AttributeError, TypeError):
3119 # Skip the attribute silently if it is not writable.
3120 # AttributeError happens if the object has __slots__ or a
3121 # read-only property, TypeError if it's a builtin class.
3122 pass
3123 return arg
3124
3125
3126# Python 3.13.3+ contains a fix for the wrapped __new__
3127if sys.version_info >= (3, 13, 3):
3128 deprecated = warnings.deprecated
3129else:
3130 _T = typing.TypeVar("_T")
3131
3132 class deprecated:
3133 """Indicate that a class, function or overload is deprecated.
3134
3135 When this decorator is applied to an object, the type checker
3136 will generate a diagnostic on usage of the deprecated object.
3137
3138 Usage:
3139
3140 @deprecated("Use B instead")
3141 class A:
3142 pass
3143
3144 @deprecated("Use g instead")
3145 def f():
3146 pass
3147
3148 @overload
3149 @deprecated("int support is deprecated")
3150 def g(x: int) -> int: ...
3151 @overload
3152 def g(x: str) -> int: ...
3153
3154 The warning specified by *category* will be emitted at runtime
3155 on use of deprecated objects. For functions, that happens on calls;
3156 for classes, on instantiation and on creation of subclasses.
3157 If the *category* is ``None``, no warning is emitted at runtime.
3158 The *stacklevel* determines where the
3159 warning is emitted. If it is ``1`` (the default), the warning
3160 is emitted at the direct caller of the deprecated object; if it
3161 is higher, it is emitted further up the stack.
3162 Static type checker behavior is not affected by the *category*
3163 and *stacklevel* arguments.
3164
3165 The deprecation message passed to the decorator is saved in the
3166 ``__deprecated__`` attribute on the decorated object.
3167 If applied to an overload, the decorator
3168 must be after the ``@overload`` decorator for the attribute to
3169 exist on the overload as returned by ``get_overloads()``.
3170
3171 See PEP 702 for details.
3172
3173 """
3174 def __init__(
3175 self,
3176 message: str,
3177 /,
3178 *,
3179 category: typing.Optional[typing.Type[Warning]] = DeprecationWarning,
3180 stacklevel: int = 1,
3181 ) -> None:
3182 if not isinstance(message, str):
3183 raise TypeError(
3184 "Expected an object of type str for 'message', not "
3185 f"{type(message).__name__!r}"
3186 )
3187 self.message = message
3188 self.category = category
3189 self.stacklevel = stacklevel
3190
3191 def __call__(self, arg: _T, /) -> _T:
3192 # Make sure the inner functions created below don't
3193 # retain a reference to self.
3194 msg = self.message
3195 category = self.category
3196 stacklevel = self.stacklevel
3197 if category is None:
3198 arg.__deprecated__ = msg
3199 return arg
3200 elif isinstance(arg, type):
3201 import functools
3202 from types import MethodType
3203
3204 original_new = arg.__new__
3205
3206 @functools.wraps(original_new)
3207 def __new__(cls, /, *args, **kwargs):
3208 if cls is arg:
3209 warnings.warn(msg, category=category, stacklevel=stacklevel + 1)
3210 if original_new is not object.__new__:
3211 return original_new(cls, *args, **kwargs)
3212 # Mirrors a similar check in object.__new__.
3213 elif cls.__init__ is object.__init__ and (args or kwargs):
3214 raise TypeError(f"{cls.__name__}() takes no arguments")
3215 else:
3216 return original_new(cls)
3217
3218 arg.__new__ = staticmethod(__new__)
3219
3220 original_init_subclass = arg.__init_subclass__
3221 # We need slightly different behavior if __init_subclass__
3222 # is a bound method (likely if it was implemented in Python)
3223 if isinstance(original_init_subclass, MethodType):
3224 original_init_subclass = original_init_subclass.__func__
3225
3226 @functools.wraps(original_init_subclass)
3227 def __init_subclass__(*args, **kwargs):
3228 warnings.warn(msg, category=category, stacklevel=stacklevel + 1)
3229 return original_init_subclass(*args, **kwargs)
3230
3231 arg.__init_subclass__ = classmethod(__init_subclass__)
3232 # Or otherwise, which likely means it's a builtin such as
3233 # object's implementation of __init_subclass__.
3234 else:
3235 @functools.wraps(original_init_subclass)
3236 def __init_subclass__(*args, **kwargs):
3237 warnings.warn(msg, category=category, stacklevel=stacklevel + 1)
3238 return original_init_subclass(*args, **kwargs)
3239
3240 arg.__init_subclass__ = __init_subclass__
3241
3242 arg.__deprecated__ = __new__.__deprecated__ = msg
3243 __init_subclass__.__deprecated__ = msg
3244 return arg
3245 elif callable(arg):
3246 import asyncio.coroutines
3247 import functools
3248 import inspect
3249
3250 @functools.wraps(arg)
3251 def wrapper(*args, **kwargs):
3252 warnings.warn(msg, category=category, stacklevel=stacklevel + 1)
3253 return arg(*args, **kwargs)
3254
3255 if asyncio.coroutines.iscoroutinefunction(arg):
3256 if sys.version_info >= (3, 12):
3257 wrapper = inspect.markcoroutinefunction(wrapper)
3258 else:
3259 wrapper._is_coroutine = asyncio.coroutines._is_coroutine
3260
3261 arg.__deprecated__ = wrapper.__deprecated__ = msg
3262 return wrapper
3263 else:
3264 raise TypeError(
3265 "@deprecated decorator with non-None category must be applied to "
3266 f"a class or callable, not {arg!r}"
3267 )
3268
3269if sys.version_info < (3, 10):
3270 def _is_param_expr(arg):
3271 return arg is ... or isinstance(
3272 arg, (tuple, list, ParamSpec, _ConcatenateGenericAlias)
3273 )
3274else:
3275 def _is_param_expr(arg):
3276 return arg is ... or isinstance(
3277 arg,
3278 (
3279 tuple,
3280 list,
3281 ParamSpec,
3282 _ConcatenateGenericAlias,
3283 typing._ConcatenateGenericAlias,
3284 ),
3285 )
3286
3287
3288# We have to do some monkey patching to deal with the dual nature of
3289# Unpack/TypeVarTuple:
3290# - We want Unpack to be a kind of TypeVar so it gets accepted in
3291# Generic[Unpack[Ts]]
3292# - We want it to *not* be treated as a TypeVar for the purposes of
3293# counting generic parameters, so that when we subscript a generic,
3294# the runtime doesn't try to substitute the Unpack with the subscripted type.
3295if not hasattr(typing, "TypeVarTuple"):
3296 def _check_generic(cls, parameters, elen=_marker):
3297 """Check correct count for parameters of a generic cls (internal helper).
3298
3299 This gives a nice error message in case of count mismatch.
3300 """
3301 # If substituting a single ParamSpec with multiple arguments
3302 # we do not check the count
3303 if (inspect.isclass(cls) and issubclass(cls, typing.Generic)
3304 and len(cls.__parameters__) == 1
3305 and isinstance(cls.__parameters__[0], ParamSpec)
3306 and parameters
3307 and not _is_param_expr(parameters[0])
3308 ):
3309 # Generic modifies parameters variable, but here we cannot do this
3310 return
3311
3312 if not elen:
3313 raise TypeError(f"{cls} is not a generic class")
3314 if elen is _marker:
3315 if not hasattr(cls, "__parameters__") or not cls.__parameters__:
3316 raise TypeError(f"{cls} is not a generic class")
3317 elen = len(cls.__parameters__)
3318 alen = len(parameters)
3319 if alen != elen:
3320 expect_val = elen
3321 if hasattr(cls, "__parameters__"):
3322 parameters = [p for p in cls.__parameters__ if not _is_unpack(p)]
3323 num_tv_tuples = sum(isinstance(p, TypeVarTuple) for p in parameters)
3324 if (num_tv_tuples > 0) and (alen >= elen - num_tv_tuples):
3325 return
3326
3327 # deal with TypeVarLike defaults
3328 # required TypeVarLikes cannot appear after a defaulted one.
3329 if alen < elen:
3330 # since we validate TypeVarLike default in _collect_type_vars
3331 # or _collect_parameters we can safely check parameters[alen]
3332 if (
3333 getattr(parameters[alen], '__default__', NoDefault)
3334 is not NoDefault
3335 ):
3336 return
3337
3338 num_default_tv = sum(getattr(p, '__default__', NoDefault)
3339 is not NoDefault for p in parameters)
3340
3341 elen -= num_default_tv
3342
3343 expect_val = f"at least {elen}"
3344
3345 things = "arguments" if sys.version_info >= (3, 10) else "parameters"
3346 raise TypeError(f"Too {'many' if alen > elen else 'few'} {things}"
3347 f" for {cls}; actual {alen}, expected {expect_val}")
3348else:
3349 # Python 3.11+
3350
3351 def _check_generic(cls, parameters, elen):
3352 """Check correct count for parameters of a generic cls (internal helper).
3353
3354 This gives a nice error message in case of count mismatch.
3355 """
3356 if not elen:
3357 raise TypeError(f"{cls} is not a generic class")
3358 alen = len(parameters)
3359 if alen != elen:
3360 expect_val = elen
3361 if hasattr(cls, "__parameters__"):
3362 parameters = [p for p in cls.__parameters__ if not _is_unpack(p)]
3363
3364 # deal with TypeVarLike defaults
3365 # required TypeVarLikes cannot appear after a defaulted one.
3366 if alen < elen:
3367 # since we validate TypeVarLike default in _collect_type_vars
3368 # or _collect_parameters we can safely check parameters[alen]
3369 if (
3370 getattr(parameters[alen], '__default__', NoDefault)
3371 is not NoDefault
3372 ):
3373 return
3374
3375 num_default_tv = sum(getattr(p, '__default__', NoDefault)
3376 is not NoDefault for p in parameters)
3377
3378 elen -= num_default_tv
3379
3380 expect_val = f"at least {elen}"
3381
3382 raise TypeError(f"Too {'many' if alen > elen else 'few'} arguments"
3383 f" for {cls}; actual {alen}, expected {expect_val}")
3384
3385if not _PEP_696_IMPLEMENTED:
3386 typing._check_generic = _check_generic
3387
3388
3389def _has_generic_or_protocol_as_origin() -> bool:
3390 try:
3391 frame = sys._getframe(2)
3392 # - Catch AttributeError: not all Python implementations have sys._getframe()
3393 # - Catch ValueError: maybe we're called from an unexpected module
3394 # and the call stack isn't deep enough
3395 except (AttributeError, ValueError):
3396 return False # err on the side of leniency
3397 else:
3398 # If we somehow get invoked from outside typing.py,
3399 # also err on the side of leniency
3400 if frame.f_globals.get("__name__") != "typing":
3401 return False
3402 origin = frame.f_locals.get("origin")
3403 # Cannot use "in" because origin may be an object with a buggy __eq__ that
3404 # throws an error.
3405 return origin is typing.Generic or origin is Protocol or origin is typing.Protocol
3406
3407
3408_TYPEVARTUPLE_TYPES = {TypeVarTuple, getattr(typing, "TypeVarTuple", None)}
3409
3410
3411def _is_unpacked_typevartuple(x) -> bool:
3412 if get_origin(x) is not Unpack:
3413 return False
3414 args = get_args(x)
3415 return (
3416 bool(args)
3417 and len(args) == 1
3418 and type(args[0]) in _TYPEVARTUPLE_TYPES
3419 )
3420
3421
3422# Python 3.11+ _collect_type_vars was renamed to _collect_parameters
3423if hasattr(typing, '_collect_type_vars'):
3424 def _collect_type_vars(types, typevar_types=None):
3425 """Collect all type variable contained in types in order of
3426 first appearance (lexicographic order). For example::
3427
3428 _collect_type_vars((T, List[S, T])) == (T, S)
3429 """
3430 if typevar_types is None:
3431 typevar_types = typing.TypeVar
3432 tvars = []
3433
3434 # A required TypeVarLike cannot appear after a TypeVarLike with a default
3435 # if it was a direct call to `Generic[]` or `Protocol[]`
3436 enforce_default_ordering = _has_generic_or_protocol_as_origin()
3437 default_encountered = False
3438
3439 # Also, a TypeVarLike with a default cannot appear after a TypeVarTuple
3440 type_var_tuple_encountered = False
3441
3442 for t in types:
3443 if _is_unpacked_typevartuple(t):
3444 type_var_tuple_encountered = True
3445 elif (
3446 isinstance(t, typevar_types) and not isinstance(t, _UnpackAlias)
3447 and t not in tvars
3448 ):
3449 if enforce_default_ordering:
3450 has_default = getattr(t, '__default__', NoDefault) is not NoDefault
3451 if has_default:
3452 if type_var_tuple_encountered:
3453 raise TypeError('Type parameter with a default'
3454 ' follows TypeVarTuple')
3455 default_encountered = True
3456 elif default_encountered:
3457 raise TypeError(f'Type parameter {t!r} without a default'
3458 ' follows type parameter with a default')
3459
3460 tvars.append(t)
3461 if _should_collect_from_parameters(t):
3462 tvars.extend([t for t in t.__parameters__ if t not in tvars])
3463 elif isinstance(t, tuple):
3464 # Collect nested type_vars
3465 # tuple wrapped by _prepare_paramspec_params(cls, params)
3466 for x in t:
3467 for collected in _collect_type_vars([x]):
3468 if collected not in tvars:
3469 tvars.append(collected)
3470 return tuple(tvars)
3471
3472 typing._collect_type_vars = _collect_type_vars
3473else:
3474 def _collect_parameters(args):
3475 """Collect all type variables and parameter specifications in args
3476 in order of first appearance (lexicographic order).
3477
3478 For example::
3479
3480 assert _collect_parameters((T, Callable[P, T])) == (T, P)
3481 """
3482 parameters = []
3483
3484 # A required TypeVarLike cannot appear after a TypeVarLike with default
3485 # if it was a direct call to `Generic[]` or `Protocol[]`
3486 enforce_default_ordering = _has_generic_or_protocol_as_origin()
3487 default_encountered = False
3488
3489 # Also, a TypeVarLike with a default cannot appear after a TypeVarTuple
3490 type_var_tuple_encountered = False
3491
3492 for t in args:
3493 if isinstance(t, type):
3494 # We don't want __parameters__ descriptor of a bare Python class.
3495 pass
3496 elif isinstance(t, tuple):
3497 # `t` might be a tuple, when `ParamSpec` is substituted with
3498 # `[T, int]`, or `[int, *Ts]`, etc.
3499 for x in t:
3500 for collected in _collect_parameters([x]):
3501 if collected not in parameters:
3502 parameters.append(collected)
3503 elif hasattr(t, '__typing_subst__'):
3504 if t not in parameters:
3505 if enforce_default_ordering:
3506 has_default = (
3507 getattr(t, '__default__', NoDefault) is not NoDefault
3508 )
3509
3510 if type_var_tuple_encountered and has_default:
3511 raise TypeError('Type parameter with a default'
3512 ' follows TypeVarTuple')
3513
3514 if has_default:
3515 default_encountered = True
3516 elif default_encountered:
3517 raise TypeError(f'Type parameter {t!r} without a default'
3518 ' follows type parameter with a default')
3519
3520 parameters.append(t)
3521 else:
3522 if _is_unpacked_typevartuple(t):
3523 type_var_tuple_encountered = True
3524 for x in getattr(t, '__parameters__', ()):
3525 if x not in parameters:
3526 parameters.append(x)
3527
3528 return tuple(parameters)
3529
3530 if not _PEP_696_IMPLEMENTED:
3531 typing._collect_parameters = _collect_parameters
3532
3533# Backport typing.NamedTuple as it exists in Python 3.13.
3534# In 3.11, the ability to define generic `NamedTuple`s was supported.
3535# This was explicitly disallowed in 3.9-3.10, and only half-worked in <=3.8.
3536# On 3.12, we added __orig_bases__ to call-based NamedTuples
3537# On 3.13, we deprecated kwargs-based NamedTuples
3538if sys.version_info >= (3, 13):
3539 NamedTuple = typing.NamedTuple
3540else:
3541 def _make_nmtuple(name, types, module, defaults=()):
3542 fields = [n for n, t in types]
3543 annotations = {n: typing._type_check(t, f"field {n} annotation must be a type")
3544 for n, t in types}
3545 nm_tpl = collections.namedtuple(name, fields,
3546 defaults=defaults, module=module)
3547 nm_tpl.__annotations__ = nm_tpl.__new__.__annotations__ = annotations
3548 # The `_field_types` attribute was removed in 3.9;
3549 # in earlier versions, it is the same as the `__annotations__` attribute
3550 if sys.version_info < (3, 9):
3551 nm_tpl._field_types = annotations
3552 return nm_tpl
3553
3554 _prohibited_namedtuple_fields = typing._prohibited
3555 _special_namedtuple_fields = frozenset({'__module__', '__name__', '__annotations__'})
3556
3557 class _NamedTupleMeta(type):
3558 def __new__(cls, typename, bases, ns):
3559 assert _NamedTuple in bases
3560 for base in bases:
3561 if base is not _NamedTuple and base is not typing.Generic:
3562 raise TypeError(
3563 'can only inherit from a NamedTuple type and Generic')
3564 bases = tuple(tuple if base is _NamedTuple else base for base in bases)
3565 if "__annotations__" in ns:
3566 types = ns["__annotations__"]
3567 elif "__annotate__" in ns:
3568 # TODO: Use inspect.VALUE here, and make the annotations lazily evaluated
3569 types = ns["__annotate__"](1)
3570 else:
3571 types = {}
3572 default_names = []
3573 for field_name in types:
3574 if field_name in ns:
3575 default_names.append(field_name)
3576 elif default_names:
3577 raise TypeError(f"Non-default namedtuple field {field_name} "
3578 f"cannot follow default field"
3579 f"{'s' if len(default_names) > 1 else ''} "
3580 f"{', '.join(default_names)}")
3581 nm_tpl = _make_nmtuple(
3582 typename, types.items(),
3583 defaults=[ns[n] for n in default_names],
3584 module=ns['__module__']
3585 )
3586 nm_tpl.__bases__ = bases
3587 if typing.Generic in bases:
3588 if hasattr(typing, '_generic_class_getitem'): # 3.12+
3589 nm_tpl.__class_getitem__ = classmethod(typing._generic_class_getitem)
3590 else:
3591 class_getitem = typing.Generic.__class_getitem__.__func__
3592 nm_tpl.__class_getitem__ = classmethod(class_getitem)
3593 # update from user namespace without overriding special namedtuple attributes
3594 for key, val in ns.items():
3595 if key in _prohibited_namedtuple_fields:
3596 raise AttributeError("Cannot overwrite NamedTuple attribute " + key)
3597 elif key not in _special_namedtuple_fields:
3598 if key not in nm_tpl._fields:
3599 setattr(nm_tpl, key, ns[key])
3600 try:
3601 set_name = type(val).__set_name__
3602 except AttributeError:
3603 pass
3604 else:
3605 try:
3606 set_name(val, nm_tpl, key)
3607 except BaseException as e:
3608 msg = (
3609 f"Error calling __set_name__ on {type(val).__name__!r} "
3610 f"instance {key!r} in {typename!r}"
3611 )
3612 # BaseException.add_note() existed on py311,
3613 # but the __set_name__ machinery didn't start
3614 # using add_note() until py312.
3615 # Making sure exceptions are raised in the same way
3616 # as in "normal" classes seems most important here.
3617 if sys.version_info >= (3, 12):
3618 e.add_note(msg)
3619 raise
3620 else:
3621 raise RuntimeError(msg) from e
3622
3623 if typing.Generic in bases:
3624 nm_tpl.__init_subclass__()
3625 return nm_tpl
3626
3627 _NamedTuple = type.__new__(_NamedTupleMeta, 'NamedTuple', (), {})
3628
3629 def _namedtuple_mro_entries(bases):
3630 assert NamedTuple in bases
3631 return (_NamedTuple,)
3632
3633 @_ensure_subclassable(_namedtuple_mro_entries)
3634 def NamedTuple(typename, fields=_marker, /, **kwargs):
3635 """Typed version of namedtuple.
3636
3637 Usage::
3638
3639 class Employee(NamedTuple):
3640 name: str
3641 id: int
3642
3643 This is equivalent to::
3644
3645 Employee = collections.namedtuple('Employee', ['name', 'id'])
3646
3647 The resulting class has an extra __annotations__ attribute, giving a
3648 dict that maps field names to types. (The field names are also in
3649 the _fields attribute, which is part of the namedtuple API.)
3650 An alternative equivalent functional syntax is also accepted::
3651
3652 Employee = NamedTuple('Employee', [('name', str), ('id', int)])
3653 """
3654 if fields is _marker:
3655 if kwargs:
3656 deprecated_thing = "Creating NamedTuple classes using keyword arguments"
3657 deprecation_msg = (
3658 "{name} is deprecated and will be disallowed in Python {remove}. "
3659 "Use the class-based or functional syntax instead."
3660 )
3661 else:
3662 deprecated_thing = "Failing to pass a value for the 'fields' parameter"
3663 example = f"`{typename} = NamedTuple({typename!r}, [])`"
3664 deprecation_msg = (
3665 "{name} is deprecated and will be disallowed in Python {remove}. "
3666 "To create a NamedTuple class with 0 fields "
3667 "using the functional syntax, "
3668 "pass an empty list, e.g. "
3669 ) + example + "."
3670 elif fields is None:
3671 if kwargs:
3672 raise TypeError(
3673 "Cannot pass `None` as the 'fields' parameter "
3674 "and also specify fields using keyword arguments"
3675 )
3676 else:
3677 deprecated_thing = "Passing `None` as the 'fields' parameter"
3678 example = f"`{typename} = NamedTuple({typename!r}, [])`"
3679 deprecation_msg = (
3680 "{name} is deprecated and will be disallowed in Python {remove}. "
3681 "To create a NamedTuple class with 0 fields "
3682 "using the functional syntax, "
3683 "pass an empty list, e.g. "
3684 ) + example + "."
3685 elif kwargs:
3686 raise TypeError("Either list of fields or keywords"
3687 " can be provided to NamedTuple, not both")
3688 if fields is _marker or fields is None:
3689 warnings.warn(
3690 deprecation_msg.format(name=deprecated_thing, remove="3.15"),
3691 DeprecationWarning,
3692 stacklevel=2,
3693 )
3694 fields = kwargs.items()
3695 nt = _make_nmtuple(typename, fields, module=_caller())
3696 nt.__orig_bases__ = (NamedTuple,)
3697 return nt
3698
3699
3700if hasattr(collections.abc, "Buffer"):
3701 Buffer = collections.abc.Buffer
3702else:
3703 class Buffer(abc.ABC): # noqa: B024
3704 """Base class for classes that implement the buffer protocol.
3705
3706 The buffer protocol allows Python objects to expose a low-level
3707 memory buffer interface. Before Python 3.12, it is not possible
3708 to implement the buffer protocol in pure Python code, or even
3709 to check whether a class implements the buffer protocol. In
3710 Python 3.12 and higher, the ``__buffer__`` method allows access
3711 to the buffer protocol from Python code, and the
3712 ``collections.abc.Buffer`` ABC allows checking whether a class
3713 implements the buffer protocol.
3714
3715 To indicate support for the buffer protocol in earlier versions,
3716 inherit from this ABC, either in a stub file or at runtime,
3717 or use ABC registration. This ABC provides no methods, because
3718 there is no Python-accessible methods shared by pre-3.12 buffer
3719 classes. It is useful primarily for static checks.
3720
3721 """
3722
3723 # As a courtesy, register the most common stdlib buffer classes.
3724 Buffer.register(memoryview)
3725 Buffer.register(bytearray)
3726 Buffer.register(bytes)
3727
3728
3729# Backport of types.get_original_bases, available on 3.12+ in CPython
3730if hasattr(_types, "get_original_bases"):
3731 get_original_bases = _types.get_original_bases
3732else:
3733 def get_original_bases(cls, /):
3734 """Return the class's "original" bases prior to modification by `__mro_entries__`.
3735
3736 Examples::
3737
3738 from typing import TypeVar, Generic
3739 from typing_extensions import NamedTuple, TypedDict
3740
3741 T = TypeVar("T")
3742 class Foo(Generic[T]): ...
3743 class Bar(Foo[int], float): ...
3744 class Baz(list[str]): ...
3745 Eggs = NamedTuple("Eggs", [("a", int), ("b", str)])
3746 Spam = TypedDict("Spam", {"a": int, "b": str})
3747
3748 assert get_original_bases(Bar) == (Foo[int], float)
3749 assert get_original_bases(Baz) == (list[str],)
3750 assert get_original_bases(Eggs) == (NamedTuple,)
3751 assert get_original_bases(Spam) == (TypedDict,)
3752 assert get_original_bases(int) == (object,)
3753 """
3754 try:
3755 return cls.__dict__.get("__orig_bases__", cls.__bases__)
3756 except AttributeError:
3757 raise TypeError(
3758 f'Expected an instance of type, not {type(cls).__name__!r}'
3759 ) from None
3760
3761
3762# NewType is a class on Python 3.10+, making it pickleable
3763# The error message for subclassing instances of NewType was improved on 3.11+
3764if sys.version_info >= (3, 11):
3765 NewType = typing.NewType
3766else:
3767 class NewType:
3768 """NewType creates simple unique types with almost zero
3769 runtime overhead. NewType(name, tp) is considered a subtype of tp
3770 by static type checkers. At runtime, NewType(name, tp) returns
3771 a dummy callable that simply returns its argument. Usage::
3772 UserId = NewType('UserId', int)
3773 def name_by_id(user_id: UserId) -> str:
3774 ...
3775 UserId('user') # Fails type check
3776 name_by_id(42) # Fails type check
3777 name_by_id(UserId(42)) # OK
3778 num = UserId(5) + 1 # type: int
3779 """
3780
3781 def __call__(self, obj, /):
3782 return obj
3783
3784 def __init__(self, name, tp):
3785 self.__qualname__ = name
3786 if '.' in name:
3787 name = name.rpartition('.')[-1]
3788 self.__name__ = name
3789 self.__supertype__ = tp
3790 def_mod = _caller()
3791 if def_mod != 'typing_extensions':
3792 self.__module__ = def_mod
3793
3794 def __mro_entries__(self, bases):
3795 # We defined __mro_entries__ to get a better error message
3796 # if a user attempts to subclass a NewType instance. bpo-46170
3797 supercls_name = self.__name__
3798
3799 class Dummy:
3800 def __init_subclass__(cls):
3801 subcls_name = cls.__name__
3802 raise TypeError(
3803 f"Cannot subclass an instance of NewType. "
3804 f"Perhaps you were looking for: "
3805 f"`{subcls_name} = NewType({subcls_name!r}, {supercls_name})`"
3806 )
3807
3808 return (Dummy,)
3809
3810 def __repr__(self):
3811 return f'{self.__module__}.{self.__qualname__}'
3812
3813 def __reduce__(self):
3814 return self.__qualname__
3815
3816 if sys.version_info >= (3, 10):
3817 # PEP 604 methods
3818 # It doesn't make sense to have these methods on Python <3.10
3819
3820 def __or__(self, other):
3821 return typing.Union[self, other]
3822
3823 def __ror__(self, other):
3824 return typing.Union[other, self]
3825
3826
3827if sys.version_info >= (3, 14):
3828 TypeAliasType = typing.TypeAliasType
3829# 3.8-3.13
3830else:
3831 if sys.version_info >= (3, 12):
3832 # 3.12-3.14
3833 def _is_unionable(obj):
3834 """Corresponds to is_unionable() in unionobject.c in CPython."""
3835 return obj is None or isinstance(obj, (
3836 type,
3837 _types.GenericAlias,
3838 _types.UnionType,
3839 typing.TypeAliasType,
3840 TypeAliasType,
3841 ))
3842 else:
3843 # 3.8-3.11
3844 def _is_unionable(obj):
3845 """Corresponds to is_unionable() in unionobject.c in CPython."""
3846 return obj is None or isinstance(obj, (
3847 type,
3848 _types.GenericAlias,
3849 _types.UnionType,
3850 TypeAliasType,
3851 ))
3852
3853 if sys.version_info < (3, 10):
3854 # Copied and pasted from https://github.com/python/cpython/blob/986a4e1b6fcae7fe7a1d0a26aea446107dd58dd2/Objects/genericaliasobject.c#L568-L582,
3855 # so that we emulate the behaviour of `types.GenericAlias`
3856 # on the latest versions of CPython
3857 _ATTRIBUTE_DELEGATION_EXCLUSIONS = frozenset({
3858 "__class__",
3859 "__bases__",
3860 "__origin__",
3861 "__args__",
3862 "__unpacked__",
3863 "__parameters__",
3864 "__typing_unpacked_tuple_args__",
3865 "__mro_entries__",
3866 "__reduce_ex__",
3867 "__reduce__",
3868 "__copy__",
3869 "__deepcopy__",
3870 })
3871
3872 class _TypeAliasGenericAlias(typing._GenericAlias, _root=True):
3873 def __getattr__(self, attr):
3874 if attr in _ATTRIBUTE_DELEGATION_EXCLUSIONS:
3875 return object.__getattr__(self, attr)
3876 return getattr(self.__origin__, attr)
3877
3878 if sys.version_info < (3, 9):
3879 def __getitem__(self, item):
3880 result = super().__getitem__(item)
3881 result.__class__ = type(self)
3882 return result
3883
3884 class TypeAliasType:
3885 """Create named, parameterized type aliases.
3886
3887 This provides a backport of the new `type` statement in Python 3.12:
3888
3889 type ListOrSet[T] = list[T] | set[T]
3890
3891 is equivalent to:
3892
3893 T = TypeVar("T")
3894 ListOrSet = TypeAliasType("ListOrSet", list[T] | set[T], type_params=(T,))
3895
3896 The name ListOrSet can then be used as an alias for the type it refers to.
3897
3898 The type_params argument should contain all the type parameters used
3899 in the value of the type alias. If the alias is not generic, this
3900 argument is omitted.
3901
3902 Static type checkers should only support type aliases declared using
3903 TypeAliasType that follow these rules:
3904
3905 - The first argument (the name) must be a string literal.
3906 - The TypeAliasType instance must be immediately assigned to a variable
3907 of the same name. (For example, 'X = TypeAliasType("Y", int)' is invalid,
3908 as is 'X, Y = TypeAliasType("X", int), TypeAliasType("Y", int)').
3909
3910 """
3911
3912 def __init__(self, name: str, value, *, type_params=()):
3913 if not isinstance(name, str):
3914 raise TypeError("TypeAliasType name must be a string")
3915 if not isinstance(type_params, tuple):
3916 raise TypeError("type_params must be a tuple")
3917 self.__value__ = value
3918 self.__type_params__ = type_params
3919
3920 default_value_encountered = False
3921 parameters = []
3922 for type_param in type_params:
3923 if (
3924 not isinstance(type_param, (TypeVar, TypeVarTuple, ParamSpec))
3925 # 3.8-3.11
3926 # Unpack Backport passes isinstance(type_param, TypeVar)
3927 or _is_unpack(type_param)
3928 ):
3929 raise TypeError(f"Expected a type param, got {type_param!r}")
3930 has_default = (
3931 getattr(type_param, '__default__', NoDefault) is not NoDefault
3932 )
3933 if default_value_encountered and not has_default:
3934 raise TypeError(f"non-default type parameter '{type_param!r}'"
3935 " follows default type parameter")
3936 if has_default:
3937 default_value_encountered = True
3938 if isinstance(type_param, TypeVarTuple):
3939 parameters.extend(type_param)
3940 else:
3941 parameters.append(type_param)
3942 self.__parameters__ = tuple(parameters)
3943 def_mod = _caller()
3944 if def_mod != 'typing_extensions':
3945 self.__module__ = def_mod
3946 # Setting this attribute closes the TypeAliasType from further modification
3947 self.__name__ = name
3948
3949 def __setattr__(self, name: str, value: object, /) -> None:
3950 if hasattr(self, "__name__"):
3951 self._raise_attribute_error(name)
3952 super().__setattr__(name, value)
3953
3954 def __delattr__(self, name: str, /) -> Never:
3955 self._raise_attribute_error(name)
3956
3957 def _raise_attribute_error(self, name: str) -> Never:
3958 # Match the Python 3.12 error messages exactly
3959 if name == "__name__":
3960 raise AttributeError("readonly attribute")
3961 elif name in {"__value__", "__type_params__", "__parameters__", "__module__"}:
3962 raise AttributeError(
3963 f"attribute '{name}' of 'typing.TypeAliasType' objects "
3964 "is not writable"
3965 )
3966 else:
3967 raise AttributeError(
3968 f"'typing.TypeAliasType' object has no attribute '{name}'"
3969 )
3970
3971 def __repr__(self) -> str:
3972 return self.__name__
3973
3974 if sys.version_info < (3, 11):
3975 def _check_single_param(self, param, recursion=0):
3976 # Allow [], [int], [int, str], [int, ...], [int, T]
3977 if param is ...:
3978 return ...
3979 if param is None:
3980 return None
3981 # Note in <= 3.9 _ConcatenateGenericAlias inherits from list
3982 if isinstance(param, list) and recursion == 0:
3983 return [self._check_single_param(arg, recursion+1)
3984 for arg in param]
3985 return typing._type_check(
3986 param, f'Subscripting {self.__name__} requires a type.'
3987 )
3988
3989 def _check_parameters(self, parameters):
3990 if sys.version_info < (3, 11):
3991 return tuple(
3992 self._check_single_param(item)
3993 for item in parameters
3994 )
3995 return tuple(typing._type_check(
3996 item, f'Subscripting {self.__name__} requires a type.'
3997 )
3998 for item in parameters
3999 )
4000
4001 def __getitem__(self, parameters):
4002 if not self.__type_params__:
4003 raise TypeError("Only generic type aliases are subscriptable")
4004 if not isinstance(parameters, tuple):
4005 parameters = (parameters,)
4006 # Using 3.9 here will create problems with Concatenate
4007 if sys.version_info >= (3, 10):
4008 return _types.GenericAlias(self, parameters)
4009 type_vars = _collect_type_vars(parameters)
4010 parameters = self._check_parameters(parameters)
4011 alias = _TypeAliasGenericAlias(self, parameters)
4012 # alias.__parameters__ is not complete if Concatenate is present
4013 # as it is converted to a list from which no parameters are extracted.
4014 if alias.__parameters__ != type_vars:
4015 alias.__parameters__ = type_vars
4016 return alias
4017
4018 def __reduce__(self):
4019 return self.__name__
4020
4021 def __init_subclass__(cls, *args, **kwargs):
4022 raise TypeError(
4023 "type 'typing_extensions.TypeAliasType' is not an acceptable base type"
4024 )
4025
4026 # The presence of this method convinces typing._type_check
4027 # that TypeAliasTypes are types.
4028 def __call__(self):
4029 raise TypeError("Type alias is not callable")
4030
4031 if sys.version_info >= (3, 10):
4032 def __or__(self, right):
4033 # For forward compatibility with 3.12, reject Unions
4034 # that are not accepted by the built-in Union.
4035 if not _is_unionable(right):
4036 return NotImplemented
4037 return typing.Union[self, right]
4038
4039 def __ror__(self, left):
4040 if not _is_unionable(left):
4041 return NotImplemented
4042 return typing.Union[left, self]
4043
4044
4045if hasattr(typing, "is_protocol"):
4046 is_protocol = typing.is_protocol
4047 get_protocol_members = typing.get_protocol_members
4048else:
4049 def is_protocol(tp: type, /) -> bool:
4050 """Return True if the given type is a Protocol.
4051
4052 Example::
4053
4054 >>> from typing_extensions import Protocol, is_protocol
4055 >>> class P(Protocol):
4056 ... def a(self) -> str: ...
4057 ... b: int
4058 >>> is_protocol(P)
4059 True
4060 >>> is_protocol(int)
4061 False
4062 """
4063 return (
4064 isinstance(tp, type)
4065 and getattr(tp, '_is_protocol', False)
4066 and tp is not Protocol
4067 and tp is not typing.Protocol
4068 )
4069
4070 def get_protocol_members(tp: type, /) -> typing.FrozenSet[str]:
4071 """Return the set of members defined in a Protocol.
4072
4073 Example::
4074
4075 >>> from typing_extensions import Protocol, get_protocol_members
4076 >>> class P(Protocol):
4077 ... def a(self) -> str: ...
4078 ... b: int
4079 >>> get_protocol_members(P)
4080 frozenset({'a', 'b'})
4081
4082 Raise a TypeError for arguments that are not Protocols.
4083 """
4084 if not is_protocol(tp):
4085 raise TypeError(f'{tp!r} is not a Protocol')
4086 if hasattr(tp, '__protocol_attrs__'):
4087 return frozenset(tp.__protocol_attrs__)
4088 return frozenset(_get_protocol_attrs(tp))
4089
4090
4091if hasattr(typing, "Doc"):
4092 Doc = typing.Doc
4093else:
4094 class Doc:
4095 """Define the documentation of a type annotation using ``Annotated``, to be
4096 used in class attributes, function and method parameters, return values,
4097 and variables.
4098
4099 The value should be a positional-only string literal to allow static tools
4100 like editors and documentation generators to use it.
4101
4102 This complements docstrings.
4103
4104 The string value passed is available in the attribute ``documentation``.
4105
4106 Example::
4107
4108 >>> from typing_extensions import Annotated, Doc
4109 >>> def hi(to: Annotated[str, Doc("Who to say hi to")]) -> None: ...
4110 """
4111 def __init__(self, documentation: str, /) -> None:
4112 self.documentation = documentation
4113
4114 def __repr__(self) -> str:
4115 return f"Doc({self.documentation!r})"
4116
4117 def __hash__(self) -> int:
4118 return hash(self.documentation)
4119
4120 def __eq__(self, other: object) -> bool:
4121 if not isinstance(other, Doc):
4122 return NotImplemented
4123 return self.documentation == other.documentation
4124
4125
4126_CapsuleType = getattr(_types, "CapsuleType", None)
4127
4128if _CapsuleType is None:
4129 try:
4130 import _socket
4131 except ImportError:
4132 pass
4133 else:
4134 _CAPI = getattr(_socket, "CAPI", None)
4135 if _CAPI is not None:
4136 _CapsuleType = type(_CAPI)
4137
4138if _CapsuleType is not None:
4139 CapsuleType = _CapsuleType
4140 __all__.append("CapsuleType")
4141
4142
4143# Using this convoluted approach so that this keeps working
4144# whether we end up using PEP 649 as written, PEP 749, or
4145# some other variation: in any case, inspect.get_annotations
4146# will continue to exist and will gain a `format` parameter.
4147_PEP_649_OR_749_IMPLEMENTED = (
4148 hasattr(inspect, 'get_annotations')
4149 and inspect.get_annotations.__kwdefaults__ is not None
4150 and "format" in inspect.get_annotations.__kwdefaults__
4151)
4152
4153
4154class Format(enum.IntEnum):
4155 VALUE = 1
4156 FORWARDREF = 2
4157 STRING = 3
4158
4159
4160if _PEP_649_OR_749_IMPLEMENTED:
4161 get_annotations = inspect.get_annotations
4162else:
4163 def get_annotations(obj, *, globals=None, locals=None, eval_str=False,
4164 format=Format.VALUE):
4165 """Compute the annotations dict for an object.
4166
4167 obj may be a callable, class, or module.
4168 Passing in an object of any other type raises TypeError.
4169
4170 Returns a dict. get_annotations() returns a new dict every time
4171 it's called; calling it twice on the same object will return two
4172 different but equivalent dicts.
4173
4174 This is a backport of `inspect.get_annotations`, which has been
4175 in the standard library since Python 3.10. See the standard library
4176 documentation for more:
4177
4178 https://docs.python.org/3/library/inspect.html#inspect.get_annotations
4179
4180 This backport adds the *format* argument introduced by PEP 649. The
4181 three formats supported are:
4182 * VALUE: the annotations are returned as-is. This is the default and
4183 it is compatible with the behavior on previous Python versions.
4184 * FORWARDREF: return annotations as-is if possible, but replace any
4185 undefined names with ForwardRef objects. The implementation proposed by
4186 PEP 649 relies on language changes that cannot be backported; the
4187 typing-extensions implementation simply returns the same result as VALUE.
4188 * STRING: return annotations as strings, in a format close to the original
4189 source. Again, this behavior cannot be replicated directly in a backport.
4190 As an approximation, typing-extensions retrieves the annotations under
4191 VALUE semantics and then stringifies them.
4192
4193 The purpose of this backport is to allow users who would like to use
4194 FORWARDREF or STRING semantics once PEP 649 is implemented, but who also
4195 want to support earlier Python versions, to simply write:
4196
4197 typing_extensions.get_annotations(obj, format=Format.FORWARDREF)
4198
4199 """
4200 format = Format(format)
4201
4202 if eval_str and format is not Format.VALUE:
4203 raise ValueError("eval_str=True is only supported with format=Format.VALUE")
4204
4205 if isinstance(obj, type):
4206 # class
4207 obj_dict = getattr(obj, '__dict__', None)
4208 if obj_dict and hasattr(obj_dict, 'get'):
4209 ann = obj_dict.get('__annotations__', None)
4210 if isinstance(ann, _types.GetSetDescriptorType):
4211 ann = None
4212 else:
4213 ann = None
4214
4215 obj_globals = None
4216 module_name = getattr(obj, '__module__', None)
4217 if module_name:
4218 module = sys.modules.get(module_name, None)
4219 if module:
4220 obj_globals = getattr(module, '__dict__', None)
4221 obj_locals = dict(vars(obj))
4222 unwrap = obj
4223 elif isinstance(obj, _types.ModuleType):
4224 # module
4225 ann = getattr(obj, '__annotations__', None)
4226 obj_globals = obj.__dict__
4227 obj_locals = None
4228 unwrap = None
4229 elif callable(obj):
4230 # this includes types.Function, types.BuiltinFunctionType,
4231 # types.BuiltinMethodType, functools.partial, functools.singledispatch,
4232 # "class funclike" from Lib/test/test_inspect... on and on it goes.
4233 ann = getattr(obj, '__annotations__', None)
4234 obj_globals = getattr(obj, '__globals__', None)
4235 obj_locals = None
4236 unwrap = obj
4237 elif hasattr(obj, '__annotations__'):
4238 ann = obj.__annotations__
4239 obj_globals = obj_locals = unwrap = None
4240 else:
4241 raise TypeError(f"{obj!r} is not a module, class, or callable.")
4242
4243 if ann is None:
4244 return {}
4245
4246 if not isinstance(ann, dict):
4247 raise ValueError(f"{obj!r}.__annotations__ is neither a dict nor None")
4248
4249 if not ann:
4250 return {}
4251
4252 if not eval_str:
4253 if format is Format.STRING:
4254 return {
4255 key: value if isinstance(value, str) else typing._type_repr(value)
4256 for key, value in ann.items()
4257 }
4258 return dict(ann)
4259
4260 if unwrap is not None:
4261 while True:
4262 if hasattr(unwrap, '__wrapped__'):
4263 unwrap = unwrap.__wrapped__
4264 continue
4265 if isinstance(unwrap, functools.partial):
4266 unwrap = unwrap.func
4267 continue
4268 break
4269 if hasattr(unwrap, "__globals__"):
4270 obj_globals = unwrap.__globals__
4271
4272 if globals is None:
4273 globals = obj_globals
4274 if locals is None:
4275 locals = obj_locals or {}
4276
4277 # "Inject" type parameters into the local namespace
4278 # (unless they are shadowed by assignments *in* the local namespace),
4279 # as a way of emulating annotation scopes when calling `eval()`
4280 if type_params := getattr(obj, "__type_params__", ()):
4281 locals = {param.__name__: param for param in type_params} | locals
4282
4283 return_value = {key:
4284 value if not isinstance(value, str) else eval(value, globals, locals)
4285 for key, value in ann.items() }
4286 return return_value
4287
4288
4289if hasattr(typing, "evaluate_forward_ref"):
4290 evaluate_forward_ref = typing.evaluate_forward_ref
4291else:
4292 # Implements annotationlib.ForwardRef.evaluate
4293 def _eval_with_owner(
4294 forward_ref, *, owner=None, globals=None, locals=None, type_params=None
4295 ):
4296 if forward_ref.__forward_evaluated__:
4297 return forward_ref.__forward_value__
4298 if getattr(forward_ref, "__cell__", None) is not None:
4299 try:
4300 value = forward_ref.__cell__.cell_contents
4301 except ValueError:
4302 pass
4303 else:
4304 forward_ref.__forward_evaluated__ = True
4305 forward_ref.__forward_value__ = value
4306 return value
4307 if owner is None:
4308 owner = getattr(forward_ref, "__owner__", None)
4309
4310 if (
4311 globals is None
4312 and getattr(forward_ref, "__forward_module__", None) is not None
4313 ):
4314 globals = getattr(
4315 sys.modules.get(forward_ref.__forward_module__, None), "__dict__", None
4316 )
4317 if globals is None:
4318 globals = getattr(forward_ref, "__globals__", None)
4319 if globals is None:
4320 if isinstance(owner, type):
4321 module_name = getattr(owner, "__module__", None)
4322 if module_name:
4323 module = sys.modules.get(module_name, None)
4324 if module:
4325 globals = getattr(module, "__dict__", None)
4326 elif isinstance(owner, _types.ModuleType):
4327 globals = getattr(owner, "__dict__", None)
4328 elif callable(owner):
4329 globals = getattr(owner, "__globals__", None)
4330
4331 # If we pass None to eval() below, the globals of this module are used.
4332 if globals is None:
4333 globals = {}
4334
4335 if locals is None:
4336 locals = {}
4337 if isinstance(owner, type):
4338 locals.update(vars(owner))
4339
4340 if type_params is None and owner is not None:
4341 # "Inject" type parameters into the local namespace
4342 # (unless they are shadowed by assignments *in* the local namespace),
4343 # as a way of emulating annotation scopes when calling `eval()`
4344 type_params = getattr(owner, "__type_params__", None)
4345
4346 # type parameters require some special handling,
4347 # as they exist in their own scope
4348 # but `eval()` does not have a dedicated parameter for that scope.
4349 # For classes, names in type parameter scopes should override
4350 # names in the global scope (which here are called `localns`!),
4351 # but should in turn be overridden by names in the class scope
4352 # (which here are called `globalns`!)
4353 if type_params is not None:
4354 globals = dict(globals)
4355 locals = dict(locals)
4356 for param in type_params:
4357 param_name = param.__name__
4358 if (
4359 _FORWARD_REF_HAS_CLASS and not forward_ref.__forward_is_class__
4360 ) or param_name not in globals:
4361 globals[param_name] = param
4362 locals.pop(param_name, None)
4363
4364 arg = forward_ref.__forward_arg__
4365 if arg.isidentifier() and not keyword.iskeyword(arg):
4366 if arg in locals:
4367 value = locals[arg]
4368 elif arg in globals:
4369 value = globals[arg]
4370 elif hasattr(builtins, arg):
4371 return getattr(builtins, arg)
4372 else:
4373 raise NameError(arg)
4374 else:
4375 code = forward_ref.__forward_code__
4376 value = eval(code, globals, locals)
4377 forward_ref.__forward_evaluated__ = True
4378 forward_ref.__forward_value__ = value
4379 return value
4380
4381 def _lax_type_check(
4382 value, msg, is_argument=True, *, module=None, allow_special_forms=False
4383 ):
4384 """
4385 A lax Python 3.11+ like version of typing._type_check
4386 """
4387 if hasattr(typing, "_type_convert"):
4388 if (
4389 sys.version_info >= (3, 10, 3)
4390 or (3, 9, 10) < sys.version_info[:3] < (3, 10)
4391 ):
4392 # allow_special_forms introduced later cpython/#30926 (bpo-46539)
4393 type_ = typing._type_convert(
4394 value,
4395 module=module,
4396 allow_special_forms=allow_special_forms,
4397 )
4398 # module was added with bpo-41249 before is_class (bpo-46539)
4399 elif "__forward_module__" in typing.ForwardRef.__slots__:
4400 type_ = typing._type_convert(value, module=module)
4401 else:
4402 type_ = typing._type_convert(value)
4403 else:
4404 if value is None:
4405 return type(None)
4406 if isinstance(value, str):
4407 return ForwardRef(value)
4408 type_ = value
4409 invalid_generic_forms = (Generic, Protocol)
4410 if not allow_special_forms:
4411 invalid_generic_forms += (ClassVar,)
4412 if is_argument:
4413 invalid_generic_forms += (Final,)
4414 if (
4415 isinstance(type_, typing._GenericAlias)
4416 and get_origin(type_) in invalid_generic_forms
4417 ):
4418 raise TypeError(f"{type_} is not valid as type argument") from None
4419 if type_ in (Any, LiteralString, NoReturn, Never, Self, TypeAlias):
4420 return type_
4421 if allow_special_forms and type_ in (ClassVar, Final):
4422 return type_
4423 if (
4424 isinstance(type_, (_SpecialForm, typing._SpecialForm))
4425 or type_ in (Generic, Protocol)
4426 ):
4427 raise TypeError(f"Plain {type_} is not valid as type argument") from None
4428 if type(type_) is tuple: # lax version with tuple instead of callable
4429 raise TypeError(f"{msg} Got {type_!r:.100}.")
4430 return type_
4431
4432 def evaluate_forward_ref(
4433 forward_ref,
4434 *,
4435 owner=None,
4436 globals=None,
4437 locals=None,
4438 type_params=None,
4439 format=Format.VALUE,
4440 _recursive_guard=frozenset(),
4441 ):
4442 """Evaluate a forward reference as a type hint.
4443
4444 This is similar to calling the ForwardRef.evaluate() method,
4445 but unlike that method, evaluate_forward_ref() also:
4446
4447 * Recursively evaluates forward references nested within the type hint.
4448 * Rejects certain objects that are not valid type hints.
4449 * Replaces type hints that evaluate to None with types.NoneType.
4450 * Supports the *FORWARDREF* and *STRING* formats.
4451
4452 *forward_ref* must be an instance of ForwardRef. *owner*, if given,
4453 should be the object that holds the annotations that the forward reference
4454 derived from, such as a module, class object, or function. It is used to
4455 infer the namespaces to use for looking up names. *globals* and *locals*
4456 can also be explicitly given to provide the global and local namespaces.
4457 *type_params* is a tuple of type parameters that are in scope when
4458 evaluating the forward reference. This parameter must be provided (though
4459 it may be an empty tuple) if *owner* is not given and the forward reference
4460 does not already have an owner set. *format* specifies the format of the
4461 annotation and is a member of the annotationlib.Format enum.
4462
4463 """
4464 if format == Format.STRING:
4465 return forward_ref.__forward_arg__
4466 if forward_ref.__forward_arg__ in _recursive_guard:
4467 return forward_ref
4468
4469 # Evaluate the forward reference
4470 try:
4471 value = _eval_with_owner(
4472 forward_ref,
4473 owner=owner,
4474 globals=globals,
4475 locals=locals,
4476 type_params=type_params,
4477 )
4478 except NameError:
4479 if format == Format.FORWARDREF:
4480 return forward_ref
4481 else:
4482 raise
4483
4484 msg = "Forward references must evaluate to types."
4485 if not _FORWARD_REF_HAS_CLASS:
4486 allow_special_forms = not forward_ref.__forward_is_argument__
4487 else:
4488 allow_special_forms = forward_ref.__forward_is_class__
4489 type_ = _lax_type_check(
4490 value,
4491 msg,
4492 is_argument=forward_ref.__forward_is_argument__,
4493 allow_special_forms=allow_special_forms,
4494 )
4495
4496 # Recursively evaluate the type
4497 if isinstance(type_, ForwardRef):
4498 if getattr(type_, "__forward_module__", True) is not None:
4499 globals = None
4500 return evaluate_forward_ref(
4501 type_,
4502 globals=globals,
4503 locals=locals,
4504 type_params=type_params, owner=owner,
4505 _recursive_guard=_recursive_guard, format=format
4506 )
4507 if sys.version_info < (3, 12, 5) and type_params:
4508 # Make use of type_params
4509 locals = dict(locals) if locals else {}
4510 for tvar in type_params:
4511 if tvar.__name__ not in locals: # lets not overwrite something present
4512 locals[tvar.__name__] = tvar
4513 if sys.version_info < (3, 9):
4514 return typing._eval_type(
4515 type_,
4516 globals,
4517 locals,
4518 )
4519 if sys.version_info < (3, 12, 5):
4520 return typing._eval_type(
4521 type_,
4522 globals,
4523 locals,
4524 recursive_guard=_recursive_guard | {forward_ref.__forward_arg__},
4525 )
4526 if sys.version_info < (3, 14):
4527 return typing._eval_type(
4528 type_,
4529 globals,
4530 locals,
4531 type_params,
4532 recursive_guard=_recursive_guard | {forward_ref.__forward_arg__},
4533 )
4534 return typing._eval_type(
4535 type_,
4536 globals,
4537 locals,
4538 type_params,
4539 recursive_guard=_recursive_guard | {forward_ref.__forward_arg__},
4540 format=format,
4541 owner=owner,
4542 )
4543
4544
4545# Aliases for items that have always been in typing.
4546# Explicitly assign these (rather than using `from typing import *` at the top),
4547# so that we get a CI error if one of these is deleted from typing.py
4548# in a future version of Python
4549AbstractSet = typing.AbstractSet
4550AnyStr = typing.AnyStr
4551BinaryIO = typing.BinaryIO
4552Callable = typing.Callable
4553Collection = typing.Collection
4554Container = typing.Container
4555Dict = typing.Dict
4556ForwardRef = typing.ForwardRef
4557FrozenSet = typing.FrozenSet
4558Generic = typing.Generic
4559Hashable = typing.Hashable
4560IO = typing.IO
4561ItemsView = typing.ItemsView
4562Iterable = typing.Iterable
4563Iterator = typing.Iterator
4564KeysView = typing.KeysView
4565List = typing.List
4566Mapping = typing.Mapping
4567MappingView = typing.MappingView
4568Match = typing.Match
4569MutableMapping = typing.MutableMapping
4570MutableSequence = typing.MutableSequence
4571MutableSet = typing.MutableSet
4572Optional = typing.Optional
4573Pattern = typing.Pattern
4574Reversible = typing.Reversible
4575Sequence = typing.Sequence
4576Set = typing.Set
4577Sized = typing.Sized
4578TextIO = typing.TextIO
4579Tuple = typing.Tuple
4580Union = typing.Union
4581ValuesView = typing.ValuesView
4582cast = typing.cast
4583no_type_check = typing.no_type_check
4584no_type_check_decorator = typing.no_type_check_decorator