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