Let us walk on the 3-isogeny graph
Loading...
Searching...
No Matches
pip._vendor.typing_extensions Namespace Reference

Data Structures

class  _AnnotatedAlias
 
class  _AnyMeta
 
class  _ConcatenateForm
 
class  _ConcatenateGenericAlias
 
class  _DefaultMixin
 
class  _ExtensionsSpecialForm
 
class  _FinalForm
 
class  _Immutable
 
class  _LiteralForm
 
class  _LiteralGenericAlias
 
class  _NamedTupleMeta
 
class  _ProtocolMeta
 
class  _RequiredForm
 
class  _Sentinel
 
class  _SpecialForm
 
class  _TypedDictMeta
 
class  _TypeGuardForm
 
class  _TypeVarLikeMeta
 
class  _UnpackAlias
 
class  _UnpackForm
 
class  _UnpackSpecialForm
 
class  Annotated
 
class  Any
 
class  Buffer
 
class  NewType
 
class  ParamSpec
 
class  ParamSpecArgs
 
class  ParamSpecKwargs
 
class  Protocol
 
class  SupportsAbs
 
class  SupportsBytes
 
class  SupportsComplex
 
class  SupportsFloat
 
class  SupportsIndex
 
class  SupportsInt
 
class  SupportsRound
 
class  TypeAliasType
 
class  TypeVar
 
class  TypeVarTuple
 

Functions

 _check_generic (cls, parameters, elen=_marker)
 
 _should_collect_from_parameters (t)
 
 _collect_type_vars (types, typevar_types=None)
 
 final (f)
 
 IntVar (name)
 
 _flatten_literal_params (parameters)
 
 _value_and_type_iter (params)
 
 overload (func)
 
 get_overloads (func)
 
 _get_protocol_attrs (cls)
 
 _maybe_adjust_parameters (cls)
 
 _caller (depth=2)
 
 _allow_reckless_class_checks (depth=3)
 
 _no_init (self, *args, **kwargs)
 
 _proto_hook (cls, other)
 
 runtime_checkable (cls)
 
 _ensure_subclassable (mro_entries)
 
 TypedDict (__typename, __fields=_marker, *total=True, **kwargs)
 
 is_typeddict (tp)
 
 assert_type (__val, __typ)
 
 _strip_extras (t)
 
 get_type_hints (obj, globalns=None, localns=None, include_extras=False)
 
 get_origin (tp)
 
 get_args (tp)
 
 TypeAlias (self, parameters)
 
 _set_default (type_param, default)
 
 _set_module (typevarlike)
 
 _concatenate_getitem (self, parameters)
 
 Concatenate (self, parameters)
 
 TypeGuard (self, parameters)
 
 LiteralString (self, params)
 
 Self (self, params)
 
 Never (self, params)
 
 Required (self, parameters)
 
 NotRequired (self, parameters)
 
 _is_unpack (obj)
 
 Unpack (self, parameters)
 
T reveal_type (T __obj)
 
Never assert_never (Never __arg)
 
typing.Callable[[T], Tdataclass_transform (*bool eq_default=True, bool order_default=False, bool kw_only_default=False, bool frozen_default=False, typing.Tuple[typing.Union[typing.Type[typing.Any], typing.Callable[..., typing.Any]],...] field_specifiers=(), **typing.Any kwargs)
 
_F override (_F __arg)
 
typing.Callable[[_T], _Tdeprecated (str __msg, *typing.Optional[typing.Type[Warning]] category=DeprecationWarning, int stacklevel=1)
 
 _make_nmtuple (name, types, module, defaults=())
 
 _namedtuple_mro_entries (bases)
 
 NamedTuple (__typename, __fields=_marker, **kwargs)
 
 get_original_bases (__cls)
 
 _is_unionable (obj)
 
bool is_protocol (type __tp)
 
typing.FrozenSet[str] get_protocol_members (type __tp)
 

Variables

bool PEP_560 = True
 
 GenericMeta = type
 
 _marker = _Sentinel()
 
 NoReturn = typing.NoReturn
 
 T = typing.TypeVar('T')
 
 KT = typing.TypeVar('KT')
 
 VT = typing.TypeVar('VT')
 
 T_co = typing.TypeVar('T_co', covariant=True)
 
 T_contra = typing.TypeVar('T_contra', contravariant=True)
 
 ClassVar = typing.ClassVar
 
 Final = typing.Final
 
 doc
 
 final = typing.final
 
 Literal = typing.Literal
 
 _overload_dummy = typing._overload_dummy
 
 overload = typing.overload
 
 get_overloads = typing.get_overloads
 
 clear_overloads = typing.clear_overloads
 
 _overload_registry
 
 Type = typing.Type
 
 Awaitable = typing.Awaitable
 
 Coroutine = typing.Coroutine
 
 AsyncIterable = typing.AsyncIterable
 
 AsyncIterator = typing.AsyncIterator
 
 Deque = typing.Deque
 
 ContextManager = typing.ContextManager
 
 AsyncContextManager = typing.AsyncContextManager
 
 DefaultDict = typing.DefaultDict
 
 OrderedDict = typing.OrderedDict
 
 Counter = typing.Counter
 
 ChainMap = typing.ChainMap
 
 AsyncGenerator = typing.AsyncGenerator
 
 Text = typing.Text
 
 TYPE_CHECKING = typing.TYPE_CHECKING
 
dict _PROTO_ALLOWLIST
 
dict _EXCLUDED_ATTRS
 
 Protocol = typing.Protocol
 
 _typing_Protocol = typing.Protocol
 
 _ProtocolMetaBase = type(_typing_Protocol)
 
 runtime_checkable = typing.runtime_checkable
 
 runtime = runtime_checkable
 
 SupportsInt = typing.SupportsInt
 
 SupportsFloat = typing.SupportsFloat
 
 SupportsComplex = typing.SupportsComplex
 
 SupportsBytes = typing.SupportsBytes
 
 SupportsIndex = typing.SupportsIndex
 
 SupportsAbs = typing.SupportsAbs
 
 SupportsRound = typing.SupportsRound
 
 TypedDict = typing.TypedDict
 
 _TypedDictMeta = typing._TypedDictMeta
 
 is_typeddict = typing.is_typeddict
 
str _TAKES_MODULE = "module" in inspect.signature(typing._type_check).parameters
 
str _fake_name = "Protocol"
 
 _TypedDict
 
tuple _TYPEDDICT_TYPES = (typing._TypedDictMeta, _TypedDictMeta)
 
 assert_type = typing.assert_type
 
 get_type_hints = typing.get_type_hints
 
 Annotated = typing.Annotated
 
 _AnnotatedAlias = typing._AnnotatedAlias
 
 get_origin = typing.get_origin
 
 get_args = typing.get_args
 
 _BaseGenericAlias = typing._GenericAlias
 
 _typing_GenericAlias = typing._GenericAlias
 
 TypeAlias = typing.TypeAlias
 
 ParamSpecArgs = typing.ParamSpecArgs
 
 ParamSpecKwargs = typing.ParamSpecKwargs
 
 Concatenate = typing.Concatenate
 
 _ConcatenateGenericAlias = typing._ConcatenateGenericAlias
 
 TypeGuard = typing.TypeGuard
 
 LiteralString = typing.LiteralString
 
 Self = typing.Self
 
 Never = typing.Never
 
 Required = typing.Required
 
 NotRequired = typing.NotRequired
 
str _UNPACK_DOC
 
 Unpack = typing.Unpack
 
 reveal_type = typing.reveal_type
 
 assert_never = typing.assert_never
 
 dataclass_transform = typing.dataclass_transform
 
 override = typing.override
 
 _F = typing.TypeVar("_F", bound=typing.Callable[..., typing.Any])
 
 deprecated = typing.deprecated
 
 _T = typing.TypeVar("_T")
 
 _collect_type_vars
 
 _check_generic
 
 NamedTuple = typing.NamedTuple
 
 _prohibited_namedtuple_fields = typing._prohibited
 
 _special_namedtuple_fields = frozenset({'__module__', '__name__', '__annotations__'})
 
 _NamedTuple
 
str _new_signature = '(typename, fields=None, /, **kwargs)'
 
 Buffer = collections.abc.Buffer
 
 get_original_bases = _types.get_original_bases
 
 NewType = typing.NewType
 
 TypeAliasType = typing.TypeAliasType
 
 is_protocol = typing.is_protocol
 
 get_protocol_members = typing.get_protocol_members
 
 AbstractSet = typing.AbstractSet
 
 AnyStr = typing.AnyStr
 
 BinaryIO = typing.BinaryIO
 
 Callable = typing.Callable
 
 Collection = typing.Collection
 
 Container = typing.Container
 
 Dict = typing.Dict
 
 ForwardRef = typing.ForwardRef
 
 FrozenSet = typing.FrozenSet
 
 Generator = typing.Generator
 
 Generic = typing.Generic
 
 Hashable = typing.Hashable
 
 IO = typing.IO
 
 ItemsView = typing.ItemsView
 
 Iterable = typing.Iterable
 
 Iterator = typing.Iterator
 
 KeysView = typing.KeysView
 
 List = typing.List
 
 Mapping = typing.Mapping
 
 MappingView = typing.MappingView
 
 Match = typing.Match
 
 MutableMapping = typing.MutableMapping
 
 MutableSequence = typing.MutableSequence
 
 MutableSet = typing.MutableSet
 
 Optional = typing.Optional
 
 Pattern = typing.Pattern
 
 Reversible = typing.Reversible
 
 Sequence = typing.Sequence
 
 Set = typing.Set
 
 Sized = typing.Sized
 
 TextIO = typing.TextIO
 
 Tuple = typing.Tuple
 
 Union = typing.Union
 
 ValuesView = typing.ValuesView
 
 cast = typing.cast
 
 no_type_check = typing.no_type_check
 
 no_type_check_decorator = typing.no_type_check_decorator
 
 _is_runtime_protocol
 

Function Documentation

◆ _allow_reckless_class_checks()

_allow_reckless_class_checks (   depth = 3)
protected
Allow instance and class checks for special stdlib modules.
The abc and functools modules indiscriminately call isinstance() and
issubclass() on the whole MRO of a user class, which may contain protocols.

Definition at line 590 of file typing_extensions.py.

590 def _allow_reckless_class_checks(depth=3):
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.
594 """
595 return _caller(depth) in {'abc', 'functools', None}
596

References pip._vendor.typing_extensions._caller().

Referenced by _ProtocolMeta.__instancecheck__(), and _ProtocolMeta.__subclasscheck__().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ _caller()

_caller (   depth = 2)
protected

Definition at line 578 of file typing_extensions.py.

578def _caller(depth=2):
579 try:
580 return sys._getframe(depth).f_globals.get('__name__', '__main__')
581 except (AttributeError, ValueError): # For platforms without _getframe()
582 return None
583
584
585# The performance of runtime-checkable protocols is significantly improved on Python 3.12,
586# so we backport the 3.12 version of Protocol to Python <=3.11
for i

References i.

Referenced by ParamSpec.__init__(), TypeVarTuple.__init__(), NewType.__init__(), TypeAliasType.__init__(), pip._vendor.typing_extensions._allow_reckless_class_checks(), pip._vendor.typing_extensions._set_module(), pip._vendor.typing_extensions.NamedTuple(), and pip._vendor.typing_extensions.TypedDict().

Here is the caller graph for this function:

◆ _check_generic()

_check_generic (   cls,
  parameters,
  elen = _marker 
)
protected
Check correct count for parameters of a generic cls (internal helper).
This gives a nice error message in case of count mismatch.

Definition at line 147 of file typing_extensions.py.

147def _check_generic(cls, parameters, elen=_marker):
148 """Check correct count for parameters of a generic cls (internal helper).
149 This gives a nice error message in case of count mismatch.
150 """
151 if not elen:
152 raise TypeError(f"{cls} is not a generic class")
153 if elen is _marker:
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)
158 if alen != elen:
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):
163 return
164 raise TypeError(f"Too {'many' if alen > elen else 'few'} parameters for {cls};"
165 f" actual {alen}, expected {elen}")
166
167

References pip._vendor.typing_extensions._is_unpack(), and i.

Here is the call graph for this function:

◆ _collect_type_vars()

_collect_type_vars (   types,
  typevar_types = None 
)
protected
Collect all type variable contained in types in order of
first appearance (lexicographic order). For example::

    _collect_type_vars((T, List[S, T])) == (T, S)

Definition at line 181 of file typing_extensions.py.

181def _collect_type_vars(types, typevar_types=None):
182 """Collect all type variable contained in types in order of
183 first appearance (lexicographic order). For example::
184
185 _collect_type_vars((T, List[S, T])) == (T, S)
186 """
187 if typevar_types is None:
188 typevar_types = typing.TypeVar
189 tvars = []
190 for t in types:
191 if (
192 isinstance(t, typevar_types) and
193 t not in tvars and
194 not _is_unpack(t)
195 ):
196 tvars.append(t)
197 if _should_collect_from_parameters(t):
198 tvars.extend([t for t in t.__parameters__ if t not in tvars])
199 return tuple(tvars)
200
201

References pip._vendor.typing_extensions._is_unpack(), pip._vendor.typing_extensions._should_collect_from_parameters(), and i.

Here is the call graph for this function:

◆ _concatenate_getitem()

_concatenate_getitem (   self,
  parameters 
)
protected

Definition at line 1775 of file typing_extensions.py.

1775def _concatenate_getitem(self, parameters):
1776 if parameters == ():
1777 raise TypeError("Cannot take a Concatenate of no types.")
1778 if not isinstance(parameters, tuple):
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."
1784 parameters = tuple(typing._type_check(p, msg) for p in parameters)
1785 return _ConcatenateGenericAlias(self, parameters)
1786
1787
1788# 3.10+

References i.

Referenced by _ConcatenateForm.__getitem__(), and pip._vendor.typing_extensions.Concatenate().

Here is the caller graph for this function:

◆ _ensure_subclassable()

_ensure_subclassable (   mro_entries)
protected

Definition at line 956 of file typing_extensions.py.

956def _ensure_subclassable(mro_entries):
957 def inner(func):
958 if sys.implementation.name == "pypy" and sys.version_info < (3, 9):
959 cls_dict = {
960 "__call__": staticmethod(func),
961 "__mro_entries__": staticmethod(mro_entries)
962 }
963 t = type(func.__name__, (), cls_dict)
964 return functools.update_wrapper(t(), func)
965 else:
966 func.__mro_entries__ = mro_entries
967 return func
968 return inner
969
970

References i.

◆ _flatten_literal_params()

_flatten_literal_params (   parameters)
protected
An internal helper for Literal creation: flatten Literals among parameters

Definition at line 324 of file typing_extensions.py.

324 def _flatten_literal_params(parameters):
325 """An internal helper for Literal creation: flatten Literals among parameters"""
326 params = []
327 for p in parameters:
328 if isinstance(p, _LiteralGenericAlias):
330 else:
332 return tuple(params)
333

References i.

Referenced by _LiteralForm.__getitem__().

Here is the caller graph for this function:

◆ _get_protocol_attrs()

_get_protocol_attrs (   cls)
protected

Definition at line 526 of file typing_extensions.py.

526def _get_protocol_attrs(cls):
527 attrs = set()
528 for base in cls.__mro__[:-1]: # without object
529 if base.__name__ in {'Protocol', 'Generic'}:
530 continue
531 annotations = getattr(base, '__annotations__', {})
532 for attr in (*base.__dict__, *annotations):
533 if (not attr.startswith('_abc_') and attr not in _EXCLUDED_ATTRS):
534 attrs.add(attr)
535 return attrs
536
537

References i.

Referenced by _ProtocolMeta.__init__(), and pip._vendor.typing_extensions.get_protocol_members().

Here is the caller graph for this function:

◆ _is_unionable()

_is_unionable (   obj)
protected
Corresponds to is_unionable() in unionobject.c in CPython.

Definition at line 2867 of file typing_extensions.py.

2867 def _is_unionable(obj):
2868 """Corresponds to is_unionable() in unionobject.c in CPython."""
2869 return obj is None or isinstance(obj, (
2870 type,
2873 TypeAliasType,
2874 ))
2875

References i.

Referenced by TypeAliasType.__or__(), and TypeAliasType.__ror__().

Here is the caller graph for this function:

◆ _is_unpack()

_is_unpack (   obj)
protected

Definition at line 2175 of file typing_extensions.py.

2175 def _is_unpack(obj):
2176 return get_origin(obj) is Unpack
2177

References pip._vendor.typing_extensions.get_origin, and i.

Referenced by pip._vendor.typing_extensions._check_generic(), and pip._vendor.typing_extensions._collect_type_vars().

Here is the caller graph for this function:

◆ _make_nmtuple()

_make_nmtuple (   name,
  types,
  module,
  defaults = () 
)
protected

Definition at line 2595 of file typing_extensions.py.

2595 def _make_nmtuple(name, types, module, defaults=()):
2596 fields = [n for n, t in types]
2597 annotations = {n: typing._type_check(t, f"field {n} annotation must be a type")
2598 for n, t in types}
2599 nm_tpl = collections.namedtuple(name, fields,
2600 defaults=defaults, module=module)
2602 # The `_field_types` attribute was removed in 3.9;
2603 # in earlier versions, it is the same as the `__annotations__` attribute
2604 if sys.version_info < (3, 9):
2605 nm_tpl._field_types = annotations
2606 return nm_tpl
2607

References i.

Referenced by _NamedTupleMeta.__new__(), and pip._vendor.typing_extensions.NamedTuple().

Here is the caller graph for this function:

◆ _maybe_adjust_parameters()

_maybe_adjust_parameters (   cls)
protected
Helper function used in Protocol.__init_subclass__ and _TypedDictMeta.__new__.

The contents of this function are very similar
to logic found in typing.Generic.__init_subclass__
on the CPython main branch.

Definition at line 538 of file typing_extensions.py.

538def _maybe_adjust_parameters(cls):
539 """Helper function used in Protocol.__init_subclass__ and _TypedDictMeta.__new__.
540
541 The contents of this function are very similar
542 to logic found in typing.Generic.__init_subclass__
543 on the CPython main branch.
544 """
545 tvars = []
546 if '__orig_bases__' in cls.__dict__:
547 tvars = _collect_type_vars(cls.__orig_bases__)
548 # Look for Generic[T1, ..., Tn] or Protocol[T1, ..., Tn].
549 # If found, tvars must be a subset of it.
550 # If not found, tvars is it.
551 # Also check for and reject plain Generic,
552 # and reject multiple Generic[...] and/or Protocol[...].
553 gvars = None
554 for base in cls.__orig_bases__:
555 if (isinstance(base, typing._GenericAlias) and
556 base.__origin__ in (typing.Generic, Protocol)):
557 # for error messages
558 the_base = base.__origin__.__name__
559 if gvars is not None:
560 raise TypeError(
561 "Cannot inherit from Generic[...]"
562 " and/or Protocol[...] multiple types.")
563 gvars = base.__parameters__
564 if gvars is None:
565 gvars = tvars
566 else:
567 tvarset = set(tvars)
568 gvarset = set(gvars)
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}]")
574 tvars = gvars
575 cls.__parameters__ = tuple(tvars)
576
577

References pip._vendor.typing_extensions._collect_type_vars, and i.

Referenced by Protocol.__init_subclass__().

Here is the caller graph for this function:

◆ _namedtuple_mro_entries()

_namedtuple_mro_entries (   bases)
protected

Definition at line 2653 of file typing_extensions.py.

2653 def _namedtuple_mro_entries(bases):
2654 assert NamedTuple in bases
2655 return (_NamedTuple,)
2656

◆ _no_init()

_no_init (   self,
args,
**  kwargs 
)
protected

Definition at line 597 of file typing_extensions.py.

597 def _no_init(self, *args, **kwargs):
598 if type(self)._is_protocol:
599 raise TypeError('Protocols cannot be instantiated')
600

References i.

◆ _proto_hook()

_proto_hook (   cls,
  other 
)
protected

Definition at line 716 of file typing_extensions.py.

716 def _proto_hook(cls, other):
717 if not cls.__dict__.get('_is_protocol', False):
718 return NotImplemented
719
720 for attr in cls.__protocol_attrs__:
721 for base in other.__mro__:
722 # Check if the members appears in the class dictionary...
723 if attr in base.__dict__:
724 if base.__dict__[attr] is None:
725 return NotImplemented
726 break
727
728 # ...or in annotations, if it is a sub-protocol.
729 annotations = getattr(base, '__annotations__', {})
730 if (
732 and attr in annotations
733 and is_protocol(other)
734 ):
735 break
736 else:
737 return NotImplemented
738 return True
739

References i, and pip._vendor.typing_extensions.is_protocol.

◆ _set_default()

_set_default (   type_param,
  default 
)
protected

Definition at line 1482 of file typing_extensions.py.

1482def _set_default(type_param, default):
1483 if isinstance(default, (tuple, list)):
1484 type_param.__default__ = tuple((typing._type_check(d, "Default must be a type")
1485 for d in default))
1486 elif default != _marker:
1487 type_param.__default__ = typing._type_check(default, "Default must be a type")
1488 else:
1490
1491

References i.

Referenced by ParamSpec.__new__(), TypeVar.__new__(), and TypeVarTuple.__new__().

Here is the caller graph for this function:

◆ _set_module()

_set_module (   typevarlike)
protected

Definition at line 1492 of file typing_extensions.py.

1492def _set_module(typevarlike):
1493 # for pickling:
1494 def_mod = _caller(depth=3)
1495 if def_mod != 'typing_extensions':
1496 typevarlike.__module__ = def_mod
1497
1498

References pip._vendor.typing_extensions._caller(), and i.

Referenced by ParamSpec.__new__(), TypeVar.__new__(), and TypeVarTuple.__new__().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ _should_collect_from_parameters()

_should_collect_from_parameters (   t)
protected

Definition at line 169 of file typing_extensions.py.

169 def _should_collect_from_parameters(t):
170 return isinstance(
172 )

References i.

Referenced by pip._vendor.typing_extensions._collect_type_vars().

Here is the caller graph for this function:

◆ _strip_extras()

_strip_extras (   t)
protected
Strips Annotated, Required and NotRequired from a given type.

Definition at line 1209 of file typing_extensions.py.

1209 def _strip_extras(t):
1210 """Strips Annotated, Required and NotRequired from a given type."""
1211 if isinstance(t, _AnnotatedAlias):
1212 return _strip_extras(t.__origin__)
1213 if hasattr(t, "__origin__") and t.__origin__ in (Required, NotRequired):
1214 return _strip_extras(t.__args__[0])
1216 stripped_args = tuple(_strip_extras(a) for a in t.__args__)
1217 if stripped_args == t.__args__:
1218 return t
1219 return t.copy_with(stripped_args)
1220 if hasattr(_types, "GenericAlias") and isinstance(t, _types.GenericAlias):
1221 stripped_args = tuple(_strip_extras(a) for a in t.__args__)
1222 if stripped_args == t.__args__:
1223 return t
1224 return _types.GenericAlias(t.__origin__, stripped_args)
1225 if hasattr(_types, "UnionType") and isinstance(t, _types.UnionType):
1226 stripped_args = tuple(_strip_extras(a) for a in t.__args__)
1227 if stripped_args == t.__args__:
1228 return t
1229 return functools.reduce(operator.or_, stripped_args)
1230
1231 return t
1232

References pip._vendor.typing_extensions._strip_extras(), and i.

Referenced by pip._vendor.typing_extensions._strip_extras(), and pip._vendor.typing_extensions.get_type_hints().

Here is the call graph for this function:
Here is the caller graph for this function:

◆ _value_and_type_iter()

_value_and_type_iter (   params)
protected

Definition at line 334 of file typing_extensions.py.

334 def _value_and_type_iter(params):
335 for p in params:
336 yield p, type(p)
337

Referenced by _LiteralGenericAlias.__eq__(), _LiteralForm.__getitem__(), and _LiteralGenericAlias.__hash__().

Here is the caller graph for this function:

◆ assert_never()

Never assert_never ( Never  __arg)
Assert to the type checker that a line of code is unreachable.

Example::

    def int_or_str(arg: int | str) -> None:
        match arg:
            case int():
                print("It's an int")
            case str():
                print("It's a str")
            case _:
                assert_never(arg)

If a type checker finds that a call to assert_never() is
reachable, it will emit an error.

At runtime, this throws an exception when called.

Definition at line 2333 of file typing_extensions.py.

2333 def assert_never(__arg: Never) -> Never:
2334 """Assert to the type checker that a line of code is unreachable.
2335
2336 Example::
2337
2338 def int_or_str(arg: int | str) -> None:
2339 match arg:
2340 case int():
2341 print("It's an int")
2342 case str():
2343 print("It's a str")
2344 case _:
2345 assert_never(arg)
2346
2347 If a type checker finds that a call to assert_never() is
2348 reachable, it will emit an error.
2349
2350 At runtime, this throws an exception when called.
2351
2352 """
2353 raise AssertionError("Expected code to be unreachable")
2354
2355

References i.

◆ assert_type()

assert_type (   __val,
  __typ 
)
Assert (to the type checker) that the value is of the given type.

When the type checker encounters a call to assert_type(), it
emits an error if the value is not of the specified type::

    def greet(name: str) -> None:
        assert_type(name, str)  # ok
        assert_type(name, int)  # type checker error

At runtime this returns the first argument unchanged and otherwise
does nothing.

Definition at line 1189 of file typing_extensions.py.

1189 def assert_type(__val, __typ):
1190 """Assert (to the type checker) that the value is of the given type.
1191
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::
1194
1195 def greet(name: str) -> None:
1196 assert_type(name, str) # ok
1197 assert_type(name, int) # type checker error
1198
1199 At runtime this returns the first argument unchanged and otherwise
1200 does nothing.
1201 """
1202 return __val
1203
1204

References i.

◆ Concatenate()

Concatenate (   self,
  parameters 
)
Used in conjunction with ``ParamSpec`` and ``Callable`` to represent a
higher order function which adds, removes or transforms parameters of a
callable.

For example::

   Callable[Concatenate[int, P], int]

See PEP 612 for detailed information.

Definition at line 1795 of file typing_extensions.py.

1795 def Concatenate(self, parameters):
1796 """Used in conjunction with ``ParamSpec`` and ``Callable`` to represent a
1797 higher order function which adds, removes or transforms parameters of a
1798 callable.
1799
1800 For example::
1801
1802 Callable[Concatenate[int, P], int]
1803
1804 See PEP 612 for detailed information.
1805 """
1806 return _concatenate_getitem(self, parameters)
1807# 3.7-8

References pip._vendor.typing_extensions._concatenate_getitem().

Here is the call graph for this function:

◆ dataclass_transform()

typing.Callable[[T], T] dataclass_transform ( *bool   eq_default = True,
bool   order_default = False,
bool   kw_only_default = False,
bool   frozen_default = False,
typing.Tuple[ typing.Union[typing.Type[typing.Any], typing.Callable[..., typing.Any]], ... ]   field_specifiers = (),
**typing.Any  kwargs 
)
Decorator that marks a function, class, or metaclass as providing
dataclass-like behavior.

Example:

    from pip._vendor.typing_extensions import dataclass_transform

    _T = TypeVar("_T")

    # Used on a decorator function
    @dataclass_transform()
    def create_model(cls: type[_T]) -> type[_T]:
        ...
        return cls

    @create_model
    class CustomerModel:
        id: int
        name: str

    # Used on a base class
    @dataclass_transform()
    class ModelBase: ...

    class CustomerModel(ModelBase):
        id: int
        name: str

    # Used on a metaclass
    @dataclass_transform()
    class ModelMeta(type): ...

    class ModelBase(metaclass=ModelMeta): ...

    class CustomerModel(ModelBase):
        id: int
        name: str

Each of the ``CustomerModel`` classes defined in this example will now
behave similarly to a dataclass created with the ``@dataclasses.dataclass``
decorator. For example, the type checker will synthesize an ``__init__``
method.

The arguments to this decorator can be used to customize this behavior:
- ``eq_default`` indicates whether the ``eq`` parameter is assumed to be
  True or False if it is omitted by the caller.
- ``order_default`` indicates whether the ``order`` parameter is
  assumed to be True or False if it is omitted by the caller.
- ``kw_only_default`` indicates whether the ``kw_only`` parameter is
  assumed to be True or False if it is omitted by the caller.
- ``frozen_default`` indicates whether the ``frozen`` parameter is
  assumed to be True or False if it is omitted by the caller.
- ``field_specifiers`` specifies a static list of supported classes
  or functions that describe fields, similar to ``dataclasses.field()``.

At runtime, this decorator records its arguments in the
``__dataclass_transform__`` attribute on the decorated object.

See PEP 681 for details.

Definition at line 2360 of file typing_extensions.py.

2371 ) -> typing.Callable[[T], T]:
2372 """Decorator that marks a function, class, or metaclass as providing
2373 dataclass-like behavior.
2374
2375 Example:
2376
2377 from pip._vendor.typing_extensions import dataclass_transform
2378
2379 _T = TypeVar("_T")
2380
2381 # Used on a decorator function
2382 @dataclass_transform()
2383 def create_model(cls: type[_T]) -> type[_T]:
2384 ...
2385 return cls
2386
2387 @create_model
2388 class CustomerModel:
2389 id: int
2390 name: str
2391
2392 # Used on a base class
2393 @dataclass_transform()
2394 class ModelBase: ...
2395
2396 class CustomerModel(ModelBase):
2397 id: int
2398 name: str
2399
2400 # Used on a metaclass
2401 @dataclass_transform()
2402 class ModelMeta(type): ...
2403
2404 class ModelBase(metaclass=ModelMeta): ...
2405
2406 class CustomerModel(ModelBase):
2407 id: int
2408 name: str
2409
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__``
2413 method.
2414
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()``.
2426
2427 At runtime, this decorator records its arguments in the
2428 ``__dataclass_transform__`` attribute on the decorated object.
2429
2430 See PEP 681 for details.
2431
2432 """
2433 def decorator(cls_or_fn):
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,
2440 "kwargs": kwargs,
2441 }
2442 return cls_or_fn
2443 return decorator
2444
2445

References i.

◆ deprecated()

typing.Callable[[_T], _T] deprecated ( str  __msg,
*typing.Optional[typing.Type[Warning]]   category = DeprecationWarning,
int   stacklevel = 1 
)
Indicate that a class, function or overload is deprecated.

Usage:

    @deprecated("Use B instead")
    class A:
        pass

    @deprecated("Use g instead")
    def f():
        pass

    @overload
    @deprecated("int support is deprecated")
    def g(x: int) -> int: ...
    @overload
    def g(x: str) -> int: ...

When this decorator is applied to an object, the type checker
will generate a diagnostic on usage of the deprecated object.

The warning specified by ``category`` will be emitted on use
of deprecated objects. For functions, that happens on calls;
for classes, on instantiation. If the ``category`` is ``None``,
no warning is emitted. The ``stacklevel`` determines where the
warning is emitted. If it is ``1`` (the default), the warning
is emitted at the direct caller of the deprecated object; if it
is higher, it is emitted further up the stack.

The decorator sets the ``__deprecated__``
attribute on the decorated object to the deprecation message
passed to the decorator. If applied to an overload, the decorator
must be after the ``@overload`` decorator for the attribute to
exist on the overload as returned by ``get_overloads()``.

See PEP 702 for details.

Definition at line 2492 of file typing_extensions.py.

2497 ) -> typing.Callable[[_T], _T]:
2498 """Indicate that a class, function or overload is deprecated.
2499
2500 Usage:
2501
2502 @deprecated("Use B instead")
2503 class A:
2504 pass
2505
2506 @deprecated("Use g instead")
2507 def f():
2508 pass
2509
2510 @overload
2511 @deprecated("int support is deprecated")
2512 def g(x: int) -> int: ...
2513 @overload
2514 def g(x: str) -> int: ...
2515
2516 When this decorator is applied to an object, the type checker
2517 will generate a diagnostic on usage of the deprecated object.
2518
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.
2526
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()``.
2532
2533 See PEP 702 for details.
2534
2535 """
2536 def decorator(__arg: _T) -> _T:
2537 if category is None:
2538 __arg.__deprecated__ = __msg
2539 return __arg
2540 elif isinstance(__arg, type):
2541 original_new = __arg.__new__
2542 has_init = __arg.__init__ is not object.__init__
2543
2544 @functools.wraps(original_new)
2545 def __new__(cls, *args, **kwargs):
2546 warnings.warn(__msg, category=category, stacklevel=stacklevel + 1)
2547 if original_new is not object.__new__:
2548 return original_new(cls, *args, **kwargs)
2549 # Mirrors a similar check in object.__new__.
2550 elif not has_init and (args or kwargs):
2551 raise TypeError(f"{cls.__name__}() takes no arguments")
2552 else:
2553 return original_new(cls)
2554
2555 __arg.__new__ = staticmethod(__new__)
2557 return __arg
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)
2563
2565 return wrapper
2566 else:
2567 raise TypeError(
2568 "@deprecated decorator with non-None category must be applied to "
2569 f"a class or callable, not {__arg!r}"
2570 )
2571
2572 return decorator
2573
2574
2575# We have to do some monkey patching to deal with the dual nature of
2576# Unpack/TypeVarTuple:
2577# - We want Unpack to be a kind of TypeVar so it gets accepted in
2578# Generic[Unpack[Ts]]
2579# - We want it to *not* be treated as a TypeVar for the purposes of
2580# counting generic parameters, so that when we subscript a generic,
2581# the runtime doesn't try to substitute the Unpack with the subscripted type.

References i.

◆ final()

final (   f)
This decorator can be used to indicate to type checkers that
the decorated method cannot be overridden, and decorated class
cannot be subclassed. For example:

    class Base:
        @final
        def done(self) -> None:
            ...
    class Sub(Base):
        def done(self) -> None:  # Error reported by type checker
            ...
    @final
    class Leaf:
        ...
    class Other(Leaf):  # Error reported by type checker
        ...

There is no runtime checking of these properties. The decorator
sets the ``__final__`` attribute to ``True`` on the decorated object
to allow runtime introspection.

Definition at line 284 of file typing_extensions.py.

284 def final(f):
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:
288
289 class Base:
290 @final
291 def done(self) -> None:
292 ...
293 class Sub(Base):
294 def done(self) -> None: # Error reported by type checker
295 ...
296 @final
297 class Leaf:
298 ...
299 class Other(Leaf): # Error reported by type checker
300 ...
301
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.
305 """
306 try:
307 f.__final__ = True
308 except (AttributeError, TypeError):
309 # Skip the attribute silently if it is not writable.
310 # AttributeError happens if the object has __slots__ or a
311 # read-only property, TypeError if it's a builtin class.
312 pass
313 return f
314
315

References i.

◆ get_args()

get_args (   tp)
Get type arguments with all substitutions performed.

For unions, basic simplifications used by Union constructor are performed.
Examples::
    get_args(Dict[str, int]) == (str, int)
    get_args(int) == ()
    get_args(Union[int, Union[T, int], str][int]) == (int, str)
    get_args(Union[int, Tuple[T, int]][str]) == (int, Tuple[str, int])
    get_args(Callable[[], T][int]) == ([], int)

Definition at line 1424 of file typing_extensions.py.

1424 def get_args(tp):
1425 """Get type arguments with all substitutions performed.
1426
1427 For unions, basic simplifications used by Union constructor are performed.
1428 Examples::
1429 get_args(Dict[str, int]) == (str, int)
1430 get_args(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)
1434 """
1435 if isinstance(tp, _AnnotatedAlias):
1436 return (tp.__origin__,) + tp.__metadata__
1437 if isinstance(tp, (typing._GenericAlias, _typing_GenericAlias)):
1438 if getattr(tp, "_special", False):
1439 return ()
1440 res = tp.__args__
1441 if get_origin(tp) is collections.abc.Callable and res[0] is not Ellipsis:
1442 res = (list(res[:-1]), res[-1])
1443 return res
1444 return ()
1445
1446
1447# 3.10+

References pip._vendor.typing_extensions.get_origin, and i.

◆ get_origin()

get_origin (   tp)
Get the unsubscripted version of a type.

This supports generic types, Callable, Tuple, Union, Literal, Final, ClassVar
and Annotated. Return None for unsupported types. Examples::

    get_origin(Literal[42]) is Literal
    get_origin(int) is None
    get_origin(ClassVar[int]) is ClassVar
    get_origin(Generic) is Generic
    get_origin(Generic[T]) is Generic
    get_origin(Union[T, int]) is Union
    get_origin(List[Tuple[T, T]][int]) == list
    get_origin(P.args) is P

Definition at line 1400 of file typing_extensions.py.

1400 def get_origin(tp):
1401 """Get the unsubscripted version of a type.
1402
1403 This supports generic types, Callable, Tuple, Union, Literal, Final, ClassVar
1404 and Annotated. Return None for unsupported types. Examples::
1405
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
1414 """
1415 if isinstance(tp, _AnnotatedAlias):
1416 return Annotated
1417 if isinstance(tp, (typing._GenericAlias, _typing_GenericAlias, _BaseGenericAlias,
1418 ParamSpecArgs, ParamSpecKwargs)):
1419 return tp.__origin__
1420 if tp is typing.Generic:
1421 return typing.Generic
1422 return None
1423

References i.

◆ get_original_bases()

get_original_bases (   __cls)
Return the class's "original" bases prior to modification by `__mro_entries__`.

Examples::

    from typing import TypeVar, Generic
    from pip._vendor.typing_extensions import NamedTuple, TypedDict

    T = TypeVar("T")
    class Foo(Generic[T]): ...
    class Bar(Foo[int], float): ...
    class Baz(list[str]): ...
    Eggs = NamedTuple("Eggs", [("a", int), ("b", str)])
    Spam = TypedDict("Spam", {"a": int, "b": str})

    assert get_original_bases(Bar) == (Foo[int], float)
    assert get_original_bases(Baz) == (list[str],)
    assert get_original_bases(Eggs) == (NamedTuple,)
    assert get_original_bases(Spam) == (TypedDict,)
    assert get_original_bases(int) == (object,)

Definition at line 2767 of file typing_extensions.py.

2767 def get_original_bases(__cls):
2768 """Return the class's "original" bases prior to modification by `__mro_entries__`.
2769
2770 Examples::
2771
2772 from typing import TypeVar, Generic
2773 from pip._vendor.typing_extensions import NamedTuple, TypedDict
2774
2775 T = TypeVar("T")
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})
2781
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,)
2787 """
2788 try:
2790 except AttributeError:
2791 try:
2792 return __cls.__bases__
2793 except AttributeError:
2794 raise TypeError(
2795 f'Expected an instance of type, not {type(__cls).__name__!r}'
2796 ) from None
2797
2798
2799# NewType is a class on Python 3.10+, making it pickleable
2800# The error message for subclassing instances of NewType was improved on 3.11+

References i.

◆ get_overloads()

get_overloads (   func)
Return all defined overloads for *func* as a sequence.

Definition at line 447 of file typing_extensions.py.

447 def get_overloads(func):
448 """Return all defined overloads for *func* as a sequence."""
449 # classmethod and staticmethod
450 f = getattr(func, "__func__", func)
451 if f.__module__ not in _overload_registry:
452 return []
453 mod_dict = _overload_registry[f.__module__]
454 if f.__qualname__ not in mod_dict:
455 return []
456 return list(mod_dict[f.__qualname__].values())
457

References i.

◆ get_protocol_members()

typing.FrozenSet[str] get_protocol_members ( type  __tp)
Return the set of members defined in a Protocol.

Example::

    >>> from typing_extensions import Protocol, get_protocol_members
    >>> class P(Protocol):
    ...     def a(self) -> str: ...
    ...     b: int
    >>> get_protocol_members(P)
    frozenset({'a', 'b'})

Raise a TypeError for arguments that are not Protocols.

Definition at line 3011 of file typing_extensions.py.

3011 def get_protocol_members(__tp: type) -> typing.FrozenSet[str]:
3012 """Return the set of members defined in a Protocol.
3013
3014 Example::
3015
3016 >>> from typing_extensions import Protocol, get_protocol_members
3017 >>> class P(Protocol):
3018 ... def a(self) -> str: ...
3019 ... b: int
3020 >>> get_protocol_members(P)
3021 frozenset({'a', 'b'})
3022
3023 Raise a TypeError for arguments that are not Protocols.
3024 """
3025 if not is_protocol(__tp):
3026 raise TypeError(f'{__tp!r} is not a Protocol')
3027 if hasattr(__tp, '__protocol_attrs__'):
3029 return frozenset(_get_protocol_attrs(__tp))
3030
3031
3032# Aliases for items that have always been in typing.
3033# Explicitly assign these (rather than using `from typing import *` at the top),
3034# so that we get a CI error if one of these is deleted from typing.py
3035# in a future version of Python

References pip._vendor.typing_extensions._get_protocol_attrs(), i, and pip._vendor.typing_extensions.is_protocol.

Here is the call graph for this function:

◆ get_type_hints()

get_type_hints (   obj,
  globalns = None,
  localns = None,
  include_extras = False 
)
Return type hints for an object.

This is often the same as obj.__annotations__, but it handles
forward references encoded as string literals, adds Optional[t] if a
default value equal to None is set and recursively replaces all
'Annotated[T, ...]', 'Required[T]' or 'NotRequired[T]' with 'T'
(unless 'include_extras=True').

The argument may be a module, class, method, or function. The annotations
are returned as a dictionary. For classes, annotations include also
inherited members.

TypeError is raised if the argument is not of a type that can contain
annotations, and an empty dictionary is returned if no annotations are
present.

BEWARE -- the behavior of globalns and localns is counterintuitive
(unless you are familiar with how eval() and exec() work).  The
search order is locals first, then globals.

- If no dict arguments are passed, an attempt is made to use the
  globals from obj (or the respective module's globals for classes),
  and these are also used as the locals.  If the object does not appear
  to have globals, an empty dictionary is used.

- If one dict argument is passed, it is used for both globals and
  locals.

- If two dict arguments are passed, they specify globals and
  locals, respectively.

Definition at line 1233 of file typing_extensions.py.

1233 def get_type_hints(obj, globalns=None, localns=None, include_extras=False):
1234 """Return type hints for an object.
1235
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').
1241
1242 The argument may be a module, class, method, or function. The annotations
1243 are returned as a dictionary. For classes, annotations include also
1244 inherited members.
1245
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
1248 present.
1249
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.
1253
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.
1258
1259 - If one dict argument is passed, it is used for both globals and
1260 locals.
1261
1262 - If two dict arguments are passed, they specify globals and
1263 locals, respectively.
1264 """
1265 if hasattr(typing, "Annotated"):
1266 hint = typing.get_type_hints(
1267 obj, globalns=globalns, localns=localns, include_extras=True
1268 )
1269 else:
1270 hint = typing.get_type_hints(obj, globalns=globalns, localns=localns)
1271 if include_extras:
1272 return hint
1273 return {k: _strip_extras(t) for k, t in hint.items()}
1274
1275
1276# Python 3.9+ has PEP 593 (Annotated)

References pip._vendor.typing_extensions._strip_extras(), and i.

Here is the call graph for this function:

◆ IntVar()

IntVar (   name)

Definition at line 316 of file typing_extensions.py.

316def IntVar(name):
317 return typing.TypeVar(name)
318
319
320# A Literal bug was fixed in 3.11.0, 3.10.1 and 3.9.8

References i.

◆ is_protocol()

bool is_protocol ( type  __tp)
Return True if the given type is a Protocol.

Example::

    >>> from typing_extensions import Protocol, is_protocol
    >>> class P(Protocol):
    ...     def a(self) -> str: ...
    ...     b: int
    >>> is_protocol(P)
    True
    >>> is_protocol(int)
    False

Definition at line 2990 of file typing_extensions.py.

2990 def is_protocol(__tp: type) -> bool:
2991 """Return True if the given type is a Protocol.
2992
2993 Example::
2994
2995 >>> from typing_extensions import Protocol, is_protocol
2996 >>> class P(Protocol):
2997 ... def a(self) -> str: ...
2998 ... b: int
2999 >>> is_protocol(P)
3000 True
3001 >>> is_protocol(int)
3002 False
3003 """
3004 return (
3005 isinstance(__tp, type)
3006 and getattr(__tp, '_is_protocol', False)
3007 and __tp is not Protocol
3008 and __tp is not getattr(typing, "Protocol", object())
3009 )
3010

References i.

◆ is_typeddict()

is_typeddict (   tp)
Check if an annotation is a TypedDict class

For example::
    class Film(TypedDict):
        title: str
        year: int

    is_typeddict(Film)  # => True
    is_typeddict(Union[list, str])  # => False

Definition at line 1168 of file typing_extensions.py.

1168 def is_typeddict(tp):
1169 """Check if an annotation is a TypedDict class
1170
1171 For example::
1172 class Film(TypedDict):
1173 title: str
1174 year: int
1175
1176 is_typeddict(Film) # => True
1177 is_typeddict(Union[list, str]) # => False
1178 """
1179 # On 3.8, this would otherwise return True
1180 if hasattr(typing, "TypedDict") and tp is typing.TypedDict:
1181 return False
1182 return isinstance(tp, _TYPEDDICT_TYPES)
1183
1184

References i.

◆ LiteralString()

LiteralString (   self,
  params 
)
Represents an arbitrary literal string.

Example::

  from pip._vendor.typing_extensions import LiteralString

  def query(sql: LiteralString) -> ...:
      ...

  query("SELECT * FROM table")  # ok
  query(f"SELECT * FROM {input()}")  # not ok

See PEP 675 for details.

Definition at line 1979 of file typing_extensions.py.

1979 def LiteralString(self, params):
1980 """Represents an arbitrary literal string.
1981
1982 Example::
1983
1984 from pip._vendor.typing_extensions import LiteralString
1985
1986 def query(sql: LiteralString) -> ...:
1987 ...
1988
1989 query("SELECT * FROM table") # ok
1990 query(f"SELECT * FROM {input()}") # not ok
1991
1992 See PEP 675 for details.
1993
1994 """
1995 raise TypeError(f"{self} is not subscriptable")
1996
1997

References i.

◆ NamedTuple()

NamedTuple (   __typename,
  __fields = _marker,
**  kwargs 
)
Typed version of namedtuple.

Usage::

    class Employee(NamedTuple):
        name: str
        id: int

This is equivalent to::

    Employee = collections.namedtuple('Employee', ['name', 'id'])

The resulting class has an extra __annotations__ attribute, giving a
dict that maps field names to types.  (The field names are also in
the _fields attribute, which is part of the namedtuple API.)
An alternative equivalent functional syntax is also accepted::

    Employee = NamedTuple('Employee', [('name', str), ('id', int)])

Definition at line 2658 of file typing_extensions.py.

2658 def NamedTuple(__typename, __fields=_marker, **kwargs):
2659 """Typed version of namedtuple.
2660
2661 Usage::
2662
2663 class Employee(NamedTuple):
2664 name: str
2665 id: int
2666
2667 This is equivalent to::
2668
2669 Employee = collections.namedtuple('Employee', ['name', 'id'])
2670
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::
2675
2676 Employee = NamedTuple('Employee', [('name', str), ('id', int)])
2677 """
2678 if __fields is _marker:
2679 if kwargs:
2680 deprecated_thing = "Creating NamedTuple classes using keyword arguments"
2681 deprecation_msg = (
2682 "{name} is deprecated and will be disallowed in Python {remove}. "
2683 "Use the class-based or functional syntax instead."
2684 )
2685 else:
2686 deprecated_thing = "Failing to pass a value for the 'fields' parameter"
2687 example = f"`{__typename} = NamedTuple({__typename!r}, [])`"
2688 deprecation_msg = (
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. "
2693 ) + example + "."
2694 elif __fields is None:
2695 if kwargs:
2696 raise TypeError(
2697 "Cannot pass `None` as the 'fields' parameter "
2698 "and also specify fields using keyword arguments"
2699 )
2700 else:
2701 deprecated_thing = "Passing `None` as the 'fields' parameter"
2702 example = f"`{__typename} = NamedTuple({__typename!r}, [])`"
2703 deprecation_msg = (
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. "
2708 ) + example + "."
2709 elif kwargs:
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:
2714 deprecation_msg.format(name=deprecated_thing, remove="3.15"),
2715 DeprecationWarning,
2716 stacklevel=2,
2717 )
2718 __fields = kwargs.items()
2719 nt = _make_nmtuple(__typename, __fields, module=_caller())
2720 nt.__orig_bases__ = (NamedTuple,)
2721 return nt
2722

References pip._vendor.typing_extensions._caller(), pip._vendor.typing_extensions._make_nmtuple(), and i.

Here is the call graph for this function:

◆ Never()

Never (   self,
  params 
)
The bottom type, a type that has no members.

This can be used to define a function that should never be
called, or a function that never returns::

    from pip._vendor.typing_extensions import Never

    def never_call_me(arg: Never) -> None:
        pass

    def int_or_str(arg: int | str) -> None:
        never_call_me(arg)  # type checker error
        match arg:
            case int():
                print("It's an int")
            case str():
                print("It's a str")
            case _:
                never_call_me(arg)  # ok, arg is of type Never

Definition at line 2023 of file typing_extensions.py.

2023 def Never(self, params):
2024 """The bottom type, a type that has no members.
2025
2026 This can be used to define a function that should never be
2027 called, or a function that never returns::
2028
2029 from pip._vendor.typing_extensions import Never
2030
2031 def never_call_me(arg: Never) -> None:
2032 pass
2033
2034 def int_or_str(arg: int | str) -> None:
2035 never_call_me(arg) # type checker error
2036 match arg:
2037 case int():
2038 print("It's an int")
2039 case str():
2040 print("It's a str")
2041 case _:
2042 never_call_me(arg) # ok, arg is of type Never
2043
2044 """
2045
2046 raise TypeError(f"{self} is not subscriptable")
2047
2048

References i.

◆ NotRequired()

NotRequired (   self,
  parameters 
)
A special typing construct to mark a key of a TypedDict as
potentially missing. For example:

    class Movie(TypedDict):
        title: str
        year: NotRequired[int]

    m = Movie(
        title='The Matrix',  # typechecker error if key is omitted
        year=1999,
    )

Definition at line 2074 of file typing_extensions.py.

2074 def NotRequired(self, parameters):
2075 """A special typing construct to mark a key of a TypedDict as
2076 potentially missing. For example:
2077
2078 class Movie(TypedDict):
2079 title: str
2080 year: NotRequired[int]
2081
2082 m = Movie(
2083 title='The Matrix', # typechecker error if key is omitted
2084 year=1999,
2085 )
2086 """
2087 item = typing._type_check(parameters, f'{self._name} accepts only a single type.')
2088 return typing._GenericAlias(self, (item,))
2089

References i.

◆ overload()

overload (   func)
Decorator for overloaded functions/methods.

In a stub file, place two or more stub definitions for the same
function in a row, each decorated with @overload.  For example:

@overload
def utf8(value: None) -> None: ...
@overload
def utf8(value: bytes) -> bytes: ...
@overload
def utf8(value: str) -> bytes: ...

In a non-stub file (i.e. a regular .py file), do the same but
follow it with an implementation.  The implementation should *not*
be decorated with @overload.  For example:

@overload
def utf8(value: None) -> None: ...
@overload
def utf8(value: bytes) -> bytes: ...
@overload
def utf8(value: str) -> bytes: ...
def utf8(value):
    # implementation goes here

The overloads for a function can be retrieved at runtime using the
get_overloads() function.

Definition at line 407 of file typing_extensions.py.

407 def overload(func):
408 """Decorator for overloaded functions/methods.
409
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:
412
413 @overload
414 def utf8(value: None) -> None: ...
415 @overload
416 def utf8(value: bytes) -> bytes: ...
417 @overload
418 def utf8(value: str) -> bytes: ...
419
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:
423
424 @overload
425 def utf8(value: None) -> None: ...
426 @overload
427 def utf8(value: bytes) -> bytes: ...
428 @overload
429 def utf8(value: str) -> bytes: ...
430 def utf8(value):
431 # implementation goes here
432
433 The overloads for a function can be retrieved at runtime using the
434 get_overloads() function.
435 """
436 # classmethod and staticmethod
437 f = getattr(func, "__func__", func)
438 try:
439 _overload_registry[f.__module__][f.__qualname__][
441 ] = func
442 except AttributeError:
443 # Not a normal function; ignore.
444 pass
445 return _overload_dummy
446

References i.

◆ override()

_F override ( _F  __arg)
Indicate that a method is intended to override a method in a base class.

Usage:

    class Base:
        def method(self) -> None: ...
            pass

    class Child(Base):
        @override
        def method(self) -> None:
            super().method()

When this decorator is applied to a method, the type checker will
validate that it overrides a method with the same name on a base class.
This helps prevent bugs that may occur when a base class is changed
without an equivalent change to a child class.

There is no runtime checking of these properties. The decorator
sets the ``__override__`` attribute to ``True`` on the decorated object
to allow runtime introspection.

See PEP 698 for details.

Definition at line 2451 of file typing_extensions.py.

2451 def override(__arg: _F) -> _F:
2452 """Indicate that a method is intended to override a method in a base class.
2453
2454 Usage:
2455
2456 class Base:
2457 def method(self) -> None: ...
2458 pass
2459
2460 class Child(Base):
2461 @override
2462 def method(self) -> None:
2463 super().method()
2464
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.
2469
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.
2473
2474 See PEP 698 for details.
2475
2476 """
2477 try:
2478 __arg.__override__ = True
2479 except (AttributeError, TypeError):
2480 # Skip the attribute silently if it is not writable.
2481 # AttributeError happens if the object has __slots__ or a
2482 # read-only property, TypeError if it's a builtin class.
2483 pass
2484 return __arg
2485
2486

References i.

◆ Required()

Required (   self,
  parameters 
)
A special typing construct to mark a key of a total=False TypedDict
as required. For example:

    class Movie(TypedDict, total=False):
        title: Required[str]
        year: int

    m = Movie(
        title='The Matrix',  # typechecker error if key is omitted
        year=1999,
    )

There is no runtime checking that a required key is actually provided
when instantiating a related TypedDict.

Definition at line 2054 of file typing_extensions.py.

2054 def Required(self, parameters):
2055 """A special typing construct to mark a key of a total=False TypedDict
2056 as required. For example:
2057
2058 class Movie(TypedDict, total=False):
2059 title: Required[str]
2060 year: int
2061
2062 m = Movie(
2063 title='The Matrix', # typechecker error if key is omitted
2064 year=1999,
2065 )
2066
2067 There is no runtime checking that a required key is actually provided
2068 when instantiating a related TypedDict.
2069 """
2070 item = typing._type_check(parameters, f'{self._name} accepts only a single type.')
2071 return typing._GenericAlias(self, (item,))
2072

References i.

◆ reveal_type()

T reveal_type ( T  __obj)
Reveal the inferred type of a variable.

When a static type checker encounters a call to ``reveal_type()``,
it will emit the inferred type of the argument::

    x: int = 1
    reveal_type(x)

Running a static type checker (e.g., ``mypy``) on this example
will produce output similar to 'Revealed type is "builtins.int"'.

At runtime, the function prints the runtime type of the
argument and returns it unchanged.

Definition at line 2310 of file typing_extensions.py.

2310 def reveal_type(__obj: T) -> T:
2311 """Reveal the inferred type of a variable.
2312
2313 When a static type checker encounters a call to ``reveal_type()``,
2314 it will emit the inferred type of the argument::
2315
2316 x: int = 1
2317 reveal_type(x)
2318
2319 Running a static type checker (e.g., ``mypy``) on this example
2320 will produce output similar to 'Revealed type is "builtins.int"'.
2321
2322 At runtime, the function prints the runtime type of the
2323 argument and returns it unchanged.
2324
2325 """
2326 print(f"Runtime type is {type(__obj).__name__!r}", file=sys.stderr)
2327 return __obj
2328
2329

References i.

◆ runtime_checkable()

runtime_checkable (   cls)
Mark a protocol class as a runtime protocol, so that it
can be used with isinstance() and issubclass(). Raise TypeError
if applied to a non-protocol class.

This allows a simple-minded structural check very similar to the
one-offs in collections.abc such as Hashable.

Definition at line 857 of file typing_extensions.py.

857 def runtime_checkable(cls):
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.
861
862 This allows a simple-minded structural check very similar to the
863 one-offs in collections.abc such as Hashable.
864 """
865 if not (
866 (isinstance(cls, _ProtocolMeta) or issubclass(cls, typing.Generic))
867 and getattr(cls, "_is_protocol", False)
868 ):
869 raise TypeError('@runtime_checkable can be only applied to protocol classes,'
870 f' got {cls!r}')
871 cls._is_runtime_protocol = True
872 return cls
873
874
875# Exists for backwards compatibility.

References i.

◆ Self()

Self (   self,
  params 
)
Used to spell the type of "self" in classes.

Example::

  from typing import Self

  class ReturnsSelf:
      def parse(self, data: bytes) -> Self:
          ...
          return self

Definition at line 2002 of file typing_extensions.py.

2002 def Self(self, params):
2003 """Used to spell the type of "self" in classes.
2004
2005 Example::
2006
2007 from typing import Self
2008
2009 class ReturnsSelf:
2010 def parse(self, data: bytes) -> Self:
2011 ...
2012 return self
2013
2014 """
2015
2016 raise TypeError(f"{self} is not subscriptable")
2017
2018

References i.

◆ TypeAlias()

TypeAlias (   self,
  parameters 
)
Special marker indicating that an assignment should
be recognized as a proper type alias definition by type
checkers.

For example::

    Predicate: TypeAlias = Callable[..., bool]

It's invalid when used anywhere except as in the example above.

Definition at line 1453 of file typing_extensions.py.

1453 def TypeAlias(self, parameters):
1454 """Special marker indicating that an assignment should
1455 be recognized as a proper type alias definition by type
1456 checkers.
1457
1458 For example::
1459
1460 Predicate: TypeAlias = Callable[..., bool]
1461
1462 It's invalid when used anywhere except as in the example above.
1463 """
1464 raise TypeError(f"{self} is not subscriptable")
1465# 3.7-3.8

◆ TypedDict()

TypedDict (   __typename,
  __fields = _marker,
total = True,
**  kwargs 
)
A simple typed namespace. At runtime it is equivalent to a plain dict.

TypedDict creates a dictionary type such that a type checker will expect all
instances to have a certain set of keys, where each key is
associated with a value of a consistent type. This expectation
is not checked at runtime.

Usage::

    class Point2D(TypedDict):
        x: int
        y: int
        label: str

    a: Point2D = {'x': 1, 'y': 2, 'label': 'good'}  # OK
    b: Point2D = {'z': 3, 'label': 'bad'}           # Fails type check

    assert Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first')

The type info can be accessed via the Point2D.__annotations__ dict, and
the Point2D.__required_keys__ and Point2D.__optional_keys__ frozensets.
TypedDict supports an additional equivalent form::

    Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str})

By default, all keys must be present in a TypedDict. It is possible
to override this by specifying totality::

    class Point2D(TypedDict, total=False):
        x: int
        y: int

This means that a Point2D TypedDict can have any of the keys omitted. A type
checker is only expected to support a literal False or True as the value of
the total argument. True is the default, and makes all items defined in the
class body be required.

The Required and NotRequired special forms can also be used to mark
individual keys as being required or not required::

    class Point2D(TypedDict):
        x: int  # the "x" key must always be present (Required is the default)
        y: NotRequired[int]  # the "y" key can be omitted

See PEP 655 for more details on Required and NotRequired.

Definition at line 1080 of file typing_extensions.py.

1080 def TypedDict(__typename, __fields=_marker, *, total=True, **kwargs):
1081 """A simple typed namespace. At runtime it is equivalent to a plain dict.
1082
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.
1087
1088 Usage::
1089
1090 class Point2D(TypedDict):
1091 x: int
1092 y: int
1093 label: str
1094
1095 a: Point2D = {'x': 1, 'y': 2, 'label': 'good'} # OK
1096 b: Point2D = {'z': 3, 'label': 'bad'} # Fails type check
1097
1098 assert Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first')
1099
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::
1103
1104 Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str})
1105
1106 By default, all keys must be present in a TypedDict. It is possible
1107 to override this by specifying totality::
1108
1109 class Point2D(TypedDict, total=False):
1110 x: int
1111 y: int
1112
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.
1117
1118 The Required and NotRequired special forms can also be used to mark
1119 individual keys as being required or not required::
1120
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
1124
1125 See PEP 655 for more details on Required and NotRequired.
1126 """
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"
1130 else:
1131 deprecated_thing = "Passing `None` as the 'fields' parameter"
1132
1133 example = f"`{__typename} = TypedDict({__typename!r}, {{}})`"
1134 deprecation_msg = (
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. "
1138 ) + example + "."
1139 warnings.warn(deprecation_msg, DeprecationWarning, stacklevel=2)
1140 __fields = kwargs
1141 elif kwargs:
1142 raise TypeError("TypedDict takes either a dict or keyword arguments,"
1143 " but not both")
1144 if kwargs:
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.",
1149 DeprecationWarning,
1150 stacklevel=2,
1151 )
1152
1153 ns = {'__annotations__': dict(__fields)}
1154 module = _caller()
1155 if module is not None:
1156 # Setting correct module is necessary to make typed dict classes pickleable.
1157 ns['__module__'] = module
1158
1159 td = _TypedDictMeta(__typename, (), ns, total=total)
1160 td.__orig_bases__ = (TypedDict,)
1161 return td
1162

References pip._vendor.typing_extensions._caller(), and i.

Here is the call graph for this function:

◆ TypeGuard()

TypeGuard (   self,
  parameters 
)
Special typing form used to annotate the return type of a user-defined
type guard function.  ``TypeGuard`` only accepts a single type argument.
At runtime, functions marked this way should return a boolean.

``TypeGuard`` aims to benefit *type narrowing* -- a technique used by static
type checkers to determine a more precise type of an expression within a
program's code flow.  Usually type narrowing is done by analyzing
conditional code flow and applying the narrowing to a block of code.  The
conditional expression here is sometimes referred to as a "type guard".

Sometimes it would be convenient to use a user-defined boolean function
as a type guard.  Such a function should use ``TypeGuard[...]`` as its
return type to alert static type checkers to this intention.

Using  ``-> TypeGuard`` tells the static type checker that for a given
function:

1. The return value is a boolean.
2. If the return value is ``True``, the type of its argument
is the type inside ``TypeGuard``.

For example::

    def is_str(val: Union[str, float]):
        # "isinstance" type guard
        if isinstance(val, str):
            # Type of ``val`` is narrowed to ``str``
            ...
        else:
            # Else, type of ``val`` is narrowed to ``float``.
            ...

Strict type narrowing is not enforced -- ``TypeB`` need not be a narrower
form of ``TypeA`` (it can even be a wider form) and this may lead to
type-unsafe results.  The main reason is to allow for things like
narrowing ``List[object]`` to ``List[str]`` even though the latter is not
a subtype of the former, since ``List`` is invariant.  The responsibility of
writing type-safe type guards is left to the user.

``TypeGuard`` also works with type variables.  For more information, see
PEP 647 (User-Defined Type Guards).

Definition at line 1832 of file typing_extensions.py.

1832 def TypeGuard(self, parameters):
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.
1836
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".
1842
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.
1846
1847 Using ``-> TypeGuard`` tells the static type checker that for a given
1848 function:
1849
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``.
1853
1854 For example::
1855
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``
1860 ...
1861 else:
1862 # Else, type of ``val`` is narrowed to ``float``.
1863 ...
1864
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.
1871
1872 ``TypeGuard`` also works with type variables. For more information, see
1873 PEP 647 (User-Defined Type Guards).
1874 """
1875 item = typing._type_check(parameters, f'{self} accepts only a single type.')
1876 return typing._GenericAlias(self, (item,))
1877# 3.7-3.8

References i.

◆ Unpack()

Unpack (   self,
  parameters 
)

Definition at line 2188 of file typing_extensions.py.

2188 def Unpack(self, parameters):
2189 item = typing._type_check(parameters, f'{self._name} accepts only a single type.')
2190 return _UnpackAlias(self, (item,))
2191

References i.

Variable Documentation

◆ _AnnotatedAlias

_AnnotatedAlias = typing._AnnotatedAlias
protected

Definition at line 1281 of file typing_extensions.py.

◆ _BaseGenericAlias

_BaseGenericAlias = typing._GenericAlias
protected

Definition at line 1393 of file typing_extensions.py.

◆ _check_generic

_check_generic
protected

Definition at line 2584 of file typing_extensions.py.

Referenced by Protocol.__class_getitem__().

◆ _collect_type_vars

_collect_type_vars
protected

◆ _ConcatenateGenericAlias

_ConcatenateGenericAlias = typing._ConcatenateGenericAlias
protected

Definition at line 1791 of file typing_extensions.py.

◆ _EXCLUDED_ATTRS

_EXCLUDED_ATTRS
protected
Initial value:
1= {
2 "__abstractmethods__", "__annotations__", "__weakref__", "_is_protocol",
3 "_is_runtime_protocol", "__dict__", "__slots__", "__parameters__",
4 "__orig_bases__", "__module__", "_MutableMapping__marker", "__doc__",
5 "__subclasshook__", "__orig_class__", "__init__", "__new__",
6 "__protocol_attrs__", "__callable_proto_members_only__",
7}

Definition at line 503 of file typing_extensions.py.

◆ _F

_F = typing.TypeVar("_F", bound=typing.Callable[..., typing.Any])
protected

Definition at line 2449 of file typing_extensions.py.

◆ _fake_name

str _fake_name = "Protocol"
protected

Definition at line 990 of file typing_extensions.py.

◆ _is_runtime_protocol

_is_runtime_protocol
protected

Definition at line 871 of file typing_extensions.py.

◆ _marker

_marker = _Sentinel()
protected

Definition at line 144 of file typing_extensions.py.

◆ _NamedTuple

_NamedTuple
protected

Definition at line 2651 of file typing_extensions.py.

◆ _new_signature

str _new_signature = '(typename, fields=None, /, **kwargs)'
protected

Definition at line 2727 of file typing_extensions.py.

◆ _overload_dummy

_overload_dummy = typing._overload_dummy
protected

Definition at line 394 of file typing_extensions.py.

◆ _overload_registry

_overload_registry
protected
Initial value:

Definition at line 403 of file typing_extensions.py.

◆ _prohibited_namedtuple_fields

_prohibited_namedtuple_fields = typing._prohibited
protected

Definition at line 2608 of file typing_extensions.py.

◆ _PROTO_ALLOWLIST

dict _PROTO_ALLOWLIST
protected
Initial value:
1= {
2 'collections.abc': [
3 'Callable', 'Awaitable', 'Iterable', 'Iterator', 'AsyncIterable',
4 'Hashable', 'Sized', 'Container', 'Collection', 'Reversible', 'Buffer',
5 ],
6 'contextlib': ['AbstractContextManager', 'AbstractAsyncContextManager'],
7 'typing_extensions': ['Buffer'],
8}

Definition at line 493 of file typing_extensions.py.

◆ _ProtocolMetaBase

_ProtocolMetaBase = type(_typing_Protocol)
protected

Definition at line 606 of file typing_extensions.py.

◆ _special_namedtuple_fields

_special_namedtuple_fields = frozenset({'__module__', '__name__', '__annotations__'})
protected

Definition at line 2609 of file typing_extensions.py.

◆ _T

_T = typing.TypeVar("_T")
protected

Definition at line 2490 of file typing_extensions.py.

◆ _TAKES_MODULE

str _TAKES_MODULE = "module" in inspect.signature(typing._type_check).parameters
protected

Definition at line 987 of file typing_extensions.py.

◆ _TypedDict

_TypedDict
protected

Definition at line 1077 of file typing_extensions.py.

◆ _TYPEDDICT_TYPES

tuple _TYPEDDICT_TYPES = (typing._TypedDictMeta, _TypedDictMeta)
protected

Definition at line 1164 of file typing_extensions.py.

◆ _TypedDictMeta

_TypedDictMeta = typing._TypedDictMeta
protected

Definition at line 983 of file typing_extensions.py.

◆ _typing_GenericAlias

_typing_GenericAlias = typing._GenericAlias
protected

Definition at line 1398 of file typing_extensions.py.

◆ _typing_Protocol

_typing_Protocol = typing.Protocol
protected

Definition at line 605 of file typing_extensions.py.

◆ _UNPACK_DOC

str _UNPACK_DOC
protected

Definition at line 2130 of file typing_extensions.py.

◆ AbstractSet

AbstractSet = typing.AbstractSet

Definition at line 3036 of file typing_extensions.py.

◆ Annotated

Annotated = typing.Annotated

Definition at line 1278 of file typing_extensions.py.

◆ AnyStr

AnyStr = typing.AnyStr

Definition at line 3037 of file typing_extensions.py.

◆ assert_never

assert_never = typing.assert_never

Definition at line 2331 of file typing_extensions.py.

◆ assert_type

assert_type = typing.assert_type

Definition at line 1186 of file typing_extensions.py.

◆ AsyncContextManager

AsyncContextManager = typing.AsyncContextManager

Definition at line 476 of file typing_extensions.py.

◆ AsyncGenerator

AsyncGenerator = typing.AsyncGenerator

Definition at line 488 of file typing_extensions.py.

◆ AsyncIterable

AsyncIterable = typing.AsyncIterable

Definition at line 472 of file typing_extensions.py.

◆ AsyncIterator

AsyncIterator = typing.AsyncIterator

Definition at line 473 of file typing_extensions.py.

◆ Awaitable

Awaitable = typing.Awaitable

Definition at line 470 of file typing_extensions.py.

◆ BinaryIO

BinaryIO = typing.BinaryIO

Definition at line 3038 of file typing_extensions.py.

◆ Buffer

Buffer = collections.abc.Buffer

Definition at line 2735 of file typing_extensions.py.

◆ Callable

Callable = typing.Callable

Definition at line 3039 of file typing_extensions.py.

◆ cast

cast = typing.cast

Definition at line 3070 of file typing_extensions.py.

◆ ChainMap

ChainMap = typing.ChainMap

Definition at line 487 of file typing_extensions.py.

◆ ClassVar

ClassVar = typing.ClassVar

Definition at line 243 of file typing_extensions.py.

◆ clear_overloads

clear_overloads ( ) = typing.clear_overloads
Clear all overloads in the registry.

Definition at line 400 of file typing_extensions.py.

◆ Collection

Collection = typing.Collection

Definition at line 3040 of file typing_extensions.py.

◆ Concatenate

Concatenate = typing.Concatenate

Definition at line 1790 of file typing_extensions.py.

◆ Container

Container = typing.Container

Definition at line 3041 of file typing_extensions.py.

◆ ContextManager

ContextManager = typing.ContextManager

Definition at line 475 of file typing_extensions.py.

◆ Coroutine

Coroutine = typing.Coroutine

Definition at line 471 of file typing_extensions.py.

◆ Counter

Counter = typing.Counter

Definition at line 486 of file typing_extensions.py.

◆ dataclass_transform

dataclass_transform = typing.dataclass_transform

Definition at line 2358 of file typing_extensions.py.

◆ DefaultDict

DefaultDict = typing.DefaultDict

Definition at line 477 of file typing_extensions.py.

◆ deprecated

deprecated = typing.deprecated

Definition at line 2488 of file typing_extensions.py.

◆ Deque

Deque = typing.Deque

Definition at line 474 of file typing_extensions.py.

◆ Dict

Dict = typing.Dict

Definition at line 3042 of file typing_extensions.py.

◆ doc

doc

Definition at line 264 of file typing_extensions.py.

◆ Final

Final = typing.Final

Definition at line 254 of file typing_extensions.py.

◆ final

final = typing.final

Definition at line 279 of file typing_extensions.py.

◆ ForwardRef

ForwardRef = typing.ForwardRef

Definition at line 3043 of file typing_extensions.py.

◆ FrozenSet

FrozenSet = typing.FrozenSet

Definition at line 3044 of file typing_extensions.py.

◆ Generator

Generator = typing.Generator

Definition at line 3045 of file typing_extensions.py.

◆ Generic

Generic = typing.Generic

Definition at line 3046 of file typing_extensions.py.

◆ GenericMeta

GenericMeta = type

Definition at line 133 of file typing_extensions.py.

◆ get_args

get_args = typing.get_args

Definition at line 1386 of file typing_extensions.py.

Referenced by _TypedDictMeta.__new__().

◆ get_origin

◆ get_original_bases

get_original_bases = _types.get_original_bases

Definition at line 2765 of file typing_extensions.py.

◆ get_overloads

get_overloads = typing.get_overloads

Definition at line 399 of file typing_extensions.py.

◆ get_protocol_members

get_protocol_members = typing.get_protocol_members

Definition at line 2988 of file typing_extensions.py.

◆ get_type_hints

get_type_hints = typing.get_type_hints

Definition at line 1206 of file typing_extensions.py.

◆ Hashable

Hashable = typing.Hashable

Definition at line 3047 of file typing_extensions.py.

◆ IO

IO = typing.IO

Definition at line 3048 of file typing_extensions.py.

◆ is_protocol

◆ is_typeddict

is_typeddict = typing.is_typeddict

Definition at line 984 of file typing_extensions.py.

◆ ItemsView

ItemsView = typing.ItemsView

Definition at line 3049 of file typing_extensions.py.

◆ Iterable

Iterable = typing.Iterable

Definition at line 3050 of file typing_extensions.py.

◆ Iterator

Iterator = typing.Iterator

Definition at line 3051 of file typing_extensions.py.

◆ KeysView

KeysView = typing.KeysView

Definition at line 3052 of file typing_extensions.py.

◆ KT

KT = typing.TypeVar('KT')

Definition at line 207 of file typing_extensions.py.

◆ List

List = typing.List

Definition at line 3053 of file typing_extensions.py.

◆ Literal

Literal = typing.Literal

Definition at line 322 of file typing_extensions.py.

◆ LiteralString

LiteralString = typing.LiteralString

Definition at line 1976 of file typing_extensions.py.

◆ Mapping

Mapping = typing.Mapping

Definition at line 3054 of file typing_extensions.py.

◆ MappingView

MappingView = typing.MappingView

Definition at line 3055 of file typing_extensions.py.

◆ Match

Match = typing.Match

Definition at line 3056 of file typing_extensions.py.

◆ MutableMapping

MutableMapping = typing.MutableMapping

Definition at line 3057 of file typing_extensions.py.

◆ MutableSequence

MutableSequence = typing.MutableSequence

Definition at line 3058 of file typing_extensions.py.

◆ MutableSet

MutableSet = typing.MutableSet

Definition at line 3059 of file typing_extensions.py.

◆ NamedTuple

NamedTuple = typing.NamedTuple

Definition at line 2593 of file typing_extensions.py.

◆ Never

Never = typing.Never

Definition at line 2020 of file typing_extensions.py.

◆ NewType

NewType = typing.NewType

Definition at line 2802 of file typing_extensions.py.

◆ no_type_check

no_type_check = typing.no_type_check

Definition at line 3071 of file typing_extensions.py.

◆ no_type_check_decorator

no_type_check_decorator = typing.no_type_check_decorator

Definition at line 3072 of file typing_extensions.py.

◆ NoReturn

NoReturn = typing.NoReturn

Definition at line 202 of file typing_extensions.py.

◆ NotRequired

NotRequired = typing.NotRequired

Definition at line 2051 of file typing_extensions.py.

◆ Optional

Optional = typing.Optional

Definition at line 3060 of file typing_extensions.py.

◆ OrderedDict

OrderedDict = typing.OrderedDict

Definition at line 481 of file typing_extensions.py.

◆ overload

overload = typing.overload

Definition at line 398 of file typing_extensions.py.

◆ override

override = typing.override

Definition at line 2447 of file typing_extensions.py.

◆ ParamSpecArgs

ParamSpecArgs = typing.ParamSpecArgs

Definition at line 1542 of file typing_extensions.py.

◆ ParamSpecKwargs

ParamSpecKwargs = typing.ParamSpecKwargs

Definition at line 1543 of file typing_extensions.py.

◆ Pattern

Pattern = typing.Pattern

Definition at line 3061 of file typing_extensions.py.

◆ PEP_560

bool PEP_560 = True

Definition at line 132 of file typing_extensions.py.

◆ Protocol

Protocol = typing.Protocol

Definition at line 588 of file typing_extensions.py.

◆ Required

Required = typing.Required

Definition at line 2050 of file typing_extensions.py.

◆ reveal_type

reveal_type = typing.reveal_type

Definition at line 2308 of file typing_extensions.py.

◆ Reversible

Reversible = typing.Reversible

Definition at line 3062 of file typing_extensions.py.

◆ runtime

runtime = runtime_checkable

Definition at line 876 of file typing_extensions.py.

◆ runtime_checkable

runtime_checkable = typing.runtime_checkable

Definition at line 855 of file typing_extensions.py.

◆ Self

Self = typing.Self

Definition at line 1999 of file typing_extensions.py.

◆ Sequence

Sequence = typing.Sequence

Definition at line 3063 of file typing_extensions.py.

◆ Set

Set = typing.Set

Definition at line 3064 of file typing_extensions.py.

◆ Sized

Sized = typing.Sized

Definition at line 3065 of file typing_extensions.py.

◆ SupportsAbs

SupportsAbs = typing.SupportsAbs

Definition at line 886 of file typing_extensions.py.

◆ SupportsBytes

SupportsBytes = typing.SupportsBytes

Definition at line 884 of file typing_extensions.py.

◆ SupportsComplex

SupportsComplex = typing.SupportsComplex

Definition at line 883 of file typing_extensions.py.

◆ SupportsFloat

SupportsFloat = typing.SupportsFloat

Definition at line 882 of file typing_extensions.py.

◆ SupportsIndex

SupportsIndex = typing.SupportsIndex

Definition at line 885 of file typing_extensions.py.

◆ SupportsInt

SupportsInt = typing.SupportsInt

Definition at line 881 of file typing_extensions.py.

◆ SupportsRound

SupportsRound = typing.SupportsRound

Definition at line 887 of file typing_extensions.py.

◆ T

T = typing.TypeVar('T')

Definition at line 206 of file typing_extensions.py.

◆ T_co

T_co = typing.TypeVar('T_co', covariant=True)

Definition at line 209 of file typing_extensions.py.

◆ T_contra

T_contra = typing.TypeVar('T_contra', contravariant=True)

Definition at line 210 of file typing_extensions.py.

◆ Text

Text = typing.Text

Definition at line 489 of file typing_extensions.py.

◆ TextIO

TextIO = typing.TextIO

Definition at line 3066 of file typing_extensions.py.

◆ Tuple

Tuple = typing.Tuple

Definition at line 3067 of file typing_extensions.py.

◆ Type

Type = typing.Type

Definition at line 464 of file typing_extensions.py.

◆ TYPE_CHECKING

TYPE_CHECKING = typing.TYPE_CHECKING

Definition at line 490 of file typing_extensions.py.

◆ TypeAlias

TypeAlias = typing.TypeAlias

Definition at line 1449 of file typing_extensions.py.

◆ TypeAliasType

TypeAliasType = typing.TypeAliasType

Definition at line 2865 of file typing_extensions.py.

◆ TypedDict

TypedDict = typing.TypedDict

Definition at line 982 of file typing_extensions.py.

◆ TypeGuard

TypeGuard = typing.TypeGuard

Definition at line 1828 of file typing_extensions.py.

◆ Union

Union = typing.Union

Definition at line 3068 of file typing_extensions.py.

◆ Unpack

Unpack = typing.Unpack

Definition at line 2173 of file typing_extensions.py.

◆ ValuesView

ValuesView = typing.ValuesView

Definition at line 3069 of file typing_extensions.py.

◆ VT

VT = typing.TypeVar('VT')

Definition at line 208 of file typing_extensions.py.