Debian Codegraph @

src/typing_extensions.py

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