34 'AsyncContextManager',
61 'dataclass_transform',
68 'get_protocol_members',
128 'no_type_check_decorator',
148 """Check correct count for parameters of a generic cls (internal helper).
149 This gives a nice error message in case of count mismatch.
152 raise TypeError(f
"{cls} is not a generic class")
154 if not hasattr(cls,
"__parameters__")
or not cls.__parameters__:
155 raise TypeError(f
"{cls} is not a generic class")
156 elen =
len(cls.__parameters__)
157 alen =
len(parameters)
159 if hasattr(cls,
"__parameters__"):
160 parameters = [p
for p
in cls.__parameters__
if not _is_unpack(p)]
161 num_tv_tuples =
sum(
isinstance(p, TypeVarTuple)
for p
in parameters)
162 if (num_tv_tuples > 0)
and (alen >= elen - num_tv_tuples):
164 raise TypeError(f
"Too {'many' if alen > elen else 'few'} parameters for {cls};"
165 f
" actual {alen}, expected {elen}")
182 """Collect all type variable contained in types in order of
183 first appearance (lexicographic order). For example::
185 _collect_type_vars((T, List[S, T])) == (T, S)
187 if typevar_types
is None:
214 from typing
import Any
220 raise TypeError(
"typing_extensions.Any cannot be used with isinstance()")
225 return "typing_extensions.Any"
228 class Any(metaclass=_AnyMeta):
229 """Special type indicating an unconstrained type.
230 - Any is compatible with every type.
231 - Any assumed to have all methods.
232 - All values assumed to be instances of Any.
233 Note that all the above statements are true from the point of view of
234 static type checkers. At runtime, Any should not be used with instance
239 raise TypeError(
"Any cannot be instantiated")
248 return 'typing_extensions.' + self._name
260 f
'{self._name} accepts only a single type.')
264 doc=
"""A special typing construct to indicate that a name
265 cannot be re-assigned or overridden in a subclass.
268 MAX_SIZE: Final = 9000
269 MAX_SIZE += 1 # Error reported by type checker
272 TIMEOUT: Final[int] = 10
273 class FastConnector(Connection):
274 TIMEOUT = 1 # Error reported by type checker
276 There is no runtime checking of these properties.""")
285 """This decorator can be used to indicate to type checkers that
286 the decorated method cannot be overridden, and decorated class
287 cannot be subclassed. For example:
291 def done(self) -> None:
294 def done(self) -> None: # Error reported by type checker
299 class Other(Leaf): # Error reported by type checker
302 There is no runtime checking of these properties. The decorator
303 sets the ``__final__`` attribute to ``True`` on the decorated object
304 to allow runtime introspection.
308 except (AttributeError, TypeError):
325 """An internal helper for Literal creation: flatten Literals among parameters"""
340 if not isinstance(other, _LiteralGenericAlias):
341 return NotImplemented
344 return these_args_deduped == other_args_deduped
356 parameters = (parameters,)
362 deduped_pairs = set(val_type_pairs)
368 if len(deduped_pairs) <
len(val_type_pairs):
370 for pair
in val_type_pairs:
371 if pair
in deduped_pairs:
374 assert not deduped_pairs, deduped_pairs
375 parameters = tuple(new_parameters)
380 A type that can be used to indicate to type checkers
381 that the corresponding value has a value literally equivalent
382 to the provided parameter. For example:
386 The type checker understands that 'var' is literally equal to
387 the value 4 and no other value.
389 Literal[...] cannot be subclassed. There is no runtime
390 checking verifying that the parameter is actually a value
391 instead of a type.""")
397if hasattr(typing,
"get_overloads"):
408 """Decorator for overloaded functions/methods.
410 In a stub file, place two or more stub definitions for the same
411 function in a row, each decorated with @overload. For example:
414 def utf8(value: None) -> None: ...
416 def utf8(value: bytes) -> bytes: ...
418 def utf8(value: str) -> bytes: ...
420 In a non-stub file (i.e. a regular .py file), do the same but
421 follow it with an implementation. The implementation should *not*
422 be decorated with @overload. For example:
425 def utf8(value: None) -> None: ...
427 def utf8(value: bytes) -> bytes: ...
429 def utf8(value: str) -> bytes: ...
431 # implementation goes here
433 The overloads for a function can be retrieved at runtime using the
434 get_overloads() function.
437 f =
getattr(func,
"__func__", func)
442 except AttributeError:
445 return _overload_dummy
448 """Return all defined overloads for *func* as a sequence."""
450 f =
getattr(func,
"__func__", func)
459 """Clear all overloads in the registry."""
480if hasattr(typing,
'OrderedDict'):
495 'Callable',
'Awaitable',
'Iterable',
'Iterator',
'AsyncIterable',
496 'Hashable',
'Sized',
'Container',
'Collection',
'Reversible',
'Buffer',
498 'contextlib': [
'AbstractContextManager',
'AbstractAsyncContextManager'],
499 'typing_extensions': [
'Buffer'],
504 "__abstractmethods__",
"__annotations__",
"__weakref__",
"_is_protocol",
505 "_is_runtime_protocol",
"__dict__",
"__slots__",
"__parameters__",
506 "__orig_bases__",
"__module__",
"_MutableMapping__marker",
"__doc__",
507 "__subclasshook__",
"__orig_class__",
"__init__",
"__new__",
508 "__protocol_attrs__",
"__callable_proto_members_only__",
513 "_gorg",
"__next_in_mro__",
"__extra__",
"__tree_hash__",
"__args__",
523_EXCLUDED_ATTRS =
frozenset(_EXCLUDED_ATTRS)
528 for base
in cls.__mro__[:-1]:
531 annotations =
getattr(base,
'__annotations__', {})
539 """Helper function used in Protocol.__init_subclass__ and _TypedDictMeta.__new__.
541 The contents of this function are very similar
542 to logic found in typing.Generic.__init_subclass__
543 on the CPython main branch.
546 if '__orig_bases__' in cls.__dict__:
554 for base
in cls.__orig_bases__:
559 if gvars
is not None:
561 "Cannot inherit from Generic[...]"
562 " and/or Protocol[...] multiple types.")
569 if not tvarset <= gvarset:
570 s_vars =
', '.join(str(t)
for t
in tvars
if t
not in gvarset)
571 s_args =
', '.join(str(g)
for g
in gvars)
572 raise TypeError(f
"Some type variables ({s_vars}) are"
573 f
" not listed in {the_base}[{s_args}]")
575 cls.__parameters__ = tuple(tvars)
581 except (AttributeError, ValueError):
591 """Allow instance and class checks for special stdlib modules.
592 The abc and functools modules indiscriminately call isinstance() and
593 issubclass() on the whole MRO of a user class, which may contain protocols.
595 return _caller(depth)
in {
'abc',
'functools',
None}
598 if type(self)._is_protocol:
599 raise TypeError(
'Protocols cannot be instantiated')
606 _ProtocolMetaBase = type(_typing_Protocol)
608 _typing_Protocol = _marker
618 def __new__(mcls, name, bases, namespace, **kwargs):
619 if name ==
"Protocol" and len(bases) < 2:
621 elif {Protocol, _typing_Protocol} & set(bases):
629 f
"Protocols can only inherit from other protocols, "
636 if getattr(cls,
"_is_protocol",
False):
648 getattr(cls,
'_is_protocol',
False)
653 raise TypeError(
'issubclass() arg 1 must be a class')
656 and cls.__dict__.get(
"__subclasshook__")
is _proto_hook
659 "Protocols with non-method members don't support issubclass()"
661 if not getattr(cls,
'_is_runtime_protocol',
False):
663 "Instance and class checks can only be used with "
664 "@runtime_checkable protocols"
673 if not getattr(cls,
"_is_protocol",
False):
678 not getattr(cls,
'_is_runtime_protocol',
False)
and
681 raise TypeError(
"Instance and class checks can only be used with"
682 " @runtime_checkable protocols")
690 except AttributeError:
692 if val
is None and callable(
getattr(cls, attr,
None)):
706 cls
is Protocol
and other
is getattr(typing,
"Protocol", object())
717 if not cls.__dict__.get(
'_is_protocol',
False):
718 return NotImplemented
720 for attr
in cls.__protocol_attrs__:
725 return NotImplemented
729 annotations =
getattr(base,
'__annotations__', {})
732 and attr
in annotations
737 return NotImplemented
745 _is_runtime_protocol =
False
751 if not cls.__dict__.get(
'_is_protocol',
False):
755 if '__subclasshook__' not in cls.__dict__:
763 class Protocol(metaclass=_ProtocolMeta):
767 """Base class for protocol classes. Protocol classes are defined as::
769 class Proto(Protocol):
770 def meth(self) -> int:
773 Such classes are primarily used with static type checkers that recognize
774 structural subtyping (static duck-typing), for example::
777 def meth(self) -> int:
780 def func(x: Proto) -> int:
783 func(C()) # Passes static type check
785 See PEP 544 for details. Protocol classes decorated with
786 @typing_extensions.runtime_checkable act
787 as simple-minded runtime-checkable protocols that check
788 only the presence of given attributes, ignoring their type signatures.
790 Protocol classes can be generic, they are defined as::
792 class GenProto(Protocol[T]):
798 _is_runtime_protocol =
False
802 raise TypeError(
"Type Protocol cannot be instantiated; "
803 "it can only be used as a base class")
812 f
"Parameter list to {cls.__qualname__}[...] cannot be empty")
813 msg =
"Parameters to generic types must be types."
822 "Parameters to Protocol[...] must all be type variables."
823 f
" Parameter {i + 1} is {params[i]}")
824 if len(set(params)) !=
len(params):
826 "Parameters to Protocol[...] must all be unique")
833 if '__orig_bases__' in cls.__dict__:
838 raise TypeError(
"Cannot inherit from plain Generic")
842 if not cls.__dict__.get(
'_is_protocol',
None):
846 if '__subclasshook__' not in cls.__dict__:
858 """Mark a protocol class as a runtime protocol, so that it
859 can be used with isinstance() and issubclass(). Raise TypeError
860 if applied to a non-protocol class.
862 This allows a simple-minded structural check very similar to the
863 one-offs in collections.abc such as Hashable.
867 and getattr(cls,
"_is_protocol",
False)
869 raise TypeError(
'@runtime_checkable can be only applied to protocol classes,'
871 cls._is_runtime_protocol =
True
876runtime = runtime_checkable
891 """An ABC with one abstract method __int__."""
900 """An ABC with one abstract method __float__."""
909 """An ABC with one abstract method __complex__."""
918 """An ABC with one abstract method __bytes__."""
936 An ABC with one abstract method __abs__ that is covariant in its return type.
947 An ABC with one abstract method __round__ that is covariant in its return type.
990 _fake_name =
"Protocol"
992 _fake_name =
"_Protocol"
995 def __new__(cls, name, bases, ns, total=True):
996 """Create new typed dict class object.
998 This method is called when TypedDict is subclassed,
999 or when TypedDict is instantiated. This way
1000 TypedDict supports all three syntax forms described in its docstring.
1001 Subclasses and instances of TypedDict return actual dictionaries.
1004 if type(base)
is not _TypedDictMeta
and base
is not typing.Generic:
1005 raise TypeError(
'cannot inherit from both a TypedDict type '
1006 'and a non-TypedDict base class')
1015 tp_dict =
type.__new__(_TypedDictMeta, _fake_name, (*generic_base, dict), ns)
1020 if not hasattr(tp_dict,
'__orig_bases__'):
1024 own_annotations =
ns.get(
'__annotations__', {})
1025 msg =
"TypedDict('Name', {f0: t0, f1: t1, ...}); each t must be a type"
1036 required_keys = set()
1037 optional_keys = set()
1046 annotation_origin =
get_origin(annotation_type)
1047 if annotation_origin
is Annotated:
1048 annotation_args =
get_args(annotation_type)
1050 annotation_type = annotation_args[0]
1051 annotation_origin =
get_origin(annotation_type)
1053 if annotation_origin
is Required:
1055 elif annotation_origin
is NotRequired:
1065 if not hasattr(tp_dict,
'__total__'):
1073 raise TypeError(
'TypedDict does not support instance and class checks')
1075 __instancecheck__ = __subclasscheck__
1079 @_ensure_subclassable(lambda bases: (_TypedDict,))
1080 def TypedDict(__typename, __fields=_marker, *, total=True, **kwargs):
1081 """A simple typed namespace. At runtime it is equivalent to a plain dict.
1083 TypedDict creates a dictionary type such that a type checker will expect all
1084 instances to have a certain set of keys, where each key is
1085 associated with a value of a consistent type. This expectation
1086 is not checked at runtime.
1090 class Point2D(TypedDict):
1095 a: Point2D = {'x': 1, 'y': 2, 'label': 'good'} # OK
1096 b: Point2D = {'z': 3, 'label': 'bad'} # Fails type check
1098 assert Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first')
1100 The type info can be accessed via the Point2D.__annotations__ dict, and
1101 the Point2D.__required_keys__ and Point2D.__optional_keys__ frozensets.
1102 TypedDict supports an additional equivalent form::
1104 Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str})
1106 By default, all keys must be present in a TypedDict. It is possible
1107 to override this by specifying totality::
1109 class Point2D(TypedDict, total=False):
1113 This means that a Point2D TypedDict can have any of the keys omitted. A type
1114 checker is only expected to support a literal False or True as the value of
1115 the total argument. True is the default, and makes all items defined in the
1116 class body be required.
1118 The Required and NotRequired special forms can also be used to mark
1119 individual keys as being required or not required::
1121 class Point2D(TypedDict):
1122 x: int # the "x" key must always be present (Required is the default)
1123 y: NotRequired[int] # the "y" key can be omitted
1125 See PEP 655 for more details on Required and NotRequired.
1127 if __fields
is _marker
or __fields
is None:
1128 if __fields
is _marker:
1129 deprecated_thing =
"Failing to pass a value for the 'fields' parameter"
1131 deprecated_thing =
"Passing `None` as the 'fields' parameter"
1133 example = f
"`{__typename} = TypedDict({__typename!r}, {{}})`"
1135 f
"{deprecated_thing} is deprecated and will be disallowed in "
1136 "Python 3.15. To create a TypedDict class with 0 fields "
1137 "using the functional syntax, pass an empty dictionary, e.g. "
1139 warnings.warn(deprecation_msg, DeprecationWarning, stacklevel=2)
1142 raise TypeError(
"TypedDict takes either a dict or keyword arguments,"
1146 "The kwargs-based syntax for TypedDict definitions is deprecated "
1147 "in Python 3.11, will be removed in Python 3.13, and may not be "
1148 "understood by third-party type checkers.",
1153 ns = {
'__annotations__': dict(__fields)}
1155 if module
is not None:
1157 ns[
'__module__'] = module
1163 if hasattr(typing,
"_TypedDictMeta"):
1166 _TYPEDDICT_TYPES = (_TypedDictMeta,)
1169 """Check if an annotation is a TypedDict class
1172 class Film(TypedDict):
1176 is_typeddict(Film) # => True
1177 is_typeddict(Union[list, str]) # => False
1185if hasattr(typing,
"assert_type"):
1190 """Assert (to the type checker) that the value is of the given type.
1192 When the type checker encounters a call to assert_type(), it
1193 emits an error if the value is not of the specified type::
1195 def greet(name: str) -> None:
1196 assert_type(name, str) # ok
1197 assert_type(name, int) # type checker error
1199 At runtime this returns the first argument unchanged and otherwise
1205if hasattr(typing,
"Required"):
1210 """Strips Annotated, Required and NotRequired from a given type."""
1234 """Return type hints for an object.
1236 This is often the same as obj.__annotations__, but it handles
1237 forward references encoded as string literals, adds Optional[t] if a
1238 default value equal to None is set and recursively replaces all
1239 'Annotated[T, ...]', 'Required[T]' or 'NotRequired[T]' with 'T'
1240 (unless 'include_extras=True').
1242 The argument may be a module, class, method, or function. The annotations
1243 are returned as a dictionary. For classes, annotations include also
1246 TypeError is raised if the argument is not of a type that can contain
1247 annotations, and an empty dictionary is returned if no annotations are
1250 BEWARE -- the behavior of globalns and localns is counterintuitive
1251 (unless you are familiar with how eval() and exec() work). The
1252 search order is locals first, then globals.
1254 - If no dict arguments are passed, an attempt is made to use the
1255 globals from obj (or the respective module's globals for classes),
1256 and these are also used as the locals. If the object does not appear
1257 to have globals, an empty dictionary is used.
1259 - If one dict argument is passed, it is used for both globals and
1262 - If two dict arguments are passed, they specify globals and
1263 locals, respectively.
1265 if hasattr(typing,
"Annotated"):
1267 obj, globalns=globalns, localns=localns, include_extras=
True
1277if hasattr(typing,
'Annotated'):
1285 """Runtime representation of an annotated type.
1287 At its core 'Annotated[t, dec1, dec2, ...]' is an alias for the type 't'
1288 with extra annotations. The alias behaves like a normal typing alias,
1289 instantiating is the same as instantiating the underlying type, binding
1290 it to types is also the same.
1300 assert len(params) == 1
1301 new_type = params[0]
1305 return (f
"typing_extensions.Annotated[{typing._type_repr(self.__origin__)}, "
1306 f
"{', '.join(repr(a) for a in self.__metadata__)}]")
1315 return NotImplemented
1324 """Add context specific metadata to a type.
1326 Example: Annotated[int, runtime_check.Unsigned] indicates to the
1327 hypothetical runtime_check module that this type is an unsigned int.
1328 Every other consumer of this type can ignore this metadata and treat
1331 The first argument to Annotated must be a valid type (and will be in
1332 the __origin__ field), the remaining arguments are kept as a tuple in
1333 the __extra__ field.
1337 - It's an error to call `Annotated` with less than two arguments.
1338 - Nested Annotated are flattened::
1340 Annotated[Annotated[T, Ann1, Ann2], Ann3] == Annotated[T, Ann1, Ann2, Ann3]
1342 - Instantiating an annotated type is equivalent to instantiating the
1345 Annotated[C, Ann1](5) == C(5)
1347 - Annotated can be used as a generic type alias::
1349 Optimized = Annotated[T, runtime.Optimize()]
1350 Optimized[int] == Annotated[int, runtime.Optimize()]
1352 OptimizedList = Annotated[List[T], runtime.Optimize()]
1353 OptimizedList[int] == Annotated[List[int], runtime.Optimize()]
1359 raise TypeError(
"Type Annotated cannot be instantiated.")
1364 raise TypeError(
"Annotated[...] should be used "
1365 "with at least two arguments (a type and an "
1367 allowed_special_forms = (ClassVar, Final)
1368 if get_origin(params[0])
in allowed_special_forms:
1371 msg =
"Annotated[t, ...]: t must be a type."
1373 metadata = tuple(params[1:])
1378 f
"Cannot subclass {cls.__module__}.Annotated"
1391 from typing
import _BaseGenericAlias
1396 from typing
import GenericAlias
as _typing_GenericAlias
1401 """Get the unsubscripted version of a type.
1403 This supports generic types, Callable, Tuple, Union, Literal, Final, ClassVar
1404 and Annotated. Return None for unsupported types. Examples::
1406 get_origin(Literal[42]) is Literal
1407 get_origin(int) is None
1408 get_origin(ClassVar[int]) is ClassVar
1409 get_origin(Generic) is Generic
1410 get_origin(Generic[T]) is Generic
1411 get_origin(Union[T, int]) is Union
1412 get_origin(List[Tuple[T, T]][int]) == list
1413 get_origin(P.args) is P
1418 ParamSpecArgs, ParamSpecKwargs)):
1425 """Get type arguments with all substitutions performed.
1427 For unions, basic simplifications used by Union constructor are performed.
1429 get_args(Dict[str, int]) == (str, int)
1431 get_args(Union[int, Union[T, int], str][int]) == (int, str)
1432 get_args(Union[int, Tuple[T, int]][str]) == (int, Tuple[str, int])
1433 get_args(Callable[[], T][int]) == ([], int)
1438 if getattr(tp,
"_special",
False):
1442 res = (list(res[:-1]), res[-1])
1448if hasattr(typing,
'TypeAlias'):
1452 @_ExtensionsSpecialForm
1454 """Special marker indicating that an assignment should
1455 be recognized as a proper type alias definition by type
1460 Predicate: TypeAlias = Callable[..., bool]
1462 It's invalid when used anywhere except as in the example above.
1464 raise TypeError(f
"{self} is not subscriptable")
1469 doc=
"""Special marker indicating that an assignment should
1470 be recognized as a proper type alias definition by type
1475 Predicate: TypeAlias = Callable[..., bool]
1477 It's invalid when used anywhere except as in the example
1486 elif default != _marker:
1495 if def_mod !=
'typing_extensions':
1500 """Mixin for TypeVarLike defaults."""
1503 __init__ = _set_default
1514 """Type variable."""
1519 covariant=False, contravariant=False,
1520 default=_marker, infer_variance=False):
1521 if hasattr(typing,
"TypeAliasType"):
1524 covariant=covariant, contravariant=contravariant,
1525 infer_variance=infer_variance)
1528 covariant=covariant, contravariant=contravariant)
1529 if infer_variance
and (covariant
or contravariant):
1530 raise ValueError(
"Variance cannot be specified with infer_variance.")
1537 raise TypeError(f
"type '{__name__}.TypeVar' is not an acceptable base type")
1541if hasattr(typing,
'ParamSpecArgs'):
1547 """Mixin to indicate that object should not be copied."""
1557 """The args for a ParamSpec object.
1559 Given a ParamSpec object P, P.args is an instance of ParamSpecArgs.
1561 ParamSpecArgs objects have a reference back to their ParamSpec:
1563 P.args.__origin__ is P
1565 This type is meant for runtime introspection and has no special meaning to
1566 static type checkers.
1572 return f
"{self.__origin__.__name__}.args"
1576 return NotImplemented
1580 """The kwargs for a ParamSpec object.
1582 Given a ParamSpec object P, P.kwargs is an instance of ParamSpecKwargs.
1584 ParamSpecKwargs objects have a reference back to their ParamSpec:
1586 P.kwargs.__origin__ is P
1588 This type is meant for runtime introspection and has no special meaning to
1589 static type checkers.
1595 return f
"{self.__origin__.__name__}.kwargs"
1599 return NotImplemented
1603if hasattr(typing,
'ParamSpec'):
1607 """Parameter specification."""
1612 covariant=False, contravariant=False,
1613 infer_variance=False, default=_marker):
1614 if hasattr(typing,
"TypeAliasType"):
1617 covariant=covariant,
1618 contravariant=contravariant,
1619 infer_variance=infer_variance)
1622 covariant=covariant,
1623 contravariant=contravariant)
1631 raise TypeError(f
"type '{__name__}.ParamSpec' is not an acceptable base type")
1638 """Parameter specification variable.
1644 Parameter specification variables exist primarily for the benefit of static
1645 type checkers. They are used to forward the parameter types of one
1646 callable to another callable, a pattern commonly found in higher order
1647 functions and decorators. They are only valid when used in ``Concatenate``,
1648 or s the first argument to ``Callable``. In Python 3.10 and higher,
1649 they are also supported in user-defined Generics at runtime.
1650 See class Generic for more information on generic types. An
1651 example for annotating a decorator::
1656 def add_logging(f: Callable[P, T]) -> Callable[P, T]:
1657 '''A type-safe decorator to add logging to a function.'''
1658 def inner(*args: P.args, **kwargs: P.kwargs) -> T:
1659 logging.info(f'{f.__name__} was called')
1660 return f(*args, **kwargs)
1664 def add_two(x: float, y: float) -> float:
1665 '''Add two numbers together.'''
1668 Parameter specification variables defined with covariant=True or
1669 contravariant=True can be used to declare covariant or contravariant
1670 generic types. These keyword arguments are valid, but their actual semantics
1671 are yet to be decided. See PEP 612 for details.
1673 Parameter specification variables can be introspected. e.g.:
1677 P.__covariant__ == False
1678 P.__contravariant__ == False
1680 Note that only parameter specification variables defined in global scope can
1695 def __init__(self, name, *, bound=None, covariant=False, contravariant=False,
1696 infer_variance=False, default=_marker):
1697 super().__init__([self])
1710 if def_mod !=
'typing_extensions':
1728 return self
is other
1739if not hasattr(typing,
'Concatenate'):
1756 return (f
'{_type_repr(self.__origin__)}'
1757 f
'[{", ".join(_type_repr(arg) for arg in self.__args__)}]')
1767 def __parameters__(self):
1776 if parameters == ():
1777 raise TypeError(
"Cannot take a Concatenate of no types.")
1779 parameters = (parameters,)
1780 if not isinstance(parameters[-1], ParamSpec):
1781 raise TypeError(
"The last parameter to Concatenate should be a "
1782 "ParamSpec variable.")
1783 msg =
"Concatenate[arg, ...]: each arg must be a type."
1789if hasattr(typing,
'Concatenate'):
1794 @_ExtensionsSpecialForm
1796 """Used in conjunction with ``ParamSpec`` and ``Callable`` to represent a
1797 higher order function which adds, removes or transforms parameters of a
1802 Callable[Concatenate[int, P], int]
1804 See PEP 612 for detailed information.
1815 doc=
"""Used in conjunction with ``ParamSpec`` and ``Callable`` to represent a
1816 higher order function which adds, removes or transforms parameters of a
1821 Callable[Concatenate[int, P], int]
1823 See PEP 612 for detailed information.
1827if hasattr(typing,
'TypeGuard'):
1831 @_ExtensionsSpecialForm
1833 """Special typing form used to annotate the return type of a user-defined
1834 type guard function. ``TypeGuard`` only accepts a single type argument.
1835 At runtime, functions marked this way should return a boolean.
1837 ``TypeGuard`` aims to benefit *type narrowing* -- a technique used by static
1838 type checkers to determine a more precise type of an expression within a
1839 program's code flow. Usually type narrowing is done by analyzing
1840 conditional code flow and applying the narrowing to a block of code. The
1841 conditional expression here is sometimes referred to as a "type guard".
1843 Sometimes it would be convenient to use a user-defined boolean function
1844 as a type guard. Such a function should use ``TypeGuard[...]`` as its
1845 return type to alert static type checkers to this intention.
1847 Using ``-> TypeGuard`` tells the static type checker that for a given
1850 1. The return value is a boolean.
1851 2. If the return value is ``True``, the type of its argument
1852 is the type inside ``TypeGuard``.
1856 def is_str(val: Union[str, float]):
1857 # "isinstance" type guard
1858 if isinstance(val, str):
1859 # Type of ``val`` is narrowed to ``str``
1862 # Else, type of ``val`` is narrowed to ``float``.
1865 Strict type narrowing is not enforced -- ``TypeB`` need not be a narrower
1866 form of ``TypeA`` (it can even be a wider form) and this may lead to
1867 type-unsafe results. The main reason is to allow for things like
1868 narrowing ``List[object]`` to ``List[str]`` even though the latter is not
1869 a subtype of the former, since ``List`` is invariant. The responsibility of
1870 writing type-safe type guards is left to the user.
1872 ``TypeGuard`` also works with type variables. For more information, see
1873 PEP 647 (User-Defined Type Guards).
1882 f
'{self._name} accepts only a single type')
1887 doc=
"""Special typing form used to annotate the return type of a user-defined
1888 type guard function. ``TypeGuard`` only accepts a single type argument.
1889 At runtime, functions marked this way should return a boolean.
1891 ``TypeGuard`` aims to benefit *type narrowing* -- a technique used by static
1892 type checkers to determine a more precise type of an expression within a
1893 program's code flow. Usually type narrowing is done by analyzing
1894 conditional code flow and applying the narrowing to a block of code. The
1895 conditional expression here is sometimes referred to as a "type guard".
1897 Sometimes it would be convenient to use a user-defined boolean function
1898 as a type guard. Such a function should use ``TypeGuard[...]`` as its
1899 return type to alert static type checkers to this intention.
1901 Using ``-> TypeGuard`` tells the static type checker that for a given
1904 1. The return value is a boolean.
1905 2. If the return value is ``True``, the type of its argument
1906 is the type inside ``TypeGuard``.
1910 def is_str(val: Union[str, float]):
1911 # "isinstance" type guard
1912 if isinstance(val, str):
1913 # Type of ``val`` is narrowed to ``str``
1916 # Else, type of ``val`` is narrowed to ``float``.
1919 Strict type narrowing is not enforced -- ``TypeB`` need not be a narrower
1920 form of ``TypeA`` (it can even be a wider form) and this may lead to
1921 type-unsafe results. The main reason is to allow for things like
1922 narrowing ``List[object]`` to ``List[str]`` even though the latter is not
1923 a subtype of the former, since ``List`` is invariant. The responsibility of
1924 writing type-safe type guards is left to the user.
1926 ``TypeGuard`` also works with type variables. For more information, see
1927 PEP 647 (User-Defined Type Guards).
1933 __slots__ = (
'_name',
'__doc__',
'_getitem')
1941 if item
in {
'__name__',
'__qualname__'}:
1947 raise TypeError(f
"Cannot subclass {self!r}")
1950 return f
'typing_extensions.{self._name}'
1956 raise TypeError(f
"Cannot instantiate {self!r}")
1965 raise TypeError(f
"{self} cannot be used with isinstance()")
1968 raise TypeError(f
"{self} cannot be used with issubclass()")
1972 return self.
_getitem(self, parameters)
1975if hasattr(typing,
"LiteralString"):
1980 """Represents an arbitrary literal string.
1984 from pip._vendor.typing_extensions import LiteralString
1986 def query(sql: LiteralString) -> ...:
1989 query("SELECT * FROM table") # ok
1990 query(f"SELECT * FROM {input()}") # not ok
1992 See PEP 675 for details.
1995 raise TypeError(f
"{self} is not subscriptable")
2003 """Used to spell the type of "self" in classes.
2007 from typing import Self
2010 def parse(self, data: bytes) -> Self:
2016 raise TypeError(f
"{self} is not subscriptable")
2024 """The bottom type, a type that has no members.
2026 This can be used to define a function that should never be
2027 called, or a function that never returns::
2029 from pip._vendor.typing_extensions import Never
2031 def never_call_me(arg: Never) -> None:
2034 def int_or_str(arg: int | str) -> None:
2035 never_call_me(arg) # type checker error
2038 print("It's an int")
2042 never_call_me(arg) # ok, arg is of type Never
2046 raise TypeError(f
"{self} is not subscriptable")
2049if hasattr(typing,
'Required'):
2053 @_ExtensionsSpecialForm
2055 """A special typing construct to mark a key of a total=False TypedDict
2056 as required. For example:
2058 class Movie(TypedDict, total=False):
2059 title: Required[str]
2063 title='The Matrix', # typechecker error if key is omitted
2067 There is no runtime checking that a required key is actually provided
2068 when instantiating a related TypedDict.
2073 @_ExtensionsSpecialForm
2075 """A special typing construct to mark a key of a TypedDict as
2076 potentially missing. For example:
2078 class Movie(TypedDict):
2080 year: NotRequired[int]
2083 title='The Matrix', # typechecker error if key is omitted
2094 f
'{self._name} accepts only a single type.')
2099 doc=
"""A special typing construct to mark a key of a total=False TypedDict
2100 as required. For example:
2102 class Movie(TypedDict, total=False):
2103 title: Required[str]
2107 title='The Matrix', # typechecker error if key is omitted
2111 There is no runtime checking that a required key is actually provided
2112 when instantiating a related TypedDict.
2116 doc=
"""A special typing construct to mark a key of a TypedDict as
2117 potentially missing. For example:
2119 class Movie(TypedDict):
2121 year: NotRequired[int]
2124 title='The Matrix', # typechecker error if key is omitted
2131Type unpack operator.
2133The type unpack operator takes the child types from some container type,
2134such as `tuple[int, str]` or a `TypeVarTuple`, and 'pulls them out'. For
2137 # For some generic class `Foo`:
2138 Foo[Unpack[tuple[int, str]]] # Equivalent to Foo[int, str]
2140 Ts = TypeVarTuple('Ts')
2141 # Specifies that `Bar` is generic in an arbitrary number of types.
2142 # (Think of `Ts` as a tuple of an arbitrary number of individual
2143 # `TypeVar`s, which the `Unpack` is 'pulling out' directly into the
2145 class Bar(Generic[Unpack[Ts]]): ...
2147 Bar[int, str] # Also valid
2149From Python 3.11, this can also be done using the `*` operator:
2151 Foo[*tuple[int, str]]
2152 class Bar(Generic[*Ts]): ...
2154The operator can also be used along with a `TypedDict` to annotate
2155`**kwargs` in a function signature. For instance:
2157 class Movie(TypedDict):
2161 # This function expects two keyword arguments - *name* of type `str` and
2162 # *year* of type `int`.
2163 def foo(**kwargs: Unpack[Movie]): ...
2165Note that there is only some runtime checking of this operator. Not
2166everything the runtime allows may be accepted by static type checkers.
2168For more information, see PEP 646 and PEP 692.
2202 f
'{self._name} accepts only a single type.')
2211if hasattr(typing,
"TypeVarTuple"):
2215 """Type variable tuple."""
2226 raise TypeError(
"Cannot subclass special typing classes")
2230 """Type variable tuple.
2234 Ts = TypeVarTuple('Ts')
2236 In the same way that a normal type variable is a stand-in for a single
2237 type such as ``int``, a type variable *tuple* is a stand-in for a *tuple*
2238 type such as ``Tuple[int, str]``.
2240 Type variable tuples can be used in ``Generic`` declarations.
2241 Consider the following example::
2243 class Array(Generic[*Ts]): ...
2245 The ``Ts`` type variable tuple here behaves like ``tuple[T1, T2]``,
2246 where ``T1`` and ``T2`` are type variables. To use these type variables
2247 as type parameters of ``Array``, we must *unpack* the type variable tuple using
2248 the star operator: ``*Ts``. The signature of ``Array`` then behaves
2249 as if we had simply written ``class Array(Generic[T1, T2]): ...``.
2250 In contrast to ``Generic[T1, T2]``, however, ``Generic[*Shape]`` allows
2251 us to parameterise the class with an *arbitrary* number of type parameters.
2253 Type variable tuples can be used anywhere a normal ``TypeVar`` can.
2254 This includes class definitions, as shown above, as well as function
2255 signatures and variable annotations::
2257 class Array(Generic[*Ts]):
2259 def __init__(self, shape: Tuple[*Ts]):
2260 self._shape: Tuple[*Ts] = shape
2262 def get_shape(self) -> Tuple[*Ts]:
2265 shape = (Height(480), Width(640))
2266 x: Array[Height, Width] = Array(shape)
2267 y = abs(x) # Inferred type is Array[Height, Width]
2268 z = x + x # ... is Array[Height, Width]
2269 x.get_shape() # ... is tuple[Height, Width]
2279 def __init__(self, name, *, default=_marker):
2285 if def_mod !=
'typing_extensions':
2297 return self
is other
2303 if '_root' not in kwds:
2304 raise TypeError(
"Cannot subclass special typing classes")
2307if hasattr(typing,
"reveal_type"):
2311 """Reveal the inferred type of a variable.
2313 When a static type checker encounters a call to ``reveal_type()``,
2314 it will emit the inferred type of the argument::
2319 Running a static type checker (e.g., ``mypy``) on this example
2320 will produce output similar to 'Revealed type is "builtins.int"'.
2322 At runtime, the function prints the runtime type of the
2323 argument and returns it unchanged.
2326 print(f
"Runtime type is {type(__obj).__name__!r}", file=
sys.stderr)
2330if hasattr(typing,
"assert_never"):
2334 """Assert to the type checker that a line of code is unreachable.
2338 def int_or_str(arg: int | str) -> None:
2341 print("It's an int")
2347 If a type checker finds that a call to assert_never() is
2348 reachable, it will emit an error.
2350 At runtime, this throws an exception when called.
2353 raise AssertionError(
"Expected code to be unreachable")
2362 eq_default: bool =
True,
2363 order_default: bool =
False,
2364 kw_only_default: bool =
False,
2365 frozen_default: bool =
False,
2372 """Decorator that marks a function, class, or metaclass as providing
2373 dataclass-like behavior.
2377 from pip._vendor.typing_extensions import dataclass_transform
2381 # Used on a decorator function
2382 @dataclass_transform()
2383 def create_model(cls: type[_T]) -> type[_T]:
2388 class CustomerModel:
2392 # Used on a base class
2393 @dataclass_transform()
2394 class ModelBase: ...
2396 class CustomerModel(ModelBase):
2400 # Used on a metaclass
2401 @dataclass_transform()
2402 class ModelMeta(type): ...
2404 class ModelBase(metaclass=ModelMeta): ...
2406 class CustomerModel(ModelBase):
2410 Each of the ``CustomerModel`` classes defined in this example will now
2411 behave similarly to a dataclass created with the ``@dataclasses.dataclass``
2412 decorator. For example, the type checker will synthesize an ``__init__``
2415 The arguments to this decorator can be used to customize this behavior:
2416 - ``eq_default`` indicates whether the ``eq`` parameter is assumed to be
2417 True or False if it is omitted by the caller.
2418 - ``order_default`` indicates whether the ``order`` parameter is
2419 assumed to be True or False if it is omitted by the caller.
2420 - ``kw_only_default`` indicates whether the ``kw_only`` parameter is
2421 assumed to be True or False if it is omitted by the caller.
2422 - ``frozen_default`` indicates whether the ``frozen`` parameter is
2423 assumed to be True or False if it is omitted by the caller.
2424 - ``field_specifiers`` specifies a static list of supported classes
2425 or functions that describe fields, similar to ``dataclasses.field()``.
2427 At runtime, this decorator records its arguments in the
2428 ``__dataclass_transform__`` attribute on the decorated object.
2430 See PEP 681 for details.
2435 "eq_default": eq_default,
2436 "order_default": order_default,
2437 "kw_only_default": kw_only_default,
2438 "frozen_default": frozen_default,
2439 "field_specifiers": field_specifiers,
2446if hasattr(typing,
"override"):
2452 """Indicate that a method is intended to override a method in a base class.
2457 def method(self) -> None: ...
2462 def method(self) -> None:
2465 When this decorator is applied to a method, the type checker will
2466 validate that it overrides a method with the same name on a base class.
2467 This helps prevent bugs that may occur when a base class is changed
2468 without an equivalent change to a child class.
2470 There is no runtime checking of these properties. The decorator
2471 sets the ``__override__`` attribute to ``True`` on the decorated object
2472 to allow runtime introspection.
2474 See PEP 698 for details.
2479 except (AttributeError, TypeError):
2487if hasattr(typing,
"deprecated"):
2496 stacklevel: int = 1,
2498 """Indicate that a class, function or overload is deprecated.
2502 @deprecated("Use B instead")
2506 @deprecated("Use g instead")
2511 @deprecated("int support is deprecated")
2512 def g(x: int) -> int: ...
2514 def g(x: str) -> int: ...
2516 When this decorator is applied to an object, the type checker
2517 will generate a diagnostic on usage of the deprecated object.
2519 The warning specified by ``category`` will be emitted on use
2520 of deprecated objects. For functions, that happens on calls;
2521 for classes, on instantiation. If the ``category`` is ``None``,
2522 no warning is emitted. The ``stacklevel`` determines where the
2523 warning is emitted. If it is ``1`` (the default), the warning
2524 is emitted at the direct caller of the deprecated object; if it
2525 is higher, it is emitted further up the stack.
2527 The decorator sets the ``__deprecated__``
2528 attribute on the decorated object to the deprecation message
2529 passed to the decorator. If applied to an overload, the decorator
2530 must be after the ``@overload`` decorator for the attribute to
2531 exist on the overload as returned by ``get_overloads()``.
2533 See PEP 702 for details.
2537 if category
is None:
2544 @functools.wraps(original_new)
2545 def __new__(cls, *args, **kwargs):
2546 warnings.warn(__msg, category=category, stacklevel=stacklevel + 1)
2550 elif not has_init
and (args
or kwargs):
2551 raise TypeError(f
"{cls.__name__}() takes no arguments")
2558 elif callable(__arg):
2559 @functools.wraps(__arg)
2560 def wrapper(*args, **kwargs):
2561 warnings.warn(__msg, category=category, stacklevel=stacklevel + 1)
2562 return __arg(*args, **kwargs)
2568 "@deprecated decorator with non-None category must be applied to "
2569 f
"a class or callable, not {__arg!r}"
2582if not hasattr(typing,
"TypeVarTuple"):
2596 fields = [n
for n, t
in types]
2600 defaults=defaults, module=module)
2609 _special_namedtuple_fields =
frozenset({
'__module__',
'__name__',
'__annotations__'})
2613 assert _NamedTuple
in bases
2617 'can only inherit from a NamedTuple type and Generic')
2618 bases = tuple(tuple
if base
is _NamedTuple
else base
for base
in bases)
2619 types =
ns.get(
'__annotations__', {})
2621 for field_name
in types:
2622 if field_name
in ns:
2625 raise TypeError(f
"Non-default namedtuple field {field_name} "
2626 f
"cannot follow default field"
2627 f
"{'s' if len(default_names) > 1 else ''} "
2628 f
"{', '.join(default_names)}")
2631 defaults=[ns[n]
for n
in default_names],
2632 module=ns[
'__module__']
2636 if hasattr(typing,
'_generic_class_getitem'):
2643 if key
in _prohibited_namedtuple_fields:
2644 raise AttributeError(
"Cannot overwrite NamedTuple attribute " + key)
2645 elif key
not in _special_namedtuple_fields
and key
not in nm_tpl._fields:
2654 assert NamedTuple
in bases
2655 return (_NamedTuple,)
2657 @_ensure_subclassable(_namedtuple_mro_entries)
2659 """Typed version of namedtuple.
2663 class Employee(NamedTuple):
2667 This is equivalent to::
2669 Employee = collections.namedtuple('Employee', ['name', 'id'])
2671 The resulting class has an extra __annotations__ attribute, giving a
2672 dict that maps field names to types. (The field names are also in
2673 the _fields attribute, which is part of the namedtuple API.)
2674 An alternative equivalent functional syntax is also accepted::
2676 Employee = NamedTuple('Employee', [('name', str), ('id', int)])
2678 if __fields
is _marker:
2680 deprecated_thing =
"Creating NamedTuple classes using keyword arguments"
2682 "{name} is deprecated and will be disallowed in Python {remove}. "
2683 "Use the class-based or functional syntax instead."
2686 deprecated_thing =
"Failing to pass a value for the 'fields' parameter"
2687 example = f
"`{__typename} = NamedTuple({__typename!r}, [])`"
2689 "{name} is deprecated and will be disallowed in Python {remove}. "
2690 "To create a NamedTuple class with 0 fields "
2691 "using the functional syntax, "
2692 "pass an empty list, e.g. "
2694 elif __fields
is None:
2697 "Cannot pass `None` as the 'fields' parameter "
2698 "and also specify fields using keyword arguments"
2701 deprecated_thing =
"Passing `None` as the 'fields' parameter"
2702 example = f
"`{__typename} = NamedTuple({__typename!r}, [])`"
2704 "{name} is deprecated and will be disallowed in Python {remove}. "
2705 "To create a NamedTuple class with 0 fields "
2706 "using the functional syntax, "
2707 "pass an empty list, e.g. "
2710 raise TypeError(
"Either list of fields or keywords"
2711 " can be provided to NamedTuple, not both")
2712 if __fields
is _marker
or __fields
is None:
2727 _new_signature =
'(typename, fields=None, /, **kwargs)'
2738 """Base class for classes that implement the buffer protocol.
2740 The buffer protocol allows Python objects to expose a low-level
2741 memory buffer interface. Before Python 3.12, it is not possible
2742 to implement the buffer protocol in pure Python code, or even
2743 to check whether a class implements the buffer protocol. In
2744 Python 3.12 and higher, the ``__buffer__`` method allows access
2745 to the buffer protocol from Python code, and the
2746 ``collections.abc.Buffer`` ABC allows checking whether a class
2747 implements the buffer protocol.
2749 To indicate support for the buffer protocol in earlier versions,
2750 inherit from this ABC, either in a stub file or at runtime,
2751 or use ABC registration. This ABC provides no methods, because
2752 there is no Python-accessible methods shared by pre-3.12 buffer
2753 classes. It is useful primarily for static checks.
2764if hasattr(_types,
"get_original_bases"):
2768 """Return the class's "original" bases prior to modification by `__mro_entries__`.
2772 from typing import TypeVar, Generic
2773 from pip._vendor.typing_extensions import NamedTuple, TypedDict
2776 class Foo(Generic[T]): ...
2777 class Bar(Foo[int], float): ...
2778 class Baz(list[str]): ...
2779 Eggs = NamedTuple("Eggs", [("a", int), ("b", str)])
2780 Spam = TypedDict("Spam", {"a": int, "b": str})
2782 assert get_original_bases(Bar) == (Foo[int], float)
2783 assert get_original_bases(Baz) == (list[str],)
2784 assert get_original_bases(Eggs) == (NamedTuple,)
2785 assert get_original_bases(Spam) == (TypedDict,)
2786 assert get_original_bases(int) == (object,)
2790 except AttributeError:
2793 except AttributeError:
2795 f
'Expected an instance of type, not {type(__cls).__name__!r}'
2805 """NewType creates simple unique types with almost zero
2806 runtime overhead. NewType(name, tp) is considered a subtype of tp
2807 by static type checkers. At runtime, NewType(name, tp) returns
2808 a dummy callable that simply returns its argument. Usage::
2809 UserId = NewType('UserId', int)
2810 def name_by_id(user_id: UserId) -> str:
2812 UserId('user') # Fails type check
2813 name_by_id(42) # Fails type check
2814 name_by_id(UserId(42)) # OK
2815 num = UserId(5) + 1 # type: int
2828 if def_mod !=
'typing_extensions':
2837 def __init_subclass__(cls):
2840 f
"Cannot subclass an instance of NewType. "
2841 f
"Perhaps you were looking for: "
2842 f
"`{subcls_name} = NewType({subcls_name!r}, {supercls_name})`"
2848 return f
'{self.__module__}.{self.__qualname__}'
2864if hasattr(typing,
"TypeAliasType"):
2868 """Corresponds to is_unionable() in unionobject.c in CPython."""
2877 """Create named, parameterized type aliases.
2879 This provides a backport of the new `type` statement in Python 3.12:
2881 type ListOrSet[T] = list[T] | set[T]
2886 ListOrSet = TypeAliasType("ListOrSet", list[T] | set[T], type_params=(T,))
2888 The name ListOrSet can then be used as an alias for the type it refers to.
2890 The type_params argument should contain all the type parameters used
2891 in the value of the type alias. If the alias is not generic, this
2892 argument is omitted.
2894 Static type checkers should only support type aliases declared using
2895 TypeAliasType that follow these rules:
2897 - The first argument (the name) must be a string literal.
2898 - The TypeAliasType instance must be immediately assigned to a variable
2899 of the same name. (For example, 'X = TypeAliasType("Y", int)' is invalid,
2900 as is 'X, Y = TypeAliasType("X", int), TypeAliasType("Y", int)').
2904 def __init__(self, name: str, value, *, type_params=()):
2906 raise TypeError(
"TypeAliasType name must be a string")
2911 for type_param
in type_params:
2918 if def_mod !=
'typing_extensions':
2933 if name ==
"__name__":
2935 elif name
in {
"__value__",
"__type_params__",
"__parameters__",
"__module__"}:
2937 f
"attribute '{name}' of 'typing.TypeAliasType' objects "
2942 f
"'typing.TypeAliasType' object has no attribute '{name}'"
2950 parameters = (parameters,)
2953 item, f
'Subscripting {self.__name__} requires a type.'
2955 for item
in parameters
2964 "type 'typing_extensions.TypeAliasType' is not an acceptable base type"
2970 raise TypeError(
"Type alias is not callable")
2977 return NotImplemented
2982 return NotImplemented
2986if hasattr(typing,
"is_protocol"):
2991 """Return True if the given type is a Protocol.
2995 >>> from typing_extensions import Protocol, is_protocol
2996 >>> class P(Protocol):
2997 ... def a(self) -> str: ...
3001 >>> is_protocol(int)
3006 and getattr(__tp,
'_is_protocol',
False)
3007 and __tp
is not Protocol
3008 and __tp
is not getattr(typing,
"Protocol", object())
3012 """Return the set of members defined in a Protocol.
3016 >>> from typing_extensions import Protocol, get_protocol_members
3017 >>> class P(Protocol):
3018 ... def a(self) -> str: ...
3020 >>> get_protocol_members(P)
3021 frozenset({'a', 'b'})
3023 Raise a TypeError for arguments that are not Protocols.
3026 raise TypeError(f
'{__tp!r} is not a Protocol')
3027 if hasattr(__tp,
'__protocol_attrs__'):
__init_subclass__(cls, *args, **kwargs)
__new__(cls, *args, **kwargs)
__class_getitem__(cls, params)
__new__(cls, *args, **kwargs)
__mro_entries__(self, bases)
__call__(self, *args, **kwargs)
None __init_subclass__(cls)
__new__(cls, name, *bound=None, covariant=False, contravariant=False, infer_variance=False, default=_marker)
__init_subclass__(cls, *args, **kwargs)
__new__(cls, *args, **kwds)
__class_getitem__(cls, params)
complex __complex__(self)
T_co __round__(self, int ndigits=0)
__init_subclass__(cls, *args, **kwargs)
__init__(self, str name, value, *type_params=())
Never _raise_attribute_error(self, str name)
None __setattr__(self, str __name, object __value)
Never __delattr__(self, str __name)
__getitem__(self, parameters)
__new__(cls, name, *default=_marker)
__init_subclass__(self, *args, **kwds)
__new__(cls, name, *constraints, bound=None, covariant=False, contravariant=False, default=_marker, infer_variance=False)
None __init_subclass__(cls)
__init__(self, origin, metadata)
__call__(self, *args, **kwargs)
__init__(self, origin, args)
_maybe_adjust_parameters(cls)
_allow_reckless_class_checks(depth=3)
_set_default(type_param, default)
_namedtuple_mro_entries(bases)
_flatten_literal_params(parameters)
_should_collect_from_parameters(t)
_no_init(self, *args, **kwargs)
_concatenate_getitem(self, parameters)
_value_and_type_iter(params)
_ensure_subclassable(mro_entries)
_make_nmtuple(name, types, module, defaults=())