Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/typing_extensions.py: 36%
890 statements
« prev ^ index » next coverage.py v7.4.0, created at 2024-01-03 07:57 +0000
« prev ^ index » next coverage.py v7.4.0, created at 2024-01-03 07:57 +0000
1import abc
2import collections
3import collections.abc
4import functools
5import inspect
6import operator
7import sys
8import types as _types
9import typing
10import warnings
13__all__ = [
14 # Super-special typing primitives.
15 'Any',
16 'ClassVar',
17 'Concatenate',
18 'Final',
19 'LiteralString',
20 'ParamSpec',
21 'ParamSpecArgs',
22 'ParamSpecKwargs',
23 'Self',
24 'Type',
25 'TypeVar',
26 'TypeVarTuple',
27 'Unpack',
29 # ABCs (from collections.abc).
30 'Awaitable',
31 'AsyncIterator',
32 'AsyncIterable',
33 'Coroutine',
34 'AsyncGenerator',
35 'AsyncContextManager',
36 'ChainMap',
38 # Concrete collection types.
39 'ContextManager',
40 'Counter',
41 'Deque',
42 'DefaultDict',
43 'NamedTuple',
44 'OrderedDict',
45 'TypedDict',
47 # Structural checks, a.k.a. protocols.
48 'SupportsIndex',
50 # One-off things.
51 'Annotated',
52 'assert_never',
53 'assert_type',
54 'clear_overloads',
55 'dataclass_transform',
56 'deprecated',
57 'get_overloads',
58 'final',
59 'get_args',
60 'get_origin',
61 'get_type_hints',
62 'IntVar',
63 'is_typeddict',
64 'Literal',
65 'NewType',
66 'overload',
67 'override',
68 'Protocol',
69 'reveal_type',
70 'runtime',
71 'runtime_checkable',
72 'Text',
73 'TypeAlias',
74 'TypeGuard',
75 'TYPE_CHECKING',
76 'Never',
77 'NoReturn',
78 'Required',
79 'NotRequired',
80]
82# for backward compatibility
83PEP_560 = True
84GenericMeta = type
86# The functions below are modified copies of typing internal helpers.
87# They are needed by _ProtocolMeta and they provide support for PEP 646.
89_marker = object()
92def _check_generic(cls, parameters, elen=_marker):
93 """Check correct count for parameters of a generic cls (internal helper).
94 This gives a nice error message in case of count mismatch.
95 """
96 if not elen:
97 raise TypeError(f"{cls} is not a generic class")
98 if elen is _marker:
99 if not hasattr(cls, "__parameters__") or not cls.__parameters__:
100 raise TypeError(f"{cls} is not a generic class")
101 elen = len(cls.__parameters__)
102 alen = len(parameters)
103 if alen != elen:
104 if hasattr(cls, "__parameters__"):
105 parameters = [p for p in cls.__parameters__ if not _is_unpack(p)]
106 num_tv_tuples = sum(isinstance(p, TypeVarTuple) for p in parameters)
107 if (num_tv_tuples > 0) and (alen >= elen - num_tv_tuples):
108 return
109 raise TypeError(f"Too {'many' if alen > elen else 'few'} parameters for {cls};"
110 f" actual {alen}, expected {elen}")
113if sys.version_info >= (3, 10):
114 def _should_collect_from_parameters(t):
115 return isinstance(
116 t, (typing._GenericAlias, _types.GenericAlias, _types.UnionType)
117 )
118elif sys.version_info >= (3, 9):
119 def _should_collect_from_parameters(t):
120 return isinstance(t, (typing._GenericAlias, _types.GenericAlias))
121else:
122 def _should_collect_from_parameters(t):
123 return isinstance(t, typing._GenericAlias) and not t._special
126def _collect_type_vars(types, typevar_types=None):
127 """Collect all type variable contained in types in order of
128 first appearance (lexicographic order). For example::
130 _collect_type_vars((T, List[S, T])) == (T, S)
131 """
132 if typevar_types is None:
133 typevar_types = typing.TypeVar
134 tvars = []
135 for t in types:
136 if (
137 isinstance(t, typevar_types) and
138 t not in tvars and
139 not _is_unpack(t)
140 ):
141 tvars.append(t)
142 if _should_collect_from_parameters(t):
143 tvars.extend([t for t in t.__parameters__ if t not in tvars])
144 return tuple(tvars)
147NoReturn = typing.NoReturn
149# Some unconstrained type variables. These are used by the container types.
150# (These are not for export.)
151T = typing.TypeVar('T') # Any type.
152KT = typing.TypeVar('KT') # Key type.
153VT = typing.TypeVar('VT') # Value type.
154T_co = typing.TypeVar('T_co', covariant=True) # Any type covariant containers.
155T_contra = typing.TypeVar('T_contra', contravariant=True) # Ditto contravariant.
158if sys.version_info >= (3, 11):
159 from typing import Any
160else:
162 class _AnyMeta(type):
163 def __instancecheck__(self, obj):
164 if self is Any:
165 raise TypeError("typing_extensions.Any cannot be used with isinstance()")
166 return super().__instancecheck__(obj)
168 def __repr__(self):
169 if self is Any:
170 return "typing_extensions.Any"
171 return super().__repr__()
173 class Any(metaclass=_AnyMeta):
174 """Special type indicating an unconstrained type.
175 - Any is compatible with every type.
176 - Any assumed to have all methods.
177 - All values assumed to be instances of Any.
178 Note that all the above statements are true from the point of view of
179 static type checkers. At runtime, Any should not be used with instance
180 checks.
181 """
182 def __new__(cls, *args, **kwargs):
183 if cls is Any:
184 raise TypeError("Any cannot be instantiated")
185 return super().__new__(cls, *args, **kwargs)
188ClassVar = typing.ClassVar
190# On older versions of typing there is an internal class named "Final".
191# 3.8+
192if hasattr(typing, 'Final') and sys.version_info[:2] >= (3, 7):
193 Final = typing.Final
194# 3.7
195else:
196 class _FinalForm(typing._SpecialForm, _root=True):
198 def __repr__(self):
199 return 'typing_extensions.' + self._name
201 def __getitem__(self, parameters):
202 item = typing._type_check(parameters,
203 f'{self._name} accepts only a single type.')
204 return typing._GenericAlias(self, (item,))
206 Final = _FinalForm('Final',
207 doc="""A special typing construct to indicate that a name
208 cannot be re-assigned or overridden in a subclass.
209 For example:
211 MAX_SIZE: Final = 9000
212 MAX_SIZE += 1 # Error reported by type checker
214 class Connection:
215 TIMEOUT: Final[int] = 10
216 class FastConnector(Connection):
217 TIMEOUT = 1 # Error reported by type checker
219 There is no runtime checking of these properties.""")
221if sys.version_info >= (3, 11):
222 final = typing.final
223else:
224 # @final exists in 3.8+, but we backport it for all versions
225 # before 3.11 to keep support for the __final__ attribute.
226 # See https://bugs.python.org/issue46342
227 def final(f):
228 """This decorator can be used to indicate to type checkers that
229 the decorated method cannot be overridden, and decorated class
230 cannot be subclassed. For example:
232 class Base:
233 @final
234 def done(self) -> None:
235 ...
236 class Sub(Base):
237 def done(self) -> None: # Error reported by type checker
238 ...
239 @final
240 class Leaf:
241 ...
242 class Other(Leaf): # Error reported by type checker
243 ...
245 There is no runtime checking of these properties. The decorator
246 sets the ``__final__`` attribute to ``True`` on the decorated object
247 to allow runtime introspection.
248 """
249 try:
250 f.__final__ = True
251 except (AttributeError, TypeError):
252 # Skip the attribute silently if it is not writable.
253 # AttributeError happens if the object has __slots__ or a
254 # read-only property, TypeError if it's a builtin class.
255 pass
256 return f
259def IntVar(name):
260 return typing.TypeVar(name)
263# 3.8+:
264if hasattr(typing, 'Literal'):
265 Literal = typing.Literal
266# 3.7:
267else:
268 class _LiteralForm(typing._SpecialForm, _root=True):
270 def __repr__(self):
271 return 'typing_extensions.' + self._name
273 def __getitem__(self, parameters):
274 return typing._GenericAlias(self, parameters)
276 Literal = _LiteralForm('Literal',
277 doc="""A type that can be used to indicate to type checkers
278 that the corresponding value has a value literally equivalent
279 to the provided parameter. For example:
281 var: Literal[4] = 4
283 The type checker understands that 'var' is literally equal to
284 the value 4 and no other value.
286 Literal[...] cannot be subclassed. There is no runtime
287 checking verifying that the parameter is actually a value
288 instead of a type.""")
291_overload_dummy = typing._overload_dummy # noqa
294if hasattr(typing, "get_overloads"): # 3.11+
295 overload = typing.overload
296 get_overloads = typing.get_overloads
297 clear_overloads = typing.clear_overloads
298else:
299 # {module: {qualname: {firstlineno: func}}}
300 _overload_registry = collections.defaultdict(
301 functools.partial(collections.defaultdict, dict)
302 )
304 def overload(func):
305 """Decorator for overloaded functions/methods.
307 In a stub file, place two or more stub definitions for the same
308 function in a row, each decorated with @overload. For example:
310 @overload
311 def utf8(value: None) -> None: ...
312 @overload
313 def utf8(value: bytes) -> bytes: ...
314 @overload
315 def utf8(value: str) -> bytes: ...
317 In a non-stub file (i.e. a regular .py file), do the same but
318 follow it with an implementation. The implementation should *not*
319 be decorated with @overload. For example:
321 @overload
322 def utf8(value: None) -> None: ...
323 @overload
324 def utf8(value: bytes) -> bytes: ...
325 @overload
326 def utf8(value: str) -> bytes: ...
327 def utf8(value):
328 # implementation goes here
330 The overloads for a function can be retrieved at runtime using the
331 get_overloads() function.
332 """
333 # classmethod and staticmethod
334 f = getattr(func, "__func__", func)
335 try:
336 _overload_registry[f.__module__][f.__qualname__][
337 f.__code__.co_firstlineno
338 ] = func
339 except AttributeError:
340 # Not a normal function; ignore.
341 pass
342 return _overload_dummy
344 def get_overloads(func):
345 """Return all defined overloads for *func* as a sequence."""
346 # classmethod and staticmethod
347 f = getattr(func, "__func__", func)
348 if f.__module__ not in _overload_registry:
349 return []
350 mod_dict = _overload_registry[f.__module__]
351 if f.__qualname__ not in mod_dict:
352 return []
353 return list(mod_dict[f.__qualname__].values())
355 def clear_overloads():
356 """Clear all overloads in the registry."""
357 _overload_registry.clear()
360# This is not a real generic class. Don't use outside annotations.
361Type = typing.Type
363# Various ABCs mimicking those in collections.abc.
364# A few are simply re-exported for completeness.
367Awaitable = typing.Awaitable
368Coroutine = typing.Coroutine
369AsyncIterable = typing.AsyncIterable
370AsyncIterator = typing.AsyncIterator
371Deque = typing.Deque
372ContextManager = typing.ContextManager
373AsyncContextManager = typing.AsyncContextManager
374DefaultDict = typing.DefaultDict
376# 3.7.2+
377if hasattr(typing, 'OrderedDict'):
378 OrderedDict = typing.OrderedDict
379# 3.7.0-3.7.2
380else:
381 OrderedDict = typing._alias(collections.OrderedDict, (KT, VT))
383Counter = typing.Counter
384ChainMap = typing.ChainMap
385AsyncGenerator = typing.AsyncGenerator
386NewType = typing.NewType
387Text = typing.Text
388TYPE_CHECKING = typing.TYPE_CHECKING
391_PROTO_WHITELIST = ['Callable', 'Awaitable',
392 'Iterable', 'Iterator', 'AsyncIterable', 'AsyncIterator',
393 'Hashable', 'Sized', 'Container', 'Collection', 'Reversible',
394 'ContextManager', 'AsyncContextManager']
397def _get_protocol_attrs(cls):
398 attrs = set()
399 for base in cls.__mro__[:-1]: # without object
400 if base.__name__ in ('Protocol', 'Generic'):
401 continue
402 annotations = getattr(base, '__annotations__', {})
403 for attr in list(base.__dict__.keys()) + list(annotations.keys()):
404 if (not attr.startswith('_abc_') and attr not in (
405 '__abstractmethods__', '__annotations__', '__weakref__',
406 '_is_protocol', '_is_runtime_protocol', '__dict__',
407 '__args__', '__slots__',
408 '__next_in_mro__', '__parameters__', '__origin__',
409 '__orig_bases__', '__extra__', '__tree_hash__',
410 '__doc__', '__subclasshook__', '__init__', '__new__',
411 '__module__', '_MutableMapping__marker', '_gorg')):
412 attrs.add(attr)
413 return attrs
416def _is_callable_members_only(cls):
417 return all(callable(getattr(cls, attr, None)) for attr in _get_protocol_attrs(cls))
420def _maybe_adjust_parameters(cls):
421 """Helper function used in Protocol.__init_subclass__ and _TypedDictMeta.__new__.
423 The contents of this function are very similar
424 to logic found in typing.Generic.__init_subclass__
425 on the CPython main branch.
426 """
427 tvars = []
428 if '__orig_bases__' in cls.__dict__:
429 tvars = typing._collect_type_vars(cls.__orig_bases__)
430 # Look for Generic[T1, ..., Tn] or Protocol[T1, ..., Tn].
431 # If found, tvars must be a subset of it.
432 # If not found, tvars is it.
433 # Also check for and reject plain Generic,
434 # and reject multiple Generic[...] and/or Protocol[...].
435 gvars = None
436 for base in cls.__orig_bases__:
437 if (isinstance(base, typing._GenericAlias) and
438 base.__origin__ in (typing.Generic, Protocol)):
439 # for error messages
440 the_base = base.__origin__.__name__
441 if gvars is not None:
442 raise TypeError(
443 "Cannot inherit from Generic[...]"
444 " and/or Protocol[...] multiple types.")
445 gvars = base.__parameters__
446 if gvars is None:
447 gvars = tvars
448 else:
449 tvarset = set(tvars)
450 gvarset = set(gvars)
451 if not tvarset <= gvarset:
452 s_vars = ', '.join(str(t) for t in tvars if t not in gvarset)
453 s_args = ', '.join(str(g) for g in gvars)
454 raise TypeError(f"Some type variables ({s_vars}) are"
455 f" not listed in {the_base}[{s_args}]")
456 tvars = gvars
457 cls.__parameters__ = tuple(tvars)
460# 3.8+
461if hasattr(typing, 'Protocol'):
462 Protocol = typing.Protocol
463# 3.7
464else:
466 def _no_init(self, *args, **kwargs):
467 if type(self)._is_protocol:
468 raise TypeError('Protocols cannot be instantiated')
470 class _ProtocolMeta(abc.ABCMeta): # noqa: B024
471 # This metaclass is a bit unfortunate and exists only because of the lack
472 # of __instancehook__.
473 def __instancecheck__(cls, instance):
474 # We need this method for situations where attributes are
475 # assigned in __init__.
476 if ((not getattr(cls, '_is_protocol', False) or
477 _is_callable_members_only(cls)) and
478 issubclass(instance.__class__, cls)):
479 return True
480 if cls._is_protocol:
481 if all(hasattr(instance, attr) and
482 (not callable(getattr(cls, attr, None)) or
483 getattr(instance, attr) is not None)
484 for attr in _get_protocol_attrs(cls)):
485 return True
486 return super().__instancecheck__(instance)
488 class Protocol(metaclass=_ProtocolMeta):
489 # There is quite a lot of overlapping code with typing.Generic.
490 # Unfortunately it is hard to avoid this while these live in two different
491 # modules. The duplicated code will be removed when Protocol is moved to typing.
492 """Base class for protocol classes. Protocol classes are defined as::
494 class Proto(Protocol):
495 def meth(self) -> int:
496 ...
498 Such classes are primarily used with static type checkers that recognize
499 structural subtyping (static duck-typing), for example::
501 class C:
502 def meth(self) -> int:
503 return 0
505 def func(x: Proto) -> int:
506 return x.meth()
508 func(C()) # Passes static type check
510 See PEP 544 for details. Protocol classes decorated with
511 @typing_extensions.runtime act as simple-minded runtime protocol that checks
512 only the presence of given attributes, ignoring their type signatures.
514 Protocol classes can be generic, they are defined as::
516 class GenProto(Protocol[T]):
517 def meth(self) -> T:
518 ...
519 """
520 __slots__ = ()
521 _is_protocol = True
523 def __new__(cls, *args, **kwds):
524 if cls is Protocol:
525 raise TypeError("Type Protocol cannot be instantiated; "
526 "it can only be used as a base class")
527 return super().__new__(cls)
529 @typing._tp_cache
530 def __class_getitem__(cls, params):
531 if not isinstance(params, tuple):
532 params = (params,)
533 if not params and cls is not typing.Tuple:
534 raise TypeError(
535 f"Parameter list to {cls.__qualname__}[...] cannot be empty")
536 msg = "Parameters to generic types must be types."
537 params = tuple(typing._type_check(p, msg) for p in params) # noqa
538 if cls is Protocol:
539 # Generic can only be subscripted with unique type variables.
540 if not all(isinstance(p, typing.TypeVar) for p in params):
541 i = 0
542 while isinstance(params[i], typing.TypeVar):
543 i += 1
544 raise TypeError(
545 "Parameters to Protocol[...] must all be type variables."
546 f" Parameter {i + 1} is {params[i]}")
547 if len(set(params)) != len(params):
548 raise TypeError(
549 "Parameters to Protocol[...] must all be unique")
550 else:
551 # Subscripting a regular Generic subclass.
552 _check_generic(cls, params, len(cls.__parameters__))
553 return typing._GenericAlias(cls, params)
555 def __init_subclass__(cls, *args, **kwargs):
556 if '__orig_bases__' in cls.__dict__:
557 error = typing.Generic in cls.__orig_bases__
558 else:
559 error = typing.Generic in cls.__bases__
560 if error:
561 raise TypeError("Cannot inherit from plain Generic")
562 _maybe_adjust_parameters(cls)
564 # Determine if this is a protocol or a concrete subclass.
565 if not cls.__dict__.get('_is_protocol', None):
566 cls._is_protocol = any(b is Protocol for b in cls.__bases__)
568 # Set (or override) the protocol subclass hook.
569 def _proto_hook(other):
570 if not cls.__dict__.get('_is_protocol', None):
571 return NotImplemented
572 if not getattr(cls, '_is_runtime_protocol', False):
573 if sys._getframe(2).f_globals['__name__'] in ['abc', 'functools']:
574 return NotImplemented
575 raise TypeError("Instance and class checks can only be used with"
576 " @runtime protocols")
577 if not _is_callable_members_only(cls):
578 if sys._getframe(2).f_globals['__name__'] in ['abc', 'functools']:
579 return NotImplemented
580 raise TypeError("Protocols with non-method members"
581 " don't support issubclass()")
582 if not isinstance(other, type):
583 # Same error as for issubclass(1, int)
584 raise TypeError('issubclass() arg 1 must be a class')
585 for attr in _get_protocol_attrs(cls):
586 for base in other.__mro__:
587 if attr in base.__dict__:
588 if base.__dict__[attr] is None:
589 return NotImplemented
590 break
591 annotations = getattr(base, '__annotations__', {})
592 if (isinstance(annotations, typing.Mapping) and
593 attr in annotations and
594 isinstance(other, _ProtocolMeta) and
595 other._is_protocol):
596 break
597 else:
598 return NotImplemented
599 return True
600 if '__subclasshook__' not in cls.__dict__:
601 cls.__subclasshook__ = _proto_hook
603 # We have nothing more to do for non-protocols.
604 if not cls._is_protocol:
605 return
607 # Check consistency of bases.
608 for base in cls.__bases__:
609 if not (base in (object, typing.Generic) or
610 base.__module__ == 'collections.abc' and
611 base.__name__ in _PROTO_WHITELIST or
612 isinstance(base, _ProtocolMeta) and base._is_protocol):
613 raise TypeError('Protocols can only inherit from other'
614 f' protocols, got {repr(base)}')
615 cls.__init__ = _no_init
618# 3.8+
619if hasattr(typing, 'runtime_checkable'):
620 runtime_checkable = typing.runtime_checkable
621# 3.7
622else:
623 def runtime_checkable(cls):
624 """Mark a protocol class as a runtime protocol, so that it
625 can be used with isinstance() and issubclass(). Raise TypeError
626 if applied to a non-protocol class.
628 This allows a simple-minded structural check very similar to the
629 one-offs in collections.abc such as Hashable.
630 """
631 if not isinstance(cls, _ProtocolMeta) or not cls._is_protocol:
632 raise TypeError('@runtime_checkable can be only applied to protocol classes,'
633 f' got {cls!r}')
634 cls._is_runtime_protocol = True
635 return cls
638# Exists for backwards compatibility.
639runtime = runtime_checkable
642# 3.8+
643if hasattr(typing, 'SupportsIndex'):
644 SupportsIndex = typing.SupportsIndex
645# 3.7
646else:
647 @runtime_checkable
648 class SupportsIndex(Protocol):
649 __slots__ = ()
651 @abc.abstractmethod
652 def __index__(self) -> int:
653 pass
656if hasattr(typing, "Required"):
657 # The standard library TypedDict in Python 3.8 does not store runtime information
658 # about which (if any) keys are optional. See https://bugs.python.org/issue38834
659 # The standard library TypedDict in Python 3.9.0/1 does not honour the "total"
660 # keyword with old-style TypedDict(). See https://bugs.python.org/issue42059
661 # The standard library TypedDict below Python 3.11 does not store runtime
662 # information about optional and required keys when using Required or NotRequired.
663 # Generic TypedDicts are also impossible using typing.TypedDict on Python <3.11.
664 TypedDict = typing.TypedDict
665 _TypedDictMeta = typing._TypedDictMeta
666 is_typeddict = typing.is_typeddict
667else:
668 def _check_fails(cls, other):
669 try:
670 if sys._getframe(1).f_globals['__name__'] not in ['abc',
671 'functools',
672 'typing']:
673 # Typed dicts are only for static structural subtyping.
674 raise TypeError('TypedDict does not support instance and class checks')
675 except (AttributeError, ValueError):
676 pass
677 return False
679 def _dict_new(*args, **kwargs):
680 if not args:
681 raise TypeError('TypedDict.__new__(): not enough arguments')
682 _, args = args[0], args[1:] # allow the "cls" keyword be passed
683 return dict(*args, **kwargs)
685 _dict_new.__text_signature__ = '($cls, _typename, _fields=None, /, **kwargs)'
687 def _typeddict_new(*args, total=True, **kwargs):
688 if not args:
689 raise TypeError('TypedDict.__new__(): not enough arguments')
690 _, args = args[0], args[1:] # allow the "cls" keyword be passed
691 if args:
692 typename, args = args[0], args[1:] # allow the "_typename" keyword be passed
693 elif '_typename' in kwargs:
694 typename = kwargs.pop('_typename')
695 import warnings
696 warnings.warn("Passing '_typename' as keyword argument is deprecated",
697 DeprecationWarning, stacklevel=2)
698 else:
699 raise TypeError("TypedDict.__new__() missing 1 required positional "
700 "argument: '_typename'")
701 if args:
702 try:
703 fields, = args # allow the "_fields" keyword be passed
704 except ValueError:
705 raise TypeError('TypedDict.__new__() takes from 2 to 3 '
706 f'positional arguments but {len(args) + 2} '
707 'were given')
708 elif '_fields' in kwargs and len(kwargs) == 1:
709 fields = kwargs.pop('_fields')
710 import warnings
711 warnings.warn("Passing '_fields' as keyword argument is deprecated",
712 DeprecationWarning, stacklevel=2)
713 else:
714 fields = None
716 if fields is None:
717 fields = kwargs
718 elif kwargs:
719 raise TypeError("TypedDict takes either a dict or keyword arguments,"
720 " but not both")
722 ns = {'__annotations__': dict(fields)}
723 try:
724 # Setting correct module is necessary to make typed dict classes pickleable.
725 ns['__module__'] = sys._getframe(1).f_globals.get('__name__', '__main__')
726 except (AttributeError, ValueError):
727 pass
729 return _TypedDictMeta(typename, (), ns, total=total)
731 _typeddict_new.__text_signature__ = ('($cls, _typename, _fields=None,'
732 ' /, *, total=True, **kwargs)')
734 _TAKES_MODULE = "module" in inspect.signature(typing._type_check).parameters
736 class _TypedDictMeta(type):
737 def __init__(cls, name, bases, ns, total=True):
738 super().__init__(name, bases, ns)
740 def __new__(cls, name, bases, ns, total=True):
741 # Create new typed dict class object.
742 # This method is called directly when TypedDict is subclassed,
743 # or via _typeddict_new when TypedDict is instantiated. This way
744 # TypedDict supports all three syntaxes described in its docstring.
745 # Subclasses and instances of TypedDict return actual dictionaries
746 # via _dict_new.
747 ns['__new__'] = _typeddict_new if name == 'TypedDict' else _dict_new
748 # Don't insert typing.Generic into __bases__ here,
749 # or Generic.__init_subclass__ will raise TypeError
750 # in the super().__new__() call.
751 # Instead, monkey-patch __bases__ onto the class after it's been created.
752 tp_dict = super().__new__(cls, name, (dict,), ns)
754 if any(issubclass(base, typing.Generic) for base in bases):
755 tp_dict.__bases__ = (typing.Generic, dict)
756 _maybe_adjust_parameters(tp_dict)
758 annotations = {}
759 own_annotations = ns.get('__annotations__', {})
760 msg = "TypedDict('Name', {f0: t0, f1: t1, ...}); each t must be a type"
761 kwds = {"module": tp_dict.__module__} if _TAKES_MODULE else {}
762 own_annotations = {
763 n: typing._type_check(tp, msg, **kwds)
764 for n, tp in own_annotations.items()
765 }
766 required_keys = set()
767 optional_keys = set()
769 for base in bases:
770 annotations.update(base.__dict__.get('__annotations__', {}))
771 required_keys.update(base.__dict__.get('__required_keys__', ()))
772 optional_keys.update(base.__dict__.get('__optional_keys__', ()))
774 annotations.update(own_annotations)
775 for annotation_key, annotation_type in own_annotations.items():
776 annotation_origin = get_origin(annotation_type)
777 if annotation_origin is Annotated:
778 annotation_args = get_args(annotation_type)
779 if annotation_args:
780 annotation_type = annotation_args[0]
781 annotation_origin = get_origin(annotation_type)
783 if annotation_origin is Required:
784 required_keys.add(annotation_key)
785 elif annotation_origin is NotRequired:
786 optional_keys.add(annotation_key)
787 elif total:
788 required_keys.add(annotation_key)
789 else:
790 optional_keys.add(annotation_key)
792 tp_dict.__annotations__ = annotations
793 tp_dict.__required_keys__ = frozenset(required_keys)
794 tp_dict.__optional_keys__ = frozenset(optional_keys)
795 if not hasattr(tp_dict, '__total__'):
796 tp_dict.__total__ = total
797 return tp_dict
799 __instancecheck__ = __subclasscheck__ = _check_fails
801 TypedDict = _TypedDictMeta('TypedDict', (dict,), {})
802 TypedDict.__module__ = __name__
803 TypedDict.__doc__ = \
804 """A simple typed name space. At runtime it is equivalent to a plain dict.
806 TypedDict creates a dictionary type that expects all of its
807 instances to have a certain set of keys, with each key
808 associated with a value of a consistent type. This expectation
809 is not checked at runtime but is only enforced by type checkers.
810 Usage::
812 class Point2D(TypedDict):
813 x: int
814 y: int
815 label: str
817 a: Point2D = {'x': 1, 'y': 2, 'label': 'good'} # OK
818 b: Point2D = {'z': 3, 'label': 'bad'} # Fails type check
820 assert Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first')
822 The type info can be accessed via the Point2D.__annotations__ dict, and
823 the Point2D.__required_keys__ and Point2D.__optional_keys__ frozensets.
824 TypedDict supports two additional equivalent forms::
826 Point2D = TypedDict('Point2D', x=int, y=int, label=str)
827 Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str})
829 The class syntax is only supported in Python 3.6+, while two other
830 syntax forms work for Python 2.7 and 3.2+
831 """
833 if hasattr(typing, "_TypedDictMeta"):
834 _TYPEDDICT_TYPES = (typing._TypedDictMeta, _TypedDictMeta)
835 else:
836 _TYPEDDICT_TYPES = (_TypedDictMeta,)
838 def is_typeddict(tp):
839 """Check if an annotation is a TypedDict class
841 For example::
842 class Film(TypedDict):
843 title: str
844 year: int
846 is_typeddict(Film) # => True
847 is_typeddict(Union[list, str]) # => False
848 """
849 return isinstance(tp, tuple(_TYPEDDICT_TYPES))
852if hasattr(typing, "assert_type"):
853 assert_type = typing.assert_type
855else:
856 def assert_type(__val, __typ):
857 """Assert (to the type checker) that the value is of the given type.
859 When the type checker encounters a call to assert_type(), it
860 emits an error if the value is not of the specified type::
862 def greet(name: str) -> None:
863 assert_type(name, str) # ok
864 assert_type(name, int) # type checker error
866 At runtime this returns the first argument unchanged and otherwise
867 does nothing.
868 """
869 return __val
872if hasattr(typing, "Required"):
873 get_type_hints = typing.get_type_hints
874else:
875 import functools
876 import types
878 # replaces _strip_annotations()
879 def _strip_extras(t):
880 """Strips Annotated, Required and NotRequired from a given type."""
881 if isinstance(t, _AnnotatedAlias):
882 return _strip_extras(t.__origin__)
883 if hasattr(t, "__origin__") and t.__origin__ in (Required, NotRequired):
884 return _strip_extras(t.__args__[0])
885 if isinstance(t, typing._GenericAlias):
886 stripped_args = tuple(_strip_extras(a) for a in t.__args__)
887 if stripped_args == t.__args__:
888 return t
889 return t.copy_with(stripped_args)
890 if hasattr(types, "GenericAlias") and isinstance(t, types.GenericAlias):
891 stripped_args = tuple(_strip_extras(a) for a in t.__args__)
892 if stripped_args == t.__args__:
893 return t
894 return types.GenericAlias(t.__origin__, stripped_args)
895 if hasattr(types, "UnionType") and isinstance(t, types.UnionType):
896 stripped_args = tuple(_strip_extras(a) for a in t.__args__)
897 if stripped_args == t.__args__:
898 return t
899 return functools.reduce(operator.or_, stripped_args)
901 return t
903 def get_type_hints(obj, globalns=None, localns=None, include_extras=False):
904 """Return type hints for an object.
906 This is often the same as obj.__annotations__, but it handles
907 forward references encoded as string literals, adds Optional[t] if a
908 default value equal to None is set and recursively replaces all
909 'Annotated[T, ...]', 'Required[T]' or 'NotRequired[T]' with 'T'
910 (unless 'include_extras=True').
912 The argument may be a module, class, method, or function. The annotations
913 are returned as a dictionary. For classes, annotations include also
914 inherited members.
916 TypeError is raised if the argument is not of a type that can contain
917 annotations, and an empty dictionary is returned if no annotations are
918 present.
920 BEWARE -- the behavior of globalns and localns is counterintuitive
921 (unless you are familiar with how eval() and exec() work). The
922 search order is locals first, then globals.
924 - If no dict arguments are passed, an attempt is made to use the
925 globals from obj (or the respective module's globals for classes),
926 and these are also used as the locals. If the object does not appear
927 to have globals, an empty dictionary is used.
929 - If one dict argument is passed, it is used for both globals and
930 locals.
932 - If two dict arguments are passed, they specify globals and
933 locals, respectively.
934 """
935 if hasattr(typing, "Annotated"):
936 hint = typing.get_type_hints(
937 obj, globalns=globalns, localns=localns, include_extras=True
938 )
939 else:
940 hint = typing.get_type_hints(obj, globalns=globalns, localns=localns)
941 if include_extras:
942 return hint
943 return {k: _strip_extras(t) for k, t in hint.items()}
946# Python 3.9+ has PEP 593 (Annotated)
947if hasattr(typing, 'Annotated'):
948 Annotated = typing.Annotated
949 # Not exported and not a public API, but needed for get_origin() and get_args()
950 # to work.
951 _AnnotatedAlias = typing._AnnotatedAlias
952# 3.7-3.8
953else:
954 class _AnnotatedAlias(typing._GenericAlias, _root=True):
955 """Runtime representation of an annotated type.
957 At its core 'Annotated[t, dec1, dec2, ...]' is an alias for the type 't'
958 with extra annotations. The alias behaves like a normal typing alias,
959 instantiating is the same as instantiating the underlying type, binding
960 it to types is also the same.
961 """
962 def __init__(self, origin, metadata):
963 if isinstance(origin, _AnnotatedAlias):
964 metadata = origin.__metadata__ + metadata
965 origin = origin.__origin__
966 super().__init__(origin, origin)
967 self.__metadata__ = metadata
969 def copy_with(self, params):
970 assert len(params) == 1
971 new_type = params[0]
972 return _AnnotatedAlias(new_type, self.__metadata__)
974 def __repr__(self):
975 return (f"typing_extensions.Annotated[{typing._type_repr(self.__origin__)}, "
976 f"{', '.join(repr(a) for a in self.__metadata__)}]")
978 def __reduce__(self):
979 return operator.getitem, (
980 Annotated, (self.__origin__,) + self.__metadata__
981 )
983 def __eq__(self, other):
984 if not isinstance(other, _AnnotatedAlias):
985 return NotImplemented
986 if self.__origin__ != other.__origin__:
987 return False
988 return self.__metadata__ == other.__metadata__
990 def __hash__(self):
991 return hash((self.__origin__, self.__metadata__))
993 class Annotated:
994 """Add context specific metadata to a type.
996 Example: Annotated[int, runtime_check.Unsigned] indicates to the
997 hypothetical runtime_check module that this type is an unsigned int.
998 Every other consumer of this type can ignore this metadata and treat
999 this type as int.
1001 The first argument to Annotated must be a valid type (and will be in
1002 the __origin__ field), the remaining arguments are kept as a tuple in
1003 the __extra__ field.
1005 Details:
1007 - It's an error to call `Annotated` with less than two arguments.
1008 - Nested Annotated are flattened::
1010 Annotated[Annotated[T, Ann1, Ann2], Ann3] == Annotated[T, Ann1, Ann2, Ann3]
1012 - Instantiating an annotated type is equivalent to instantiating the
1013 underlying type::
1015 Annotated[C, Ann1](5) == C(5)
1017 - Annotated can be used as a generic type alias::
1019 Optimized = Annotated[T, runtime.Optimize()]
1020 Optimized[int] == Annotated[int, runtime.Optimize()]
1022 OptimizedList = Annotated[List[T], runtime.Optimize()]
1023 OptimizedList[int] == Annotated[List[int], runtime.Optimize()]
1024 """
1026 __slots__ = ()
1028 def __new__(cls, *args, **kwargs):
1029 raise TypeError("Type Annotated cannot be instantiated.")
1031 @typing._tp_cache
1032 def __class_getitem__(cls, params):
1033 if not isinstance(params, tuple) or len(params) < 2:
1034 raise TypeError("Annotated[...] should be used "
1035 "with at least two arguments (a type and an "
1036 "annotation).")
1037 allowed_special_forms = (ClassVar, Final)
1038 if get_origin(params[0]) in allowed_special_forms:
1039 origin = params[0]
1040 else:
1041 msg = "Annotated[t, ...]: t must be a type."
1042 origin = typing._type_check(params[0], msg)
1043 metadata = tuple(params[1:])
1044 return _AnnotatedAlias(origin, metadata)
1046 def __init_subclass__(cls, *args, **kwargs):
1047 raise TypeError(
1048 f"Cannot subclass {cls.__module__}.Annotated"
1049 )
1051# Python 3.8 has get_origin() and get_args() but those implementations aren't
1052# Annotated-aware, so we can't use those. Python 3.9's versions don't support
1053# ParamSpecArgs and ParamSpecKwargs, so only Python 3.10's versions will do.
1054if sys.version_info[:2] >= (3, 10):
1055 get_origin = typing.get_origin
1056 get_args = typing.get_args
1057# 3.7-3.9
1058else:
1059 try:
1060 # 3.9+
1061 from typing import _BaseGenericAlias
1062 except ImportError:
1063 _BaseGenericAlias = typing._GenericAlias
1064 try:
1065 # 3.9+
1066 from typing import GenericAlias as _typing_GenericAlias
1067 except ImportError:
1068 _typing_GenericAlias = typing._GenericAlias
1070 def get_origin(tp):
1071 """Get the unsubscripted version of a type.
1073 This supports generic types, Callable, Tuple, Union, Literal, Final, ClassVar
1074 and Annotated. Return None for unsupported types. Examples::
1076 get_origin(Literal[42]) is Literal
1077 get_origin(int) is None
1078 get_origin(ClassVar[int]) is ClassVar
1079 get_origin(Generic) is Generic
1080 get_origin(Generic[T]) is Generic
1081 get_origin(Union[T, int]) is Union
1082 get_origin(List[Tuple[T, T]][int]) == list
1083 get_origin(P.args) is P
1084 """
1085 if isinstance(tp, _AnnotatedAlias):
1086 return Annotated
1087 if isinstance(tp, (typing._GenericAlias, _typing_GenericAlias, _BaseGenericAlias,
1088 ParamSpecArgs, ParamSpecKwargs)):
1089 return tp.__origin__
1090 if tp is typing.Generic:
1091 return typing.Generic
1092 return None
1094 def get_args(tp):
1095 """Get type arguments with all substitutions performed.
1097 For unions, basic simplifications used by Union constructor are performed.
1098 Examples::
1099 get_args(Dict[str, int]) == (str, int)
1100 get_args(int) == ()
1101 get_args(Union[int, Union[T, int], str][int]) == (int, str)
1102 get_args(Union[int, Tuple[T, int]][str]) == (int, Tuple[str, int])
1103 get_args(Callable[[], T][int]) == ([], int)
1104 """
1105 if isinstance(tp, _AnnotatedAlias):
1106 return (tp.__origin__,) + tp.__metadata__
1107 if isinstance(tp, (typing._GenericAlias, _typing_GenericAlias)):
1108 if getattr(tp, "_special", False):
1109 return ()
1110 res = tp.__args__
1111 if get_origin(tp) is collections.abc.Callable and res[0] is not Ellipsis:
1112 res = (list(res[:-1]), res[-1])
1113 return res
1114 return ()
1117# 3.10+
1118if hasattr(typing, 'TypeAlias'):
1119 TypeAlias = typing.TypeAlias
1120# 3.9
1121elif sys.version_info[:2] >= (3, 9):
1122 class _TypeAliasForm(typing._SpecialForm, _root=True):
1123 def __repr__(self):
1124 return 'typing_extensions.' + self._name
1126 @_TypeAliasForm
1127 def TypeAlias(self, parameters):
1128 """Special marker indicating that an assignment should
1129 be recognized as a proper type alias definition by type
1130 checkers.
1132 For example::
1134 Predicate: TypeAlias = Callable[..., bool]
1136 It's invalid when used anywhere except as in the example above.
1137 """
1138 raise TypeError(f"{self} is not subscriptable")
1139# 3.7-3.8
1140else:
1141 class _TypeAliasForm(typing._SpecialForm, _root=True):
1142 def __repr__(self):
1143 return 'typing_extensions.' + self._name
1145 TypeAlias = _TypeAliasForm('TypeAlias',
1146 doc="""Special marker indicating that an assignment should
1147 be recognized as a proper type alias definition by type
1148 checkers.
1150 For example::
1152 Predicate: TypeAlias = Callable[..., bool]
1154 It's invalid when used anywhere except as in the example
1155 above.""")
1158class _DefaultMixin:
1159 """Mixin for TypeVarLike defaults."""
1161 __slots__ = ()
1163 def __init__(self, default):
1164 if isinstance(default, (tuple, list)):
1165 self.__default__ = tuple((typing._type_check(d, "Default must be a type")
1166 for d in default))
1167 elif default != _marker:
1168 self.__default__ = typing._type_check(default, "Default must be a type")
1169 else:
1170 self.__default__ = None
1173# Add default and infer_variance parameters from PEP 696 and 695
1174class TypeVar(typing.TypeVar, _DefaultMixin, _root=True):
1175 """Type variable."""
1177 __module__ = 'typing'
1179 def __init__(self, name, *constraints, bound=None,
1180 covariant=False, contravariant=False,
1181 default=_marker, infer_variance=False):
1182 super().__init__(name, *constraints, bound=bound, covariant=covariant,
1183 contravariant=contravariant)
1184 _DefaultMixin.__init__(self, default)
1185 self.__infer_variance__ = infer_variance
1187 # for pickling:
1188 try:
1189 def_mod = sys._getframe(1).f_globals.get('__name__', '__main__')
1190 except (AttributeError, ValueError):
1191 def_mod = None
1192 if def_mod != 'typing_extensions':
1193 self.__module__ = def_mod
1196# Python 3.10+ has PEP 612
1197if hasattr(typing, 'ParamSpecArgs'):
1198 ParamSpecArgs = typing.ParamSpecArgs
1199 ParamSpecKwargs = typing.ParamSpecKwargs
1200# 3.7-3.9
1201else:
1202 class _Immutable:
1203 """Mixin to indicate that object should not be copied."""
1204 __slots__ = ()
1206 def __copy__(self):
1207 return self
1209 def __deepcopy__(self, memo):
1210 return self
1212 class ParamSpecArgs(_Immutable):
1213 """The args for a ParamSpec object.
1215 Given a ParamSpec object P, P.args is an instance of ParamSpecArgs.
1217 ParamSpecArgs objects have a reference back to their ParamSpec:
1219 P.args.__origin__ is P
1221 This type is meant for runtime introspection and has no special meaning to
1222 static type checkers.
1223 """
1224 def __init__(self, origin):
1225 self.__origin__ = origin
1227 def __repr__(self):
1228 return f"{self.__origin__.__name__}.args"
1230 def __eq__(self, other):
1231 if not isinstance(other, ParamSpecArgs):
1232 return NotImplemented
1233 return self.__origin__ == other.__origin__
1235 class ParamSpecKwargs(_Immutable):
1236 """The kwargs for a ParamSpec object.
1238 Given a ParamSpec object P, P.kwargs is an instance of ParamSpecKwargs.
1240 ParamSpecKwargs objects have a reference back to their ParamSpec:
1242 P.kwargs.__origin__ is P
1244 This type is meant for runtime introspection and has no special meaning to
1245 static type checkers.
1246 """
1247 def __init__(self, origin):
1248 self.__origin__ = origin
1250 def __repr__(self):
1251 return f"{self.__origin__.__name__}.kwargs"
1253 def __eq__(self, other):
1254 if not isinstance(other, ParamSpecKwargs):
1255 return NotImplemented
1256 return self.__origin__ == other.__origin__
1258# 3.10+
1259if hasattr(typing, 'ParamSpec'):
1261 # Add default Parameter - PEP 696
1262 class ParamSpec(typing.ParamSpec, _DefaultMixin, _root=True):
1263 """Parameter specification variable."""
1265 __module__ = 'typing'
1267 def __init__(self, name, *, bound=None, covariant=False, contravariant=False,
1268 default=_marker):
1269 super().__init__(name, bound=bound, covariant=covariant,
1270 contravariant=contravariant)
1271 _DefaultMixin.__init__(self, default)
1273 # for pickling:
1274 try:
1275 def_mod = sys._getframe(1).f_globals.get('__name__', '__main__')
1276 except (AttributeError, ValueError):
1277 def_mod = None
1278 if def_mod != 'typing_extensions':
1279 self.__module__ = def_mod
1281# 3.7-3.9
1282else:
1284 # Inherits from list as a workaround for Callable checks in Python < 3.9.2.
1285 class ParamSpec(list, _DefaultMixin):
1286 """Parameter specification variable.
1288 Usage::
1290 P = ParamSpec('P')
1292 Parameter specification variables exist primarily for the benefit of static
1293 type checkers. They are used to forward the parameter types of one
1294 callable to another callable, a pattern commonly found in higher order
1295 functions and decorators. They are only valid when used in ``Concatenate``,
1296 or s the first argument to ``Callable``. In Python 3.10 and higher,
1297 they are also supported in user-defined Generics at runtime.
1298 See class Generic for more information on generic types. An
1299 example for annotating a decorator::
1301 T = TypeVar('T')
1302 P = ParamSpec('P')
1304 def add_logging(f: Callable[P, T]) -> Callable[P, T]:
1305 '''A type-safe decorator to add logging to a function.'''
1306 def inner(*args: P.args, **kwargs: P.kwargs) -> T:
1307 logging.info(f'{f.__name__} was called')
1308 return f(*args, **kwargs)
1309 return inner
1311 @add_logging
1312 def add_two(x: float, y: float) -> float:
1313 '''Add two numbers together.'''
1314 return x + y
1316 Parameter specification variables defined with covariant=True or
1317 contravariant=True can be used to declare covariant or contravariant
1318 generic types. These keyword arguments are valid, but their actual semantics
1319 are yet to be decided. See PEP 612 for details.
1321 Parameter specification variables can be introspected. e.g.:
1323 P.__name__ == 'T'
1324 P.__bound__ == None
1325 P.__covariant__ == False
1326 P.__contravariant__ == False
1328 Note that only parameter specification variables defined in global scope can
1329 be pickled.
1330 """
1332 # Trick Generic __parameters__.
1333 __class__ = typing.TypeVar
1335 @property
1336 def args(self):
1337 return ParamSpecArgs(self)
1339 @property
1340 def kwargs(self):
1341 return ParamSpecKwargs(self)
1343 def __init__(self, name, *, bound=None, covariant=False, contravariant=False,
1344 default=_marker):
1345 super().__init__([self])
1346 self.__name__ = name
1347 self.__covariant__ = bool(covariant)
1348 self.__contravariant__ = bool(contravariant)
1349 if bound:
1350 self.__bound__ = typing._type_check(bound, 'Bound must be a type.')
1351 else:
1352 self.__bound__ = None
1353 _DefaultMixin.__init__(self, default)
1355 # for pickling:
1356 try:
1357 def_mod = sys._getframe(1).f_globals.get('__name__', '__main__')
1358 except (AttributeError, ValueError):
1359 def_mod = None
1360 if def_mod != 'typing_extensions':
1361 self.__module__ = def_mod
1363 def __repr__(self):
1364 if self.__covariant__:
1365 prefix = '+'
1366 elif self.__contravariant__:
1367 prefix = '-'
1368 else:
1369 prefix = '~'
1370 return prefix + self.__name__
1372 def __hash__(self):
1373 return object.__hash__(self)
1375 def __eq__(self, other):
1376 return self is other
1378 def __reduce__(self):
1379 return self.__name__
1381 # Hack to get typing._type_check to pass.
1382 def __call__(self, *args, **kwargs):
1383 pass
1386# 3.7-3.9
1387if not hasattr(typing, 'Concatenate'):
1388 # Inherits from list as a workaround for Callable checks in Python < 3.9.2.
1389 class _ConcatenateGenericAlias(list):
1391 # Trick Generic into looking into this for __parameters__.
1392 __class__ = typing._GenericAlias
1394 # Flag in 3.8.
1395 _special = False
1397 def __init__(self, origin, args):
1398 super().__init__(args)
1399 self.__origin__ = origin
1400 self.__args__ = args
1402 def __repr__(self):
1403 _type_repr = typing._type_repr
1404 return (f'{_type_repr(self.__origin__)}'
1405 f'[{", ".join(_type_repr(arg) for arg in self.__args__)}]')
1407 def __hash__(self):
1408 return hash((self.__origin__, self.__args__))
1410 # Hack to get typing._type_check to pass in Generic.
1411 def __call__(self, *args, **kwargs):
1412 pass
1414 @property
1415 def __parameters__(self):
1416 return tuple(
1417 tp for tp in self.__args__ if isinstance(tp, (typing.TypeVar, ParamSpec))
1418 )
1421# 3.7-3.9
1422@typing._tp_cache
1423def _concatenate_getitem(self, parameters):
1424 if parameters == ():
1425 raise TypeError("Cannot take a Concatenate of no types.")
1426 if not isinstance(parameters, tuple):
1427 parameters = (parameters,)
1428 if not isinstance(parameters[-1], ParamSpec):
1429 raise TypeError("The last parameter to Concatenate should be a "
1430 "ParamSpec variable.")
1431 msg = "Concatenate[arg, ...]: each arg must be a type."
1432 parameters = tuple(typing._type_check(p, msg) for p in parameters)
1433 return _ConcatenateGenericAlias(self, parameters)
1436# 3.10+
1437if hasattr(typing, 'Concatenate'):
1438 Concatenate = typing.Concatenate
1439 _ConcatenateGenericAlias = typing._ConcatenateGenericAlias # noqa
1440# 3.9
1441elif sys.version_info[:2] >= (3, 9):
1442 @_TypeAliasForm
1443 def Concatenate(self, parameters):
1444 """Used in conjunction with ``ParamSpec`` and ``Callable`` to represent a
1445 higher order function which adds, removes or transforms parameters of a
1446 callable.
1448 For example::
1450 Callable[Concatenate[int, P], int]
1452 See PEP 612 for detailed information.
1453 """
1454 return _concatenate_getitem(self, parameters)
1455# 3.7-8
1456else:
1457 class _ConcatenateForm(typing._SpecialForm, _root=True):
1458 def __repr__(self):
1459 return 'typing_extensions.' + self._name
1461 def __getitem__(self, parameters):
1462 return _concatenate_getitem(self, parameters)
1464 Concatenate = _ConcatenateForm(
1465 'Concatenate',
1466 doc="""Used in conjunction with ``ParamSpec`` and ``Callable`` to represent a
1467 higher order function which adds, removes or transforms parameters of a
1468 callable.
1470 For example::
1472 Callable[Concatenate[int, P], int]
1474 See PEP 612 for detailed information.
1475 """)
1477# 3.10+
1478if hasattr(typing, 'TypeGuard'):
1479 TypeGuard = typing.TypeGuard
1480# 3.9
1481elif sys.version_info[:2] >= (3, 9):
1482 class _TypeGuardForm(typing._SpecialForm, _root=True):
1483 def __repr__(self):
1484 return 'typing_extensions.' + self._name
1486 @_TypeGuardForm
1487 def TypeGuard(self, parameters):
1488 """Special typing form used to annotate the return type of a user-defined
1489 type guard function. ``TypeGuard`` only accepts a single type argument.
1490 At runtime, functions marked this way should return a boolean.
1492 ``TypeGuard`` aims to benefit *type narrowing* -- a technique used by static
1493 type checkers to determine a more precise type of an expression within a
1494 program's code flow. Usually type narrowing is done by analyzing
1495 conditional code flow and applying the narrowing to a block of code. The
1496 conditional expression here is sometimes referred to as a "type guard".
1498 Sometimes it would be convenient to use a user-defined boolean function
1499 as a type guard. Such a function should use ``TypeGuard[...]`` as its
1500 return type to alert static type checkers to this intention.
1502 Using ``-> TypeGuard`` tells the static type checker that for a given
1503 function:
1505 1. The return value is a boolean.
1506 2. If the return value is ``True``, the type of its argument
1507 is the type inside ``TypeGuard``.
1509 For example::
1511 def is_str(val: Union[str, float]):
1512 # "isinstance" type guard
1513 if isinstance(val, str):
1514 # Type of ``val`` is narrowed to ``str``
1515 ...
1516 else:
1517 # Else, type of ``val`` is narrowed to ``float``.
1518 ...
1520 Strict type narrowing is not enforced -- ``TypeB`` need not be a narrower
1521 form of ``TypeA`` (it can even be a wider form) and this may lead to
1522 type-unsafe results. The main reason is to allow for things like
1523 narrowing ``List[object]`` to ``List[str]`` even though the latter is not
1524 a subtype of the former, since ``List`` is invariant. The responsibility of
1525 writing type-safe type guards is left to the user.
1527 ``TypeGuard`` also works with type variables. For more information, see
1528 PEP 647 (User-Defined Type Guards).
1529 """
1530 item = typing._type_check(parameters, f'{self} accepts only a single type.')
1531 return typing._GenericAlias(self, (item,))
1532# 3.7-3.8
1533else:
1534 class _TypeGuardForm(typing._SpecialForm, _root=True):
1536 def __repr__(self):
1537 return 'typing_extensions.' + self._name
1539 def __getitem__(self, parameters):
1540 item = typing._type_check(parameters,
1541 f'{self._name} accepts only a single type')
1542 return typing._GenericAlias(self, (item,))
1544 TypeGuard = _TypeGuardForm(
1545 'TypeGuard',
1546 doc="""Special typing form used to annotate the return type of a user-defined
1547 type guard function. ``TypeGuard`` only accepts a single type argument.
1548 At runtime, functions marked this way should return a boolean.
1550 ``TypeGuard`` aims to benefit *type narrowing* -- a technique used by static
1551 type checkers to determine a more precise type of an expression within a
1552 program's code flow. Usually type narrowing is done by analyzing
1553 conditional code flow and applying the narrowing to a block of code. The
1554 conditional expression here is sometimes referred to as a "type guard".
1556 Sometimes it would be convenient to use a user-defined boolean function
1557 as a type guard. Such a function should use ``TypeGuard[...]`` as its
1558 return type to alert static type checkers to this intention.
1560 Using ``-> TypeGuard`` tells the static type checker that for a given
1561 function:
1563 1. The return value is a boolean.
1564 2. If the return value is ``True``, the type of its argument
1565 is the type inside ``TypeGuard``.
1567 For example::
1569 def is_str(val: Union[str, float]):
1570 # "isinstance" type guard
1571 if isinstance(val, str):
1572 # Type of ``val`` is narrowed to ``str``
1573 ...
1574 else:
1575 # Else, type of ``val`` is narrowed to ``float``.
1576 ...
1578 Strict type narrowing is not enforced -- ``TypeB`` need not be a narrower
1579 form of ``TypeA`` (it can even be a wider form) and this may lead to
1580 type-unsafe results. The main reason is to allow for things like
1581 narrowing ``List[object]`` to ``List[str]`` even though the latter is not
1582 a subtype of the former, since ``List`` is invariant. The responsibility of
1583 writing type-safe type guards is left to the user.
1585 ``TypeGuard`` also works with type variables. For more information, see
1586 PEP 647 (User-Defined Type Guards).
1587 """)
1590# Vendored from cpython typing._SpecialFrom
1591class _SpecialForm(typing._Final, _root=True):
1592 __slots__ = ('_name', '__doc__', '_getitem')
1594 def __init__(self, getitem):
1595 self._getitem = getitem
1596 self._name = getitem.__name__
1597 self.__doc__ = getitem.__doc__
1599 def __getattr__(self, item):
1600 if item in {'__name__', '__qualname__'}:
1601 return self._name
1603 raise AttributeError(item)
1605 def __mro_entries__(self, bases):
1606 raise TypeError(f"Cannot subclass {self!r}")
1608 def __repr__(self):
1609 return f'typing_extensions.{self._name}'
1611 def __reduce__(self):
1612 return self._name
1614 def __call__(self, *args, **kwds):
1615 raise TypeError(f"Cannot instantiate {self!r}")
1617 def __or__(self, other):
1618 return typing.Union[self, other]
1620 def __ror__(self, other):
1621 return typing.Union[other, self]
1623 def __instancecheck__(self, obj):
1624 raise TypeError(f"{self} cannot be used with isinstance()")
1626 def __subclasscheck__(self, cls):
1627 raise TypeError(f"{self} cannot be used with issubclass()")
1629 @typing._tp_cache
1630 def __getitem__(self, parameters):
1631 return self._getitem(self, parameters)
1634if hasattr(typing, "LiteralString"):
1635 LiteralString = typing.LiteralString
1636else:
1637 @_SpecialForm
1638 def LiteralString(self, params):
1639 """Represents an arbitrary literal string.
1641 Example::
1643 from typing_extensions import LiteralString
1645 def query(sql: LiteralString) -> ...:
1646 ...
1648 query("SELECT * FROM table") # ok
1649 query(f"SELECT * FROM {input()}") # not ok
1651 See PEP 675 for details.
1653 """
1654 raise TypeError(f"{self} is not subscriptable")
1657if hasattr(typing, "Self"):
1658 Self = typing.Self
1659else:
1660 @_SpecialForm
1661 def Self(self, params):
1662 """Used to spell the type of "self" in classes.
1664 Example::
1666 from typing import Self
1668 class ReturnsSelf:
1669 def parse(self, data: bytes) -> Self:
1670 ...
1671 return self
1673 """
1675 raise TypeError(f"{self} is not subscriptable")
1678if hasattr(typing, "Never"):
1679 Never = typing.Never
1680else:
1681 @_SpecialForm
1682 def Never(self, params):
1683 """The bottom type, a type that has no members.
1685 This can be used to define a function that should never be
1686 called, or a function that never returns::
1688 from typing_extensions import Never
1690 def never_call_me(arg: Never) -> None:
1691 pass
1693 def int_or_str(arg: int | str) -> None:
1694 never_call_me(arg) # type checker error
1695 match arg:
1696 case int():
1697 print("It's an int")
1698 case str():
1699 print("It's a str")
1700 case _:
1701 never_call_me(arg) # ok, arg is of type Never
1703 """
1705 raise TypeError(f"{self} is not subscriptable")
1708if hasattr(typing, 'Required'):
1709 Required = typing.Required
1710 NotRequired = typing.NotRequired
1711elif sys.version_info[:2] >= (3, 9):
1712 class _ExtensionsSpecialForm(typing._SpecialForm, _root=True):
1713 def __repr__(self):
1714 return 'typing_extensions.' + self._name
1716 @_ExtensionsSpecialForm
1717 def Required(self, parameters):
1718 """A special typing construct to mark a key of a total=False TypedDict
1719 as required. For example:
1721 class Movie(TypedDict, total=False):
1722 title: Required[str]
1723 year: int
1725 m = Movie(
1726 title='The Matrix', # typechecker error if key is omitted
1727 year=1999,
1728 )
1730 There is no runtime checking that a required key is actually provided
1731 when instantiating a related TypedDict.
1732 """
1733 item = typing._type_check(parameters, f'{self._name} accepts only a single type.')
1734 return typing._GenericAlias(self, (item,))
1736 @_ExtensionsSpecialForm
1737 def NotRequired(self, parameters):
1738 """A special typing construct to mark a key of a TypedDict as
1739 potentially missing. For example:
1741 class Movie(TypedDict):
1742 title: str
1743 year: NotRequired[int]
1745 m = Movie(
1746 title='The Matrix', # typechecker error if key is omitted
1747 year=1999,
1748 )
1749 """
1750 item = typing._type_check(parameters, f'{self._name} accepts only a single type.')
1751 return typing._GenericAlias(self, (item,))
1753else:
1754 class _RequiredForm(typing._SpecialForm, _root=True):
1755 def __repr__(self):
1756 return 'typing_extensions.' + self._name
1758 def __getitem__(self, parameters):
1759 item = typing._type_check(parameters,
1760 f'{self._name} accepts only a single type.')
1761 return typing._GenericAlias(self, (item,))
1763 Required = _RequiredForm(
1764 'Required',
1765 doc="""A special typing construct to mark a key of a total=False TypedDict
1766 as required. For example:
1768 class Movie(TypedDict, total=False):
1769 title: Required[str]
1770 year: int
1772 m = Movie(
1773 title='The Matrix', # typechecker error if key is omitted
1774 year=1999,
1775 )
1777 There is no runtime checking that a required key is actually provided
1778 when instantiating a related TypedDict.
1779 """)
1780 NotRequired = _RequiredForm(
1781 'NotRequired',
1782 doc="""A special typing construct to mark a key of a TypedDict as
1783 potentially missing. For example:
1785 class Movie(TypedDict):
1786 title: str
1787 year: NotRequired[int]
1789 m = Movie(
1790 title='The Matrix', # typechecker error if key is omitted
1791 year=1999,
1792 )
1793 """)
1796if hasattr(typing, "Unpack"): # 3.11+
1797 Unpack = typing.Unpack
1798elif sys.version_info[:2] >= (3, 9):
1799 class _UnpackSpecialForm(typing._SpecialForm, _root=True):
1800 def __repr__(self):
1801 return 'typing_extensions.' + self._name
1803 class _UnpackAlias(typing._GenericAlias, _root=True):
1804 __class__ = typing.TypeVar
1806 @_UnpackSpecialForm
1807 def Unpack(self, parameters):
1808 """A special typing construct to unpack a variadic type. For example:
1810 Shape = TypeVarTuple('Shape')
1811 Batch = NewType('Batch', int)
1813 def add_batch_axis(
1814 x: Array[Unpack[Shape]]
1815 ) -> Array[Batch, Unpack[Shape]]: ...
1817 """
1818 item = typing._type_check(parameters, f'{self._name} accepts only a single type.')
1819 return _UnpackAlias(self, (item,))
1821 def _is_unpack(obj):
1822 return isinstance(obj, _UnpackAlias)
1824else:
1825 class _UnpackAlias(typing._GenericAlias, _root=True):
1826 __class__ = typing.TypeVar
1828 class _UnpackForm(typing._SpecialForm, _root=True):
1829 def __repr__(self):
1830 return 'typing_extensions.' + self._name
1832 def __getitem__(self, parameters):
1833 item = typing._type_check(parameters,
1834 f'{self._name} accepts only a single type.')
1835 return _UnpackAlias(self, (item,))
1837 Unpack = _UnpackForm(
1838 'Unpack',
1839 doc="""A special typing construct to unpack a variadic type. For example:
1841 Shape = TypeVarTuple('Shape')
1842 Batch = NewType('Batch', int)
1844 def add_batch_axis(
1845 x: Array[Unpack[Shape]]
1846 ) -> Array[Batch, Unpack[Shape]]: ...
1848 """)
1850 def _is_unpack(obj):
1851 return isinstance(obj, _UnpackAlias)
1854if hasattr(typing, "TypeVarTuple"): # 3.11+
1856 # Add default Parameter - PEP 696
1857 class TypeVarTuple(typing.TypeVarTuple, _DefaultMixin, _root=True):
1858 """Type variable tuple."""
1860 def __init__(self, name, *, default=_marker):
1861 super().__init__(name)
1862 _DefaultMixin.__init__(self, default)
1864 # for pickling:
1865 try:
1866 def_mod = sys._getframe(1).f_globals.get('__name__', '__main__')
1867 except (AttributeError, ValueError):
1868 def_mod = None
1869 if def_mod != 'typing_extensions':
1870 self.__module__ = def_mod
1872else:
1873 class TypeVarTuple(_DefaultMixin):
1874 """Type variable tuple.
1876 Usage::
1878 Ts = TypeVarTuple('Ts')
1880 In the same way that a normal type variable is a stand-in for a single
1881 type such as ``int``, a type variable *tuple* is a stand-in for a *tuple*
1882 type such as ``Tuple[int, str]``.
1884 Type variable tuples can be used in ``Generic`` declarations.
1885 Consider the following example::
1887 class Array(Generic[*Ts]): ...
1889 The ``Ts`` type variable tuple here behaves like ``tuple[T1, T2]``,
1890 where ``T1`` and ``T2`` are type variables. To use these type variables
1891 as type parameters of ``Array``, we must *unpack* the type variable tuple using
1892 the star operator: ``*Ts``. The signature of ``Array`` then behaves
1893 as if we had simply written ``class Array(Generic[T1, T2]): ...``.
1894 In contrast to ``Generic[T1, T2]``, however, ``Generic[*Shape]`` allows
1895 us to parameterise the class with an *arbitrary* number of type parameters.
1897 Type variable tuples can be used anywhere a normal ``TypeVar`` can.
1898 This includes class definitions, as shown above, as well as function
1899 signatures and variable annotations::
1901 class Array(Generic[*Ts]):
1903 def __init__(self, shape: Tuple[*Ts]):
1904 self._shape: Tuple[*Ts] = shape
1906 def get_shape(self) -> Tuple[*Ts]:
1907 return self._shape
1909 shape = (Height(480), Width(640))
1910 x: Array[Height, Width] = Array(shape)
1911 y = abs(x) # Inferred type is Array[Height, Width]
1912 z = x + x # ... is Array[Height, Width]
1913 x.get_shape() # ... is tuple[Height, Width]
1915 """
1917 # Trick Generic __parameters__.
1918 __class__ = typing.TypeVar
1920 def __iter__(self):
1921 yield self.__unpacked__
1923 def __init__(self, name, *, default=_marker):
1924 self.__name__ = name
1925 _DefaultMixin.__init__(self, default)
1927 # for pickling:
1928 try:
1929 def_mod = sys._getframe(1).f_globals.get('__name__', '__main__')
1930 except (AttributeError, ValueError):
1931 def_mod = None
1932 if def_mod != 'typing_extensions':
1933 self.__module__ = def_mod
1935 self.__unpacked__ = Unpack[self]
1937 def __repr__(self):
1938 return self.__name__
1940 def __hash__(self):
1941 return object.__hash__(self)
1943 def __eq__(self, other):
1944 return self is other
1946 def __reduce__(self):
1947 return self.__name__
1949 def __init_subclass__(self, *args, **kwds):
1950 if '_root' not in kwds:
1951 raise TypeError("Cannot subclass special typing classes")
1954if hasattr(typing, "reveal_type"):
1955 reveal_type = typing.reveal_type
1956else:
1957 def reveal_type(__obj: T) -> T:
1958 """Reveal the inferred type of a variable.
1960 When a static type checker encounters a call to ``reveal_type()``,
1961 it will emit the inferred type of the argument::
1963 x: int = 1
1964 reveal_type(x)
1966 Running a static type checker (e.g., ``mypy``) on this example
1967 will produce output similar to 'Revealed type is "builtins.int"'.
1969 At runtime, the function prints the runtime type of the
1970 argument and returns it unchanged.
1972 """
1973 print(f"Runtime type is {type(__obj).__name__!r}", file=sys.stderr)
1974 return __obj
1977if hasattr(typing, "assert_never"):
1978 assert_never = typing.assert_never
1979else:
1980 def assert_never(__arg: Never) -> Never:
1981 """Assert to the type checker that a line of code is unreachable.
1983 Example::
1985 def int_or_str(arg: int | str) -> None:
1986 match arg:
1987 case int():
1988 print("It's an int")
1989 case str():
1990 print("It's a str")
1991 case _:
1992 assert_never(arg)
1994 If a type checker finds that a call to assert_never() is
1995 reachable, it will emit an error.
1997 At runtime, this throws an exception when called.
1999 """
2000 raise AssertionError("Expected code to be unreachable")
2003if sys.version_info >= (3, 12):
2004 # dataclass_transform exists in 3.11 but lacks the frozen_default parameter
2005 dataclass_transform = typing.dataclass_transform
2006else:
2007 def dataclass_transform(
2008 *,
2009 eq_default: bool = True,
2010 order_default: bool = False,
2011 kw_only_default: bool = False,
2012 frozen_default: bool = False,
2013 field_specifiers: typing.Tuple[
2014 typing.Union[typing.Type[typing.Any], typing.Callable[..., typing.Any]],
2015 ...
2016 ] = (),
2017 **kwargs: typing.Any,
2018 ) -> typing.Callable[[T], T]:
2019 """Decorator that marks a function, class, or metaclass as providing
2020 dataclass-like behavior.
2022 Example:
2024 from typing_extensions import dataclass_transform
2026 _T = TypeVar("_T")
2028 # Used on a decorator function
2029 @dataclass_transform()
2030 def create_model(cls: type[_T]) -> type[_T]:
2031 ...
2032 return cls
2034 @create_model
2035 class CustomerModel:
2036 id: int
2037 name: str
2039 # Used on a base class
2040 @dataclass_transform()
2041 class ModelBase: ...
2043 class CustomerModel(ModelBase):
2044 id: int
2045 name: str
2047 # Used on a metaclass
2048 @dataclass_transform()
2049 class ModelMeta(type): ...
2051 class ModelBase(metaclass=ModelMeta): ...
2053 class CustomerModel(ModelBase):
2054 id: int
2055 name: str
2057 Each of the ``CustomerModel`` classes defined in this example will now
2058 behave similarly to a dataclass created with the ``@dataclasses.dataclass``
2059 decorator. For example, the type checker will synthesize an ``__init__``
2060 method.
2062 The arguments to this decorator can be used to customize this behavior:
2063 - ``eq_default`` indicates whether the ``eq`` parameter is assumed to be
2064 True or False if it is omitted by the caller.
2065 - ``order_default`` indicates whether the ``order`` parameter is
2066 assumed to be True or False if it is omitted by the caller.
2067 - ``kw_only_default`` indicates whether the ``kw_only`` parameter is
2068 assumed to be True or False if it is omitted by the caller.
2069 - ``frozen_default`` indicates whether the ``frozen`` parameter is
2070 assumed to be True or False if it is omitted by the caller.
2071 - ``field_specifiers`` specifies a static list of supported classes
2072 or functions that describe fields, similar to ``dataclasses.field()``.
2074 At runtime, this decorator records its arguments in the
2075 ``__dataclass_transform__`` attribute on the decorated object.
2077 See PEP 681 for details.
2079 """
2080 def decorator(cls_or_fn):
2081 cls_or_fn.__dataclass_transform__ = {
2082 "eq_default": eq_default,
2083 "order_default": order_default,
2084 "kw_only_default": kw_only_default,
2085 "frozen_default": frozen_default,
2086 "field_specifiers": field_specifiers,
2087 "kwargs": kwargs,
2088 }
2089 return cls_or_fn
2090 return decorator
2093if hasattr(typing, "override"):
2094 override = typing.override
2095else:
2096 _F = typing.TypeVar("_F", bound=typing.Callable[..., typing.Any])
2098 def override(__arg: _F) -> _F:
2099 """Indicate that a method is intended to override a method in a base class.
2101 Usage:
2103 class Base:
2104 def method(self) -> None: ...
2105 pass
2107 class Child(Base):
2108 @override
2109 def method(self) -> None:
2110 super().method()
2112 When this decorator is applied to a method, the type checker will
2113 validate that it overrides a method with the same name on a base class.
2114 This helps prevent bugs that may occur when a base class is changed
2115 without an equivalent change to a child class.
2117 There is no runtime checking of these properties. The decorator
2118 sets the ``__override__`` attribute to ``True`` on the decorated object
2119 to allow runtime introspection.
2121 See PEP 698 for details.
2123 """
2124 try:
2125 __arg.__override__ = True
2126 except (AttributeError, TypeError):
2127 # Skip the attribute silently if it is not writable.
2128 # AttributeError happens if the object has __slots__ or a
2129 # read-only property, TypeError if it's a builtin class.
2130 pass
2131 return __arg
2134if hasattr(typing, "deprecated"):
2135 deprecated = typing.deprecated
2136else:
2137 _T = typing.TypeVar("_T")
2139 def deprecated(
2140 __msg: str,
2141 *,
2142 category: typing.Optional[typing.Type[Warning]] = DeprecationWarning,
2143 stacklevel: int = 1,
2144 ) -> typing.Callable[[_T], _T]:
2145 """Indicate that a class, function or overload is deprecated.
2147 Usage:
2149 @deprecated("Use B instead")
2150 class A:
2151 pass
2153 @deprecated("Use g instead")
2154 def f():
2155 pass
2157 @overload
2158 @deprecated("int support is deprecated")
2159 def g(x: int) -> int: ...
2160 @overload
2161 def g(x: str) -> int: ...
2163 When this decorator is applied to an object, the type checker
2164 will generate a diagnostic on usage of the deprecated object.
2166 No runtime warning is issued. The decorator sets the ``__deprecated__``
2167 attribute on the decorated object to the deprecation message
2168 passed to the decorator. If applied to an overload, the decorator
2169 must be after the ``@overload`` decorator for the attribute to
2170 exist on the overload as returned by ``get_overloads()``.
2172 See PEP 702 for details.
2174 """
2175 def decorator(__arg: _T) -> _T:
2176 if category is None:
2177 __arg.__deprecated__ = __msg
2178 return __arg
2179 elif isinstance(__arg, type):
2180 original_new = __arg.__new__
2181 has_init = __arg.__init__ is not object.__init__
2183 @functools.wraps(original_new)
2184 def __new__(cls, *args, **kwargs):
2185 warnings.warn(__msg, category=category, stacklevel=stacklevel + 1)
2186 # Mirrors a similar check in object.__new__.
2187 if not has_init and (args or kwargs):
2188 raise TypeError(f"{cls.__name__}() takes no arguments")
2189 if original_new is not object.__new__:
2190 return original_new(cls, *args, **kwargs)
2191 else:
2192 return original_new(cls)
2194 __arg.__new__ = staticmethod(__new__)
2195 __arg.__deprecated__ = __new__.__deprecated__ = __msg
2196 return __arg
2197 elif callable(__arg):
2198 @functools.wraps(__arg)
2199 def wrapper(*args, **kwargs):
2200 warnings.warn(__msg, category=category, stacklevel=stacklevel + 1)
2201 return __arg(*args, **kwargs)
2203 __arg.__deprecated__ = wrapper.__deprecated__ = __msg
2204 return wrapper
2205 else:
2206 raise TypeError(
2207 "@deprecated decorator with non-None category must be applied to "
2208 f"a class or callable, not {__arg!r}"
2209 )
2211 return decorator
2214# We have to do some monkey patching to deal with the dual nature of
2215# Unpack/TypeVarTuple:
2216# - We want Unpack to be a kind of TypeVar so it gets accepted in
2217# Generic[Unpack[Ts]]
2218# - We want it to *not* be treated as a TypeVar for the purposes of
2219# counting generic parameters, so that when we subscript a generic,
2220# the runtime doesn't try to substitute the Unpack with the subscripted type.
2221if not hasattr(typing, "TypeVarTuple"):
2222 typing._collect_type_vars = _collect_type_vars
2223 typing._check_generic = _check_generic
2226# Backport typing.NamedTuple as it exists in Python 3.11.
2227# In 3.11, the ability to define generic `NamedTuple`s was supported.
2228# This was explicitly disallowed in 3.9-3.10, and only half-worked in <=3.8.
2229if sys.version_info >= (3, 11):
2230 NamedTuple = typing.NamedTuple
2231else:
2232 def _caller():
2233 try:
2234 return sys._getframe(2).f_globals.get('__name__', '__main__')
2235 except (AttributeError, ValueError): # For platforms without _getframe()
2236 return None
2238 def _make_nmtuple(name, types, module, defaults=()):
2239 fields = [n for n, t in types]
2240 annotations = {n: typing._type_check(t, f"field {n} annotation must be a type")
2241 for n, t in types}
2242 nm_tpl = collections.namedtuple(name, fields,
2243 defaults=defaults, module=module)
2244 nm_tpl.__annotations__ = nm_tpl.__new__.__annotations__ = annotations
2245 # The `_field_types` attribute was removed in 3.9;
2246 # in earlier versions, it is the same as the `__annotations__` attribute
2247 if sys.version_info < (3, 9):
2248 nm_tpl._field_types = annotations
2249 return nm_tpl
2251 _prohibited_namedtuple_fields = typing._prohibited
2252 _special_namedtuple_fields = frozenset({'__module__', '__name__', '__annotations__'})
2254 class _NamedTupleMeta(type):
2255 def __new__(cls, typename, bases, ns):
2256 assert _NamedTuple in bases
2257 for base in bases:
2258 if base is not _NamedTuple and base is not typing.Generic:
2259 raise TypeError(
2260 'can only inherit from a NamedTuple type and Generic')
2261 bases = tuple(tuple if base is _NamedTuple else base for base in bases)
2262 types = ns.get('__annotations__', {})
2263 default_names = []
2264 for field_name in types:
2265 if field_name in ns:
2266 default_names.append(field_name)
2267 elif default_names:
2268 raise TypeError(f"Non-default namedtuple field {field_name} "
2269 f"cannot follow default field"
2270 f"{'s' if len(default_names) > 1 else ''} "
2271 f"{', '.join(default_names)}")
2272 nm_tpl = _make_nmtuple(
2273 typename, types.items(),
2274 defaults=[ns[n] for n in default_names],
2275 module=ns['__module__']
2276 )
2277 nm_tpl.__bases__ = bases
2278 if typing.Generic in bases:
2279 class_getitem = typing.Generic.__class_getitem__.__func__
2280 nm_tpl.__class_getitem__ = classmethod(class_getitem)
2281 # update from user namespace without overriding special namedtuple attributes
2282 for key in ns:
2283 if key in _prohibited_namedtuple_fields:
2284 raise AttributeError("Cannot overwrite NamedTuple attribute " + key)
2285 elif key not in _special_namedtuple_fields and key not in nm_tpl._fields:
2286 setattr(nm_tpl, key, ns[key])
2287 if typing.Generic in bases:
2288 nm_tpl.__init_subclass__()
2289 return nm_tpl
2291 def NamedTuple(__typename, __fields=None, **kwargs):
2292 if __fields is None:
2293 __fields = kwargs.items()
2294 elif kwargs:
2295 raise TypeError("Either list of fields or keywords"
2296 " can be provided to NamedTuple, not both")
2297 return _make_nmtuple(__typename, __fields, module=_caller())
2299 NamedTuple.__doc__ = typing.NamedTuple.__doc__
2300 _NamedTuple = type.__new__(_NamedTupleMeta, 'NamedTuple', (), {})
2302 # On 3.8+, alter the signature so that it matches typing.NamedTuple.
2303 # The signature of typing.NamedTuple on >=3.8 is invalid syntax in Python 3.7,
2304 # so just leave the signature as it is on 3.7.
2305 if sys.version_info >= (3, 8):
2306 NamedTuple.__text_signature__ = '(typename, fields=None, /, **kwargs)'
2308 def _namedtuple_mro_entries(bases):
2309 assert NamedTuple in bases
2310 return (_NamedTuple,)
2312 NamedTuple.__mro_entries__ = _namedtuple_mro_entries