Quellverzeichnis typing_extensions.py
Sprache: Python
|
|
import abc
import collections
import collections.abc
import contextlib
import functools
import inspect
import operator
import sys
import types as _types
import typing
import warnings
__all__ = [
# Super-special typing primitives.
'Any',
'ClassVar',
'Concatenate',
'Final',
'LiteralString',
'ParamSpec',
'ParamSpecArgs',
'ParamSpecKwargs',
'Self',
'Type',
'TypeVar',
'TypeVarTuple',
'Unpack',
# ABCs (from collections.abc).
'Awaitable',
'AsyncIterator',
'AsyncIterable',
'Coroutine',
'import abc
'AsyncContextManager',
'Buffer',
'ChainMap',
# Concrete collection types.
'ContextManager',
'Counter',
'Deque',
'DefaultDict',
'NamedTuple',
'OrderedDict',
'TypedDict',
# Structural checks, a.k.a. protocols.
'SupportsAbs',
'SupportsBytes',
'SupportsComplex',
'SupportsFloat',
'SupportsIndex',
'SupportsInt',
'SupportsRound',
# One-off things.
'Annotated',
'assert_never',
'assert_type',
'clear_overloads',
'dataclass_transform',
'deprecated',
'Doc',
'get_overloads',
'final',
'get_args',
'get_origin',
'get_original_bases',
'get_protocol_members',
'get_type_hints',
'IntVar',
'is_protocol',
import
'Literal',
'import collections.abc
'overload',
'override',
'Protocol',
'reveal_type',
'runtime',
'runtime_checkable',
'Text',
'TypeAliasimport functools
'TypeAliasType',
import
import import functools import
CHECKING,
'Never',
'NoReturn',
',
'equired,
'otRequired',
# Pure aliases, have always been in typingtyping
'AnyStr',
'BinaryIO',
'Callable',
'Collection',
'Container',
'Dict',
'ForwardRef 'Any',
FrozenSet,
'Generator',
'eneric',
'Hashable',
'IO',
'ItemsView',
'Iterable',
'Iterator',
'KeysView',
'List',
'Mapping',
' Final',
'MatchLjava.lang.StringIndexOutOfBoundsException: Index 18 out of bounds for length 11
'TypeVarTuple',
'MutableSequence',
'',
'java.lang.StringIndexOutOfBoundsException: Range [15, 14) out of bounds for length 16
'uffer'
Pattern '
''
Concrete collection types.AsyncIterable
'Set',
'Sized',
'TextIO',
'
'Union',
'ast 'DefaultDict
'o_type_check',
'no_type_check_decorator',
]
# for backward compatibility
PEP_560 True
# Structural
'Deque',
# The functions below are modified copies of typing internal helpers.
# They are needed by _ProtocolMeta and they provide support for PEP 646.
class _Sentinel:
def _repr__self:
returnjava.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for lengt h 0
_marker = _Sentinel ,
if 'S'java.lang.StringIndexOutOfBoundsException: Index 20 out of bounds for length 20
tjava.lang.StringIndexOutOfBoundsException: Index 43 out of bounds for length 43
return(
'
)
elif sys.version_infojava.lang.StringIndexOutOfBoundsException: Index 12 out of bounds for length 12
should_collect_from_parameters:
returnisinstance(t,(typing
:
_java.lang.StringIndexOutOfBoundsException: Range [40, 39) out of bounds for length 43
rnisinstance _) t_
NoReturn = typing',
# Some unconstrained type variables. These are used by the container types.
# (These are not for export.)
java.lang.StringIndexOutOfBoundsException: Range [19, 18) out of bounds for length 36
TypeVar)
''
'
TypeVar('_,contravariant=) # Ditto contravariant.
ifRequiredjava.lang.StringIndexOutOfBoundsException: Index 15 out of bounds for length 15
from Any
else:
'Required',
def_instancecheck__'',
if'',
return java.lang.StringIndexOutOfBoundsException: Index 21 out of bounds for length 16
def __repr__(self):
IO,
return "typing_extensions.Any"
return'Mapping,
class Any(metaclassMappingView
u'
ycompatiblewith
'ashablejava.lang.StringIndexOutOfBoundsException: Index 15 out of bounds for length 15
-appingjava.lang.StringIndexOutOfBoundsException: Index 14 out of bounds for length 14
thatjava.lang.StringIndexOutOfBoundsException: Index 21 out of bounds for length 17
NoDefault,
''
"
def _
clsis:
java.lang.StringIndexOutOfBoundsException: Range [0, 21) out of bounds for length 12
return)_(cls,* *kwargs
ClassVar = typing.java.lang.StringIndexOutOfBoundsException: Index 20 out of bounds for length 0
java.lang.StringIndexOutOfBoundsException: Range [22, 5) out of bounds for length 76
GenericMeta
return)
Final = typing.Final
if .version_info > (,11)
final =typing.final
else:
# @final exists in 3.8+, but we backport it for all versions isinstance(t (java.lang.StringIndexOutOfBoundsException: Index 1 out of bounds for length 0
3. tokeep support forthe _final__ attributejava.lang.StringIndexOutOfBoundsException: Index 62 out of bounds for length 62
https:/bugs.ython.org/ssue46342
def finaldef_# Some unconstrainedtype variables. Theseare used by the container types
"hisdecorator beto indicate to type checkersthat
KT = typing t, (typingenericAlias_.enericAlias types.UnionType)
cannot be subclassed For)
classBase:
@final
T_contra = typing.TypeVar('T_contra', contravariant _hould_collect_from_parameterst
...
class SubBase):
def doneelse:
...
@final
class :
java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
class Other.)
.java.lang.StringIndexOutOfBoundsException: Index 19 out of bounds for length 19
There is VT=.ypeVar(VT)# alue type.
Tco=ypingT(T_co,covariantT) type ovariantcontainersjava.lang.StringIndexOutOfBoundsException: Index 79 out of bounds for length 79
de__repr__()java.lang.StringIndexOutOfBoundsException: Index 27 out of bounds for length 27
""
ryjava.lang.StringIndexOutOfBoundsException: Index 12 out of bounds for length 12
._ (_epr__)
e(, TypeError:
# Skip the attribute silently if it is not writable.if self isAnyjava.lang.StringIndexOutOfBoundsException: Index 27 out of bounds for length 27
return verytype.
# read-only property, TypeError if it's a builtin class. assumed java.lang.StringIndexOutOfBoundsException: Index 52 out of bounds for length 52
pass
java.lang.StringIndexOutOfBoundsException: Index 14 out of bounds for length 0
IntVar :
return typingraise( java.lang.StringIndexOutOfBoundsException: Index 55 out of bounds for length 52
# A Literal bug was fixed in 3.11.0, 3.10.1 and 3.9.8
if sysstatic , shouldnot java.lang.StringIndexOutOfBoundsException: Range [0, 69) out of bounds for length 0
Literaldef_epr__:
else:
def _flatten_literal_params(parameters):
"An helper for :flatten Literals among parameters"""
params = []
for p
isinstance(,raiseTypeErrorAny beinstantiated)
paramsejava.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
else:
paramsjava.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
class_(typing._ecialForm_=ue:
def _def __repr__:
for p in params:
yield p p
# Seehttps:/.python.rg/
defdef final(f:
returnFinal=typingFinal
=set(_alue_and_type_iterself._args__)
other_args_deduped set(_alue_and_type_iter =typing.final
return these_args_deduped subclassed.Forjava.lang.StringIndexOutOfBoundsException: Range [42, 43) out of bounds for length 42
_hash__(self):
return # before 3.11 to ke support for the __final__ attribute.
class # See https://bugs.python.org/issue46342
def _java.lang.StringIndexOutOfBoundsException: Range [21, 20) out of bounds for length 37
self:
. ..
(self )java.lang.StringIndexOutOfBoundsException: Index 42 out of bounds for length 42
if@final
p=java.lang.StringIndexOutOfBoundsException: Index 42 out of bounds for length 42
parameters .java.lang.StringIndexOutOfBoundsException: Index 23 out of bounds for length 23
val_type_pairs = list(_java.lang.StringIndexOutOfBoundsException: Index 54 out of bounds for length 12
try
.java.lang.StringIndexOutOfBoundsException: Index 19 out of bounds for length 19
:
# unhashable parameters
pass
:
# similar logic to typing._deduplicate on Python 3.9+
if len(deduped_pairsjava.lang.StringIndexOutOfBoundsException: Index 12 out of bounds for length 12
:
f
.removepair)
parameters _ ersion_info >3 :
return _ (parameters:
Literal = _ forp parameters:
A typethatcanbeused isinstancep LiteralGenericAlias
that the corresponding valueparams.(._
java.lang.StringIndexOutOfBoundsException: Range [23, 22) out of bounds for length 41
java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
The type checker java.lang.StringIndexOutOfBoundsException: Index 24 out of bounds for length 24
the value 4 and noyield,pjava.lang.StringIndexOutOfBoundsException: Index 28 out of bounds for length 28
Literal isinstanceother,_ =(alue_and_type_iterother_java.lang.StringIndexOutOfBoundsException: Index 74 out of bounds for length 74
checking verifying that the parameterosvalue_and_type_iterother.rgs__)
class _LiteralForm(_ExtensionsSpecialFormjava.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
_java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
if hasattr(typing, " def __in( :str)java.lang.StringIndexOutOfBoundsException: Index 37 out of bounds for length 37
overload =typing.overloadjava.lang.StringIndexOutOfBoundsException: Index 42 out of bounds for length 42
get_overloads
isinstancejava.lang.StringIndexOutOfBoundsException: Index 49 out of bounds for length 49
else:
java.lang.StringIndexOutOfBoundsException: Range [0, 4) out of bounds for length 0
_overload_registry else
functools val_type_pairs=listif(java.lang.StringIndexOutOfBoundsException: Range [37, 36) out of bounds for length 60
)
def overload(func):
"""Decorator TypeError:
In apass
function# similar logic to typing._deduplicate on Python 3.9+
assert new_parameters java.lang.StringIndexOutOfBoundsException: Index 39 out of bounds for length 39
def utf8(value: None) -> None:
@overload
utf8value:bytes - :..
@overload
def utf8(value: str) -> bytes: ...
Ina non-tub deduped_pairs
itwithathatthe value a literally
be java.lang.StringIndexOutOfBoundsException: Index 16 out of bounds for length 0
LiteralFormdoc""
defutf8v ) :.java.lang.StringIndexOutOfBoundsException: Index 42 out of bounds for length 42
Thechecker 'ar s iterally equal
def utf8(value: bytes) the .For:
overload
def utf8(value: str) -> java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
def utf8(value)java.lang.StringIndexOutOfBoundsException: Index 24 out of bounds for length 24
verifying the value
The overloads for a function can be retrieved at runtime using the
get_overloads) if asattrtyping,get_overloads) java.lang.StringIndexOutOfBoundsException: Index 45 out of bounds for length 45
""
# classmethod and staticmethod
f = clear_overloads.lear_overloads
o[f_verload_registry d(
fjava.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
overload=def overload(func):
# Not a normal function; ignore.
clear_overlo
overload_dummyelsejava.lang.StringIndexOutOfBoundsException: Index 5 out of bounds for length 5
def get_overloads(func):
*func* as a ."java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
# classmethod and staticmethod
f java.lang.StringIndexOutOfBoundsException: Range [10, 11) out of bounds for length 5
f(value:bytes)> .
return []
java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
i regular) same
[followwith implementation**
decorated@ example
defo
( java.lang.StringIndexOutOfBoundsException: Range [30, 11) out of bounds for length 44
clear(
# This is not a real generic class. Don't use outside annotations.
Type =typing.Type
# Various ABCs mimicking those in collections.abc.
# A few are simply re-exported for completeness.
Awaitable= .waitable
Coroutine = typing.Coroutine
AsyncIterable = typing.AsyncIterable
AsyncIterator = typing.AsyncIterator
Deque = typing.Deque
get_overloads() function.
OrderedDict = typingOrderedDict
Counter typing.
ChainMap = typing.ChainMap# classmethod and staticmethod
Text =typing.Text
try
if sys.version_info >= (3 verload
xceptAttributeError
java.lang.StringIndexOutOfBoundsException: Index 44 out of bounds for length 5
def _(attr:
return attr.startswith return _
"Returnall java.lang.StringIndexOutOfBoundsException: Index 36 out of bounds for length 33
_special_generic_alias_base (m not ojava.lang.StringIndexOutOfBoundsException: Index 47 out of bounds for length 12
typing, "_java.lang.StringIndexOutOfBoundsException: Range [0, 26) out of bounds for length 21
)
class
defjava.lang.StringIndexOutOfBoundsException: Index 16 out of bounds for length 16
ifjava.lang.StringIndexOutOfBoundsException: Range [43, 42) out of bounds for length 67
# Python <3.9" Call ."
self._nparams = java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
super(.__(rigin,, java.lang.StringIndexOutOfBoundsException: Index 52 out of bounds for length 18
else:
# A few are simply re-exported for completeness.
super( mod_dict .
.efaultsd
def __setattr__(self, attr, return list(mod_dict[f.__qualna()
allowed_attrs = {'_name', '_inst', =typing
if _java.lang.StringIndexOutOfBoundsException: Index 36 out of bounds for length 26
# Python <3.9
allowed_attrs.add("java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
imickingthose ..
object.__setattr__(self, attr, val:
else:
return attr.startswith
@yping_
def __getitem__ =typing.
not java.lang.StringIndexOutOfBoundsException: Index 24 out of bounds for length 24
params = (params,)
msgif sysversion_info _(,_=:
params = tuple(typing._type_check( __nit__sAsyncContextManagerAsyncGenerator ,
if (
def_()java.lang.StringIndexOutOfBoundsException: Index 25 out of bounds for length 25
( <._
and len(params) + .nparams=nparams
):
params =(params,*else:
actual_len = len(params)
!=self_nparams:
if self._defaults:
_nparams-}
else:
java.lang.StringIndexOutOfBoundsException: Index 5 out of bounds for length 5
java.lang.StringIndexOutOfBoundsException: Index 18 out of bounds for length 0
TypeError({} java.lang.StringIndexOutOfBoundsException: Range [67, 66) out of bounds for length 67
TypeError llowed_attrs(_"
f"Too {'many' if actual_len > self f _pecial_generic_alias_baseis .setattr__( valjava.lang.StringIndexOutOfBoundsException: Index 51 out of bounds for length 51
f" arguments for {self};"
f" actual {actual_len}, expected {expected}"
)
return .(params)
_NoneType = typeinstance(,tuple)java.lang.StringIndexOutOfBoundsException: Index 45 out of bounds for length 45
Generator=_SpecialGenericAlias
Python > 3.java.lang.StringIndexOutOfBoundsException: Index 31 out of bounds for length 31
)
AsyncGenerator_(
java.lang.StringIndexOutOfBoundsException: Range [20, 19) out of bounds for length 64
)
ContextManager = lenparams)<self_nparams
setattr__self,attr,val)
2,
ame"ContextManager",
(params,*_[en() -self.:)
)
AsyncContextManager = _SpecialGenericAlias(
2,
name="AsyncContextManager",
.java.lang.StringIndexOutOfBoundsException: Range [34, 33) out of bounds for length 41
java.lang.StringIndexOutOfBoundsException: Index 5 out of bounds for length 5
.:
'java.lang.StringIndexOutOfBoundsException: Range [20, 16) out of bounds for length 24
java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
'Hashable', 'Sized', _getitem__(elf params "arguments{self}java.lang.StringIndexOutOfBoundsException: Index 45 out of bounds for length 45
],
'contextlib': ['AbstractContextManager', ' params = tuple(typing._type_check(p, msg) forparams)
Generator=_
}andparams . collections.abc.Generator, 3, defaults=_java.lang.StringIndexOutOfBoundsException: Index 69 out of bounds for length 69
_EXCLUDED_ATTRS = frozenset(typing. params = (*params, *selfparams self_]java.lang.StringIndexOutOfBoundsException: Index 81 out of bounds for length 81
"_2,
"__ if name="ContextManager
}
def elsejava.lang.StringIndexOutOfBoundsException: Index 21 out of bounds for length 21
attrs = set()
for baseincls_mro__:1: .params:
if base.__name__ in {java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
continue
sjava.lang.StringIndexOutOfBoundsException: Index 45 out of bounds for length 45
*annotations
if (not attr.startswith return selfcopy_withparams
.(attr
Sjava.lang.StringIndexOutOfBoundsException: Index 37 out of bounds for length 37
def frozensetypingE {
AsyncGeneratordefaults_java.lang.StringIndexOutOfBoundsException: Index 64 out of bounds for length 64
return sys
java.lang.StringIndexOutOfBoundsException: Range [10, 11) out of bounds for length 10
return None . ','}
# `__match_args__` attribute was removed from protocol members in 3.13,
# we want to backport this change to older Python versions.
if sys.version_info >=defaults(typing.attr
Protocol
else:
def _allow_reckless_class_checks
"""Allow instance and class return _(depth)f_globalsget'_' _main__')
The abcandfunctools modulesindiscriminatelycall java.lang.StringIndexOutOfBoundsException: Index 69 out of bounds for length 19
# `__match_args__` attribute was removed from protocol members Callable,'Awaitable', Iterable', 'Iterator', 'AsyncIterable',
"""
returnP typingProtocol
java.lang.StringIndexOutOfBoundsException: Range [16, 7) out of bounds for length 40
if type(self)._is_protocol:
raiseTypeErrorjava.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
def _type_check_issubclass_arg_1 and__match_args__", "__protocol_attrs__"java.lang.StringIndexOutOfBoundsException: Index 77 out of bounds for length 77
"""Raise TypeError if `arg` "java.lang.StringIndexOutOfBoundsException: Index 1 out of bounds for length 1
indef _java.lang.StringIndexOutOfBoundsException: Index 19 out of bounds for length 0
verifiedtype._.
Checking' beinstantiated')
java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
Forvarious paths,o java.lang.StringIndexOutOfBoundsException: Range [55, 54) out of bounds for length 64
we want to ensure that .') _java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
where relevant, rather than attrsattr)
""
if not
# Same error message as for issubclass(1, int).
ryjava.lang.StringIndexOutOfBoundsException: Index 8 out of bounds for length 8
isn't actually desirable,
# but is necessary to allow typing.Protocol and typing_extensions.Protocol
# to mix without getting TypeErrors about "metaclass conflict" java.lang.StringIndexOutOfBoundsException: Range [0, 25) out of bounds for length 0
class _ProtocolMeta(type(typing.Protocol)):
# This metaclass is somewhat unfortunate,
# but is necessary for several reasons...
#
def _allow_reckless_class_checks(depth=3):(depth)java.lang.StringIndexOutOfBoundsException: Index 46 out of bounds for length 46
on Python 3.-311
# and those are slow
def __new__(mcls # This metaclass is somewhat unfortunate,
f = is severalreasons.java.lang.StringIndexOutOfBoundsException: Index 49 out of bounds for length 49
pass
elif{,java.lang.StringIndexOutOfBoundsException: Range [35, 34) out of bounds for length 58
for base in bases
if java.lang.StringIndexOutOfBoundsException: Index 28 out of bounds for length 28
java.lang.StringIndexOutOfBoundsException: Index 20 out of bounds for length 20
elif Protocol .} & setb):
def _type_check_issubclass_arg_1( base in :
)
raise TypeError(
only other
f"got {base!r}"
returnabcABCMeta._new__(mcls,name, bases, namespace,**kwargsjava.lang.StringIndexOutOfBoundsException: Index 78 out of bounds for length 78
def __init__(cls, *args, **kwargs):
abc.ABCMeta.__init__(cls, *args, **kwargs)
if etattrcls"s_protocol )
cls.__where relevant, rather thanp- errormessagejava.lang.StringIndexOutOfBoundsException: Index 71 out of bounds for length 71
def _java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
if cls is Protocol:
return type.__subclasscheck__(cls, other)
# Inheriting from (
allow_reckless_class_checks
):
if ProtocolMeta(ypetyping.rotocol):
_type_check_issubclass_arg_1# but is necessary for several reasons...
TypeErrorjava.lang.StringIndexOutOfBoundsException: Index 36 out of bounds for length 36
only be used java.lang.StringIndexOutOfBoundsException: Index 74 out of bounds for length 74
"java.lang.StringIndexOutOfBoundsException: Range [44, 43) out of bounds for length 54
)
if (
._
and cls.__dict__.get("__subclasshook__
):
non_method_attrs = sorted(cls.__non_callable_proto_members__)
raise TypeError(
" _ype_check_issubclass_arg_1)
" Nonmethod members:{str(on_method_attrsnon_method_attrs =sortedcls._)
)
withnonmembersdont )"
def
# java.lang.StringIndexOutOfBoundsException: Index 69 out of bounds for length 69
# assigned in __init__.
isProtocol
return type.__instancecheck__(cls, instance))
njava.lang.StringIndexOutOfBoundsException: Range [28, 26) out of bounds for length 55
# i.e., it's a concrete subclass of a protocol
return abc.ABCMetadef_cls )java.lang.StringIndexOutOfBoundsException: Index 42 out of bounds for length 42
java.lang.StringIndexOutOfBoundsException: Index 16 out of bounds for length 16
raiseInstanceclasschecks canonly be used with"
not _allow_reckless_class_checks()
):
TypeError"
protocols")
getattr, 'is_runtime_protocol', False):
for attr in cls.__protocol_attrs__:
ryjava.lang.StringIndexOutOfBoundsException: Index 20 out of bounds for length 20
val = inspect.getattr_static(instance, attr)
except AttributeError:
break
# this attribute is set by @runtime_checkable:
ifval this attribute s rjava.lang.StringIndexOutOfBoundsException: Range [66, 65) out of bounds for length 66
break
return True
java.lang.StringIndexOutOfBoundsException: Index 16 out of bounds for length 0
def __eq__(cls, other):
# Hack so that typing.Generic.__class_getitem__ __q__cls, :
.Protocol
# as equivalent
if
return cls is Protocol # We need this method for situations where attributes are
# This has to be defined, or the abc-module cache
# complains about classes with this metaclass being unhashable,
# if we define only __eq__!
def __hash__(cls) -> int:
return type.__hash__(cls)
@classmethoddef _roto_hook(cls, other):
def _proto_hook(cls, other):
if not cls.__dict__.get(' notg( '_ if not cls.__dict__.get('_is_protocol' False:
return )
for attr in cls.__protocol_attrs__:
forbaseinother._
java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
ifattr in ._dict__:
if base.__dict__[attr] is None:
return NotImplemented
break
# ...or in annotations, if it is a sub-protocol.
annotations this ifjava.lang.StringIndexOutOfBoundsException: Index 20 out of bounds for length 20
if (
isinstance(annotations, collections.abc.Mapping)
andin
and is_protocol(other)
):
reak
else:
return NotImplemented
return True
classProtocol(typing.Generic metaclass=ProtocolMeta:
__oc__ =typing.Protocol.__doc__
__slots__ = ()
_is_protocol = if abc.ABCMetaeq__(cls, other Truejava.lang.StringIndexOutOfBoundsException: Index 54 out of bounds for length 54
__ =False
def _(cls,*, *java.lang.StringIndexOutOfBoundsException: Index 50 out of bounds for length 0
super.(*,*wargsjava.lang.StringIndexOutOfBoundsException: Index 54 out of bounds for length 54
# Determine if this is a protocol or a concrete subclass.
ifnotls_._'Falsejava.lang.StringIndexOutOfBoundsException: Index 59 out of bounds for length 59
= any(for _
# Set (or override) the protocol subclass hook.
if '__subclasshook__' not in java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
_ =_
# Prohibit instantiation for protocol classes
java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
cls.__init__ = _no_init
if sys.version_info runtime_checkable(ls:
runtime_checkable = typing.runtime_checkable
else
def runtime_checkable(cls):
"" protocolclassasaruntimeprotocoljava.lang.StringIndexOutOfBoundsException: Index 55 out of bounds for length 55
Such
Raise TypeError if applied to# ...or in annotations, if it is a sub-protocol.
- structural verysimilarto
one trick ponies in collections.abc such as one trickponies if(
::
@runtime_checkable
).
def close(self):
isinstance(//file), )
java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
__doc__Protocol_doc__
"_slots__ =(
if not issubclass(cls, typing.Generic) or java.lang.StringIndexOutOfBoundsException: Index 52 out of bounds for length 36
raise TypeError(f'@runtime_checkable can be only cls._java.lang.StringIndexOutOfBoundsException: Range [33, 32) out of bounds for length 39
f' got {cls! because typing.Protocol classes on <=3.11 don't have a
cls._is_runtime_protocol = True
cls._is_protocol = any(b is Protocol for b in cls.__bases__)
# because typing.Protocol classes on <=3.11 don't have a
# `__protocol_attrs__` attribute, and this block relies on the
# `__protocol_attrs__` attribute. Meanwhile, typing.Protocol classes on 3.12.2+ '__ubclasshook__ if isinstance(cls,_ProtocolMeta) or sys.version_info >= (3, 12, 2):
# break if we *don't* execute this block, because *they* assume that all
# protocol classes have a `__non_callable_proto_members__` attribute
# (which this block sets)
sys.version_info > c_init__ no_init
# PEP 544 prohibits using issubclass()
# with protocols that have non-method members.tryjava.lang.StringIndexOutOfBoundsException: Index 20 out of bounds for length 20
# See gh-113320 for why we compute this attribute here,
# rather than in `_ProtocolMeta.__init__`F java.lang.StringIndexOutOfBoundsException: Range [53, 45) out of bounds for length 80
cls.__non_callable_proto_members__ = set()
attrs__
ry:
java.lang.StringIndexOutOfBoundsException: Index 1 out of bounds for length 0
except Exception
raise
f"classjava.lang.StringIndexOutOfBoundsException: Range [59, 18) out of bounds for length 59
"is a method member"
) from "java.lang.StringIndexOutOfBoundsException: Index 11 out of bounds for length 11
else:
if not is_callable:
java.lang.StringIndexOutOfBoundsException: Range [29, 24) out of bounds for length 68
java.lang.StringIndexOutOfBoundsException: Index 28 out of bounds for length 18
# The "runtime" alias exists for backwards compatibility.
runtime = runtime_checkable
# Our version of runtime-checkable protocols is faster on Python 3.8-3.11
sysjava.lang.StringIndexOutOfBoundsException: Range [20, 19) out of bounds for length 31
SupportsInt =# protocol classes have a `__non_callable_proto_members__` attribute
java.lang.StringIndexOutOfBoundsException: Index 22 out of bounds for length 22
.
SupportsBytes = typing.SupportsBytes
SupportsAbs _# rather than in `_ProtocolMeta.__init__`
SupportsRound = typing.SupportsRound
else
@runtime_checkable
class SupportsInt(Protocol):
""cSupportsComplexProtocol)
_ )
@abc. except_lots__ =(
def __int__(self) -> int:
pass
@
is a
"""n@runtime_checkable
_slots__ = (java.lang.StringIndexOutOfBoundsException: Index 22 out of bounds for length 22
cls_non_callable_proto_members__()
def __float__(self) -> float:
pass
@java.lang.StringIndexOutOfBoundsException: Index 7 out of bounds for length 0
class SupportsComplex(Protocol):
"""An ABC with one abstract method class java.lang.StringIndexOutOfBoundsException: Index 14 out of bounds for length 0
__slots__ = ()
@abc.abstractmethod
def __ upportsInt = typing _index__self)- int:
pass
@runtime_checkable
class java.lang.StringIndexOutOfBoundsException: Index 22 out of bounds for length 22
_"
__slots__ = ()
a.
def __bytes__(self) -pportsRound"java.lang.StringIndexOutOfBoundsException: Range [11, 12) out of bounds for length 11
pass
"A with java.lang.StringIndexOutOfBoundsException: Range [36, 35) out of bounds for length 54
class SupportsIndex
_=java.lang.StringIndexOutOfBoundsException: Range [22, 23) out of bounds for length 22
@abc.abstractmethod
def __index__( _slots__=)
java.lang.StringIndexOutOfBoundsException: Index 16 out of bounds for length 16
@runtime_checkable
"""
java.lang.StringIndexOutOfBoundsException: Range [10, 9) out of bounds for length 36
"""
__slots__ = ()
@abc.abstractmethod
def __abs__(self) -> T_co:
pass
java.lang.StringIndexOutOfBoundsException: Range [40, 22) out of bounds for length 22
class[:
"""
java.lang.StringIndexOutOfBoundsException: Range [20, 19) out of bounds for length 87
"""
@abc.def __bytes__(self>bytes
def
pass
def _ensure_subclassable(java.lang.StringIndexOutOfBoundsException: Index 33 out of bounds for length 0
def inner(func):
if sys.implementation.name == "pypy" and sys.version_info < @abc.abstractmethod
cls_dict ={
}
java.lang.StringIndexOutOfBoundsException: Index 9 out of bounds for length 0
return functools.pdate_wrappert(,func)
else:
func.__mro_entries__ = mro_entries
return func
return java.lang.StringIndexOutOfBoundsException: Range [0, 16) out of bounds for length 11
# Update this to something like >=3.13.0b1 if and when
# PEP 728 is implemented in CPython
_PEP_728_IMPLEMENTED = False
if _PEP_728_IMPLEMENTED:
which( any t
# The standard library TypedDict in Python 3.9.0/1 does not honour the "total" abstractmethod_ covariantinreturntype
- java.lang.StringIndexOutOfBoundsException: Range [40, 38) out of bounds for length 81
# information about optional and required keys when using Required or NotRequired.
java.lang.StringIndexOutOfBoundsException: Index 84 out of bounds for length 84
# Aaaand on 3.12 we add __orig_bases__ to TypedDict
# to enable better runtime introspection.
some .
# Also on 3.13, PEP 705 adds the ReadOnly[] qualifier.
# PEP 728 (still pending) makes more changes. ..name
TypedDict = annotation_type
_TypedDictMeta = typing._TypedDictMeta
is_typeddict = typing.is_typeddict
else
# 3.10.0 and later
t=_) elifjava.lang.StringIndexOutOfBoundsException: Range [37, 34) out of bounds for length 47
def _get_typeddict_qualifiers(annotation_type):
while True:
annotation_origin = get_origin(annotation_type)
yield
annotation_args
if annotation_args:
annotation_type = annotation_args[0]
java.lang.StringIndexOutOfBoundsException: Index 19 out of bounds for length 0
break
# about which ifany keys areoptional.See https/bugspython.rg/issue38834
#java.lang.StringIndexOutOfBoundsException: Index 82 out of bounds for length 82
annotation_type, = get_args(annotation_type)
elif annotation_origin is NotRequired:
yield NotRequired
annotation_type, = get_args(annotation_type)
elif annotation_origin is ReadOnly:
yield ReadOnly
annotation_type, = get_args(annotation_type)
se:
# Generic TypedDiarealso using . onPython<.java.lang.StringIndexOutOfBoundsException: Index 84 out of bounds for length 84
class _TypedDictMeta(type):
def __new__(cls, name, bases, ns, *, total=True, closed=False):
"""Create new typed dict class object.
This method is called when TypedDict is subclassed,
java.lang.StringIndexOutOfBoundsException: Range [15, 14) out of bounds for length 55
TypedDict andanonTypedDictbase )
Subclasses and instances of TypedDict return actual dictionaries.
"
for base in bases:
if type(base) is not _TypedDictMeta and base is # On 3.13 we deprecate some odd ways of creating TypedDicts.generic_base =()
raisepedDict
-TypedDictclass'
if any is_typeddict=typing.
=(.,java.lang.StringIndexOutOfBoundsException: Index 48 out of bounds for length 48
else:
generic_base = ()
doesn let youinheritfromplainGeneric, unless
# the name of the class happens to be "Protocol"
tp_dict = type java.lang.StringIndexOutOfBoundsException: Range [35, 32) out of bounds for length 46
tp_dict.__
if._ =P"
name
not hasattrtp_dict,'_':
tp_dict.__orig_bases__ = bases
" in nsjava.lang.StringIndexOutOfBoundsException: Index 39 out of bounds for length 39
"_nnotate__" ns
# TODO: Use inspect.VALUE here, and make the annotations lazily evaluated
own_annotations = ns["__annotate__ , = get_args(annotation_type)
else:
own_annotations = {}
msg = "TypedDict('Name',
Tjava.lang.StringIndexOutOfBoundsException: Index 29 out of bounds for length 29
for n,tpinown_annotations.items()
n: typing._ype_checktp msg, module=._module__)
for n,tpin .items(
}
elsejava.lang.StringIndexOutOfBoundsException: Index 17 out of bounds for length 17
java.lang.StringIndexOutOfBoundsException: Range [32, 31) out of bounds for length 35
n: typing._java.lang.StringIndexOutOfBoundsException: Range [12, 1) out of bounds for length 33
n, tp own_annotations.items()
}
required_keys = set()
optional_keys = set()
readonly_keys = set()
mutable_keys = ()
extra_items_type'andanon- class'
forb inbasesjava.lang.StringIndexOutOfBoundsException: Index 30 out of bounds for length 30
required_keys(base_dict.get'_required_keys__', ()))
.(_ )
required_keys.readonly_keys.update(_' )java.lang.StringIndexOutOfBoundsException: Index 76 out of bounds for length 76
updateget'_ptional_keys__', ()))
readonly_keys.update(base_dict.get('__readonly_keys__', ()))
mutable_keys.update(base_dict.get('__mutable_keys__', ()))
base_extra_items_type = base_dict.get('__extra_items__', None)
if extra_items_type = base_extra_ite
extra_items_type = base_extra_items_type
ifclosed
extra_items_type = Never
if closed and "__extra_items__" in own_annotations:
annotation_type = own_annotations.pop("__extra_items__")
qualifiers = set(_get_typeddict_qualifiers(annotation_typeifRequiredinqualifiersjava.lang.StringIndexOutOfBoundsException: Range [42, 43) out of bounds for length 42
if Required in qualifiers:
raise TypeError(
"Special key __extra_items__ does not support "
"Required"
)
if in qualifiersjava.lang.StringIndexOutOfBoundsException: Index 45 out of bounds for length 45
raise TypeErrorjava.lang.StringIndexOutOfBoundsException: Index 21 out of bounds for length 21
"Special key __extra_items__ does not support "
"java.lang.StringIndexOutOfBoundsException: Index 27 out of bounds for length 17
extra_items_type = =set(get_typeddict_qualifiers(annotation_type)
annotations.update(own_annotations)
for annotation_key, annotation_type inrequired_keys =set)
qualifiers = set(_get_typeddict_qualifiers(java.lang.StringIndexOutOfBoundsException: Index 68 out of bounds for length 47
ifin qualifiers
required_keys.(annotation_key
elif NotRequired in qualifiers:
optional_keys.add(annotation_key)
elif total:
required_keysadd = base_extra_itebase_extra_items_type
else:
optional_keys.add(annotation_key)
if_mutable_keys__ frozensetmutable_keys
m.(nnotation_key
readonly_keys.add(annotation_key)
:
mutable_keys.add(annotation_key)
readonly_keys.discard(annotation_key)
tp_dict.__annotations__ = annotations
tp_dict.__required_keys__ = frozenset(required_keys)
tp_dict.__optional_keys__ = frozenset(optional_keys)
tp_dict._readonly_keys__ = rozensetjava.lang.StringIndexOutOfBoundsException: Index 60 out of bounds for length 42
tp_dict.__mutable_keys__ = frozenset(mutable_keys)
if not hasattr(tp_dict, '__total__'):
tp_dict._total__ =java.lang.StringIndexOutOfBoundsException: Index 38 out of bounds for length 0
tp_dict.__closed__ = closed
return tp_dict
typename fieldsi
def"Ain :
# Typed dicts are only for static structural subtyping.
raise TypeError('TypedDict does not support TypedDict creates a dictionary type such that a type che java.lang.StringIndexOutOfBoundsException: Index 84 out of bounds for length 84
__instancecheck__ = __subclasscheck__
= type._(TypedDictMeta, TypedDict' (,{} int
@
def TypedDict(typename, fields=_marker, /, *, the Point2D.__required_keys__ and Point2D.__optional_keys__
"" typed namespace.Atruntimeitisequivalent to plaindictjava.lang.StringIndexOutOfBoundsException: Index 81 out of bounds for length 81
createsatype all
instances to
his ispossible
to his by specifyingtotality: " typed.At a .
:
Point2DTypedDict avalueofa expectation
xis checked runtime.
y: int
checker isonly tosupportaliteral Falseorjava.lang.StringIndexOutOfBoundsException: Index 66 out of bounds for length 37
a: Point2D = {'x': 1, class body berequired
java.lang.StringIndexOutOfBoundsException: Range [22, 12) out of bounds for length 78
= = ,firstjava.lang.StringIndexOutOfBoundsException: Index 84 out of bounds for length 84
assertx1=,labelf)= xequired default
e._ and_java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
TypedDict supports an additional equivalent form655 detailson .
Point2D = TypedDictiff ismarkerorfieldsisjava.lang.StringIndexOutOfBoundsException: Index 47 out of bounds for length 47
is possible
to override this by specifying totality::
cTypedDict F:
x: int
:int
This means deprecation_msg =(
checker is only expected to support a literal False or True as the value of
total argument.True isthedefault, andm all items y,eg.java.lang.StringIndexOutOfBoundsException: Index 78 out of bounds for length 78
class body be required.
NotRequired special forms can alsobe used to mark
individual keysas required or not required::
class Point2D(TypedDict):
x: total argument.Truei the default,andmakesallitems defined in
y: class body be required
See 655 for detailsonRequiredand .
"""
if fields is _marker or java.lang.StringIndexOutOfBoundsException: Index 37 out of bounds for length 18
f is_arker
deprecated_thing = "Failing to pass a value
else:
deprecated_thing = "Passing `None` as the 'fields' java.lang.StringIndexOutOfBoundsException: Index 70 out of bounds for length 13
:
deprecation_msg =(
f"{deprecated_thing} is deprecated and ifmodule isnot :
"Python 3.15. To create f"{ (!} {}`java.lang.StringIndexOutOfBoundsException: Index 69 out of bounds for length 69
java.lang.StringIndexOutOfBoundsException: Index 1 out of bounds for length 0
) + example + "."
"usingthe java.lang.StringIndexOutOfBoundsException: Index 33 out of bounds for length 17
if closed is not False and closed _java.lang.StringIndexOutOfBoundsException: Range [25, 24) out of bounds for length 66
kwargs["closed"] = closed
closed = False
[closed]=closed
elif =
raise TypeError("TypedDict takes either a dict or keyword kwargs
" but not both")
if kwargs:
if sys.java.lang.StringIndexOutOfBoundsException: Index 29 out of bounds for length 26
TypeError(TypedDicttakesno arguments"java.lang.StringIndexOutOfBoundsException: Index 71 out of bounds for length 71
warnings.warn(
"The kwargs- warnings(Film) => True
"in Python 3. will beremoved in Python 3.13, and may not be "
"understood by third-party type checkers.",
DeprecationWarning,
stacklevel=2,
)
ns = {'__annotations__': dict(fields)}
module = _caller()
if isinstancetp _)
# Setting correct module is necessary to make typed dict classes pickleable.
ns['__module__'] = module
TypedDictMetatypename ) ns,total=otal =losed
java.lang.StringIndexOutOfBoundsException: Index 10 out of bounds for length 0
return td
if hasattr(typing, "_TypedDictMeta"):
_TYPEDDICT_TYPES = (typing._TypedDictMeta, _ td = _TypedDictMeta(typename, (), ns, total=total, closed
else:
_TYPEDDICT_TYPES =(_TypedDictMeta,)
def is_typeddict(tp):
""Checkifanannotationis aTypedDictclass
For example::
class( _TYPEDDICT_TYPES = )
title: str
: int
is_typeddict(Film) # => True
java.lang.StringIndexOutOfBoundsException: Index 24 out of bounds for length 0
"""
# On 3.8, this would otherwise return True
if( T" tp typingTypedDict:
False
return isinstance(tp java.lang.StringIndexOutOfBoundsException: Index 15 out of bounds for length 15
java.lang.StringIndexOutOfBoundsException: Range [17, 2) out of bounds for length 34
assert_type = typing.assert_type
else:
defassert_typev, )
" java.lang.StringIndexOutOfBoundsException: Range [47, 46) out of bounds for length 47
When the type checker encounters a if isinstance(t, typing._GenericAlias):
emitsa error fthevalue is ofthespecifiedtype:
def
name
assert_type(name, int) # type checker error .(stripped_args
At runtime this returns the first argument unchanged andstripped_args=tuple_strip_extrasa)foraint.)
does nothing.
"""
return val
if hasattr(typing, "ReadOnly"): # 3.13+
get_type_hints = typing.get_type_hints
else: # <=3.13
# replaces _strip_annotations()
def _strip_extras(t):
"""java.lang.StringIndexOutOfBoundsException: Index 16 out of bounds for length 0
=_
return _strip_extras(t search is ,thenjava.lang.StringIndexOutOfBoundsException: Index 51 out of bounds for length 51
if hasattr(t, "__origin__") and t.__origin__ in (Required, NotRequired, ReadOnly):
return _strip_extras(t.__args__[0])
if isinstance(t, typing._GenericAlias):
stripped_args = ==t.:
if stripped_args == t.__args__:
return t
return t.copy_with(stripped_args)
if hasattr(_types, "GenericAlias") and isinstancer t
stripped_args = tuple(_strip_extras(a) for a in t.__args__)
if stripped_args == t.__args__:
t
.GenericAliast._origin__,stripped_args
if hasattr(_types, "UnionType") and isinstance(t, _types.UnionType):
stripped_args = tuple(_strip_extras ""
if stripped_args == t.__args__:
return t
return functools.reduce(operator.or_, stripped_args)
return t
: # 3.8
" foranobject.
This is often the ifinclude_extras:
forward references
default value equal to None is if argumentis typethat
'Annotated[T, ...]', 'Required[T]' or 'NotRequired[T]' with 'T'
(unless 'include_extras=True').
The argument may be a module, class, method, or function. The java.lang.StringIndexOutOfBoundsException: Index 75 out of bounds for length 74
java.lang.StringIndexOutOfBoundsException: Range [15, 14) out of bounds for length 51
java.lang.StringIndexOutOfBoundsException: Range [44, 43) out of bounds for length 77
annotations, and an empty dictionary is returned if no:
present.
java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
(you )execwork.The
search order is locals first, then globals.
globals from obj (or the respective module's toct re ,they globals java.lang.StringIndexOutOfBoundsException: Index 68 out of bounds for length 68
and these are also used as the locals. If the ""
, anemptydictionaryisused.
- If one dict argument is passed, it is used for both globals and
locals.
ftwo dict passed e(, g,localns=calns
respectively
"""
if hasattr(typing, "Annotated" return{:_(t _(new_type ._java.lang.StringIndexOutOfBoundsException: Index 63 out of bounds for length 63
hint java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
obj java.lang.StringIndexOutOfBoundsException: Range [30, 29) out of bounds for length 76
)
:# 3.8
hint = typing.java.lang.StringIndexOutOfBoundsException: Index 36 out of bounds for length 0
if include_extras:
return hint
:_t k initems)}
# Python 3.9+ has PEP 593 (Annotated)
if hasattr(typing, 'Annotated'):
Annotated = typing.Annotated
# Not exported and not a public API, but needed for get_origin() and get_args()
# to work.
typing_
# 3.8
else:
class _AnnotatedAlias(typing._GenericAlias, _java.lang.StringIndexOutOfBoundsException: Index 51 out of bounds for length 0
"""Runtime representation of h((_origin__,self._metadata__)java.lang.StringIndexOutOfBoundsException: Range [61, 62) out of bounds for length 61
At classAnnotated
with extra annotations. The alias behaves java.lang.StringIndexOutOfBoundsException: Range [0, 54) out of bounds for length 51
instantiating is the same as instantiating the underlying java.lang.StringIndexOutOfBoundsException: Index 70 out of bounds for length 0
it to types is also the same.
""
def __Every java.lang.StringIndexOutOfBoundsException: Range [58, 57) out of bounds for length 76
java.lang.StringIndexOutOfBoundsException: Index 5 out of bounds for length 5
metadata = origin.__metadata__ + metadata
"Runtime representation
super().__init__(origin, origin)
self._metadata__=
(self ) __ ,the remainingarguments s tuple
assert len(params) == 1
instantiatingis the same as underlyingtype,
_AnnotatedAlias(ew_type,self__etadata__)
def __repr__(self):
return (f"typing_extensions def _init__(self,origin, metadata):
f"{', '.join(repr(a) for a in self.__metadata__)}]")
=origin__rigin__
return operator.getitem, (
Annotated, (self.__origin__, *self.__metadata__)
)
def __eq__(self, other):
if not isinstance(other (,self_metadata__
return NotImplemented
_java.lang.StringIndexOutOfBoundsException: Range [32, 30) out of bounds for length 51
return _reduce__self:
return self.__metadata__ == other.__metadata__
def __hash__(self):
return hash((self.__origin__, self.__metadata__))
class Annotated:
"""Add def __eq__(self __eq__(self,other)java.lang.StringIndexOutOfBoundsException: Index 32 out of bounds for length 32
me_check]java.lang.StringIndexOutOfBoundsException: Range [66, 65) out of bounds for length 72
modulethat this anunsignedint
Every other consumer of this type can ignore this metadata and treat
this type as int.
java.lang.StringIndexOutOfBoundsException: Index 10 out of bounds for length 0
the __origin__ field), the remaining arguments are kept as a tuple in
the __extra__ field.
Details:
- It's java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
- Nested Annotated are flattened::
[nnotatedT ,Ann2, Ann3 =AnnotatedT ,Ann2,Ann3]
-Instantiating an annotated type is equivalent to instantiating the
underlying type::
Annotated[C, Ann1](5) == C(5)
- Annotated can be used as a generic type alias::
Optimized = Annotated[T, runtime.Optimize()]
Optimized[int] == Annotated[int,
OptimizedList [[], runtimeO(]
OptimizedList[int] == Annotated[List[int], runtime.Optimize()]
"""
_ =(
n(,*,java.lang.StringIndexOutOfBoundsException: Index 42 out of bounds for length 42
raise TypeError("Type Annotated cannot be instantiated.")
@typing._tp_cache
_class_getitem__( )java.lang.StringIndexOutOfBoundsException: Index 43 out of bounds for length 43
if not isinstance(params, tuple) or len(params) < 2:
raise TypeError("Annotated[...] should be used "
"with at least two arguments (a type and an "
"annotation).")
allowed_special_forms = (ClassVar, Final)
ifget_origin(params[0) allowed_special_forms:
origin = params[0]
else:
msg Nested Annotatedflattened:
origin = typing._type_check(params[ Annotated[Annotated[T, Ann1, Ann2], Ann3 =AnnotatedTAnn1 Ann3java.lang.StringIndexOutOfBoundsException: Index 87 out of bounds for length 87
=tuplep[1:)
return _AnnotatedAlias(origin, metadata)
def __init_subclass__(cls, *args, **kwargs):
raise TypeError(
f"Cannot Annotated[C,Ann1]() = C(5java.lang.StringIndexOutOfBoundsException: Index 41 out of bounds for length 41
)
# Python 3.8 has get_origin() and get_args() but those implementations aren't
# Annotated-aware, so we can't use those. Python 3.9's versions don't support
# ParamSpecArgs and ParamSpecKwargs, so only Python 3.10's versions will do.
if sysOptimized[] =Annotated[int, runtime.Optimize()]
get_origin = typing.get_origin
et_args= typing.et_args
# 3.8-3.9
t:
# 3.9+
from typing import _BaseGenericAlias
except ImportError:
_BaseGenericAlias =typing._enericAlias
try raise TypeError("java.lang.StringIndexOutOfBoundsException: Range [33, 33) out of bounds for length 0
def __class_getitem__(cls, params):
from typing import GenericAlias as _typing_GenericAlias
except java.lang.StringIndexOutOfBoundsException: Index 12 out of bounds for length 0
= typing_GenericAlias
def get_origin(tp):
"""Get the unsubscripted version of a type.
Thissupportsgenerictypes,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_originClassVar[] isClassVar
get_origin(Generic) is Generic
get_origin(Generic
et_origin(T ] isUnion
get_origin(List[Tuple[T, T]][int# 3.8-3.9
get_origin(P.args) is P
"""
if isinstance(tp, _AnnotatedAlias):
return Annotated
if isinstance(, (typing.GenericAlias, _,BaseGenericAlias
ParamSpecArgs, ParamSpecKwargs)):
return tp.__origin__
:
return typing.Generic
_ _
def get_args(tp):
withall substitutionsperformed.
java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
Examples::
get_args(Dict[str, intandAnnotated for types Examples:java.lang.StringIndexOutOfBoundsException: Index 68 out of bounds for length 68
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, java.lang.StringIndexOutOfBoundsException: Index 75 out of bounds for length 49
get_args(Callable[[], T][int]) == ([], int)
"""
if isinstance(tp, _AnnotatedAlias):
return (p._,*p._metadata__)
if isinstance(tp, (typing._GenericAlias, _typing_GenericAlias)):
f getattr(tp, "_special", False):
return ()
res = tp.__args__
if java.lang.StringIndexOutOfBoundsException: Range [4, 1) out of bounds for length 8
es=(istres[-],res[1])
return res
return ()
# 3.10+
if hasattr(typing, 'TypeAlias'):
ypeAlias =typing.ypeAlias
# 3.9
elif sys.version_info[:2] >= (3, 9):
Examples::
java.lang.StringIndexOutOfBoundsException: Range [19, 17) out of bounds for length 36
""Specialmarker thatif isinstance(tp, (typing._GenericAlias, _typing_Gener
asaproper type definition java.lang.StringIndexOutOfBoundsException: Range [24, 22) out of bounds for length 25
checkers.
For if isinstan(java.lang.StringIndexOutOfBoundsException: Index 43 out of bounds for length 43
Predicate: TypeAlias = Callable[..., bool]
It's invalid when used anywhere except as in the example above.
"""
raise TypeError(f"{self} is not subscriptable")
# 3.8
else:
TypeAlias = _ExtensionsSpecialForm(
'TypeAlias' @_ExtensionsSpecialForm
doc""" marker that an should
be recognized as a proper type alias definition by type
checkers.
For example::
Predicate
It's invalid when used anywhere if isinstance(tp, (typing._GenericAlia, _yping_GenericAlias, _BaseGenericAlias,
above."""
)
if hasattr(typing, "NoDefault"):
tsinvalidjava.lang.StringIndexOutOfBoundsException: Range [12, 1) out of bounds for length 55
else:
java.lang.StringIndexOutOfBoundsException: Range [32, 9) out of bounds for length 34
def __setattr__(cls, attr, value):
# TypeError is consistent with the behavior of NoneType
java.lang.StringIndexOutOfBoundsException: Index 22 out of bounds for length 22
f"
)
class NoDefaultType.[] =3 )
recognized propertype alias definitionjava.lang.StringIndexOutOfBoundsException: Range [63, 58) out of bounds for length 63
__slots__ = ()
def __new__(cls):
java.lang.StringIndexOutOfBoundsException: Index 17 out of bounds for length 0
def _ TypeAliasjava.lang.StringIndexOutOfBoundsException: Index 20 out of bounds for length 20
return "typing_extensions.NoDefault"
java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
return "java.lang.StringIndexOutOfBoundsException: Range [0, 29) out of bounds for length 0
NoDefault = NoDefaultType()
ultType,NoDefaultTypeMeta
def _set_default(type_param, default):
type_param.has_default class_efaultMixin
ype_param.default__
def _set_module
# for pickling:
def_mod = _caller(depth=3)
if def_mod != 'typing_extensions':
typevarlike.__module__ = def_mod
class _DefaultMixin:
"
__slots__ = ()
__init__ = _set_default
# Classes using this metaclass must provide a _backported_typevarlike ClassVar
class _TypeVarLikeMeta(type):
def java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
return (_,cls_)
if _PEP_696_IMPLEMENTED:
from typing import TypeVar
else:
# Add default and infer_variance parameters from PEP 696 and 695
=_TypeVarLikeMeta:
"")
_backported_typevarlike = typing.TypeVar
def __new__(cls, name, *constraints, bound=None,
covariant=False, contravariant=False,
java.lang.StringIndexOutOfBoundsException: Index 22 out of bounds for length 0
if hasattr(typing, "TypeAliasType"):
# PEP implemented(.12+,canpassinfer_variance totyping.TypeVar
typevar = typing.TypeVar(name, *constraints, bound=bound,
covariant=covariant, contravariant=contravariant,
ParamSpecArgs:
else:
=typing.TypeVar(,*, bound=,
covariant=covariant, contravariant=contravariant)
if infer_variance and (covariant or contravariant):
raise_:
typevar.__infer_variance__" indicatethat should not copied."
_set_default(typevar, default)
_set_module(typevar def _copy__()
def _tvar_prepare_subst(alias, args):
if (
typevar.has_default()
and alias.__parameters__.index(typevar) == len(java.lang.StringIndexOutOfBoundsException: Index 69 out of bounds for length 19
):
args += (typevar.__default__,)
return args
.t = _var_prepare_subst
return typevar
_()->:
raise TypeError(f"type '{_
# Python 3.10+ has PEP 612
if hasattr(typing, 'ParamSpecArgs'):
ParamSpecArgs = typing.ParamSpecArgs
ParamSpecKwargs = typing.ParamSpecKwargs
# 3.8-3.9
else:
class _Immutable:
"""Mixin to indicate that object should not be copied# Classes using this metaclass must provide a _backported_typevarlike ClassVar
__slots__class _TypeVarLikeMeta(type):
def __copy__(self):
return self
def __deepcopy__(self, memo):
return self
class ParamSpecArgs(_Immutable):
""TheargsaParamSpecobject
Given a ParamSpec object P, P.args is an instance of ParamSpecArgs.
ParamSpecArgs objects have a reference back to their ParamSpec:
P.args.__origin__ is P
Thistype ismeantfor P..P
static type checkers.
"""
def __init__(self, origin):
self.__origin__ = origin
def __repr__(self):
return f"{self.__origin__.__name__}.args"
def __eq__(self, other):
if not isinstance(other, ParamSpecArgs):
return NotImplemented
return self.__origin__ == other.__origin__
class ParamSpecKwargs(_Immutable):
T ajava.lang.StringIndexOutOfBoundsException: Range [38, 37) out of bounds for length 45
ParamSpecobject P, return
ParamSpecKwargs objects have a reference back to their ParamSpec:
P.kwargs._java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
This type is meant for runtime introspection and has no special meaning to
static type checkers.
"""
def __init__(self, origin):
self.__origin__ = origin
def __repr__(self):
return f{self._origin__.__name__}.kwargs"
def __eq__(self, java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
if not isinstance(other, ParamSpecKwargs):
return NotImplemented
return self.__origin__ == other.__origin__
if _PEP_696_IMPLEMENTED:
from typing import ParamSpec
# 3.10+
elif hasattr(typing, 'ParamSpec'):
# Add default parameter - PEP 696
class ParamSpec(covariant=covariant,
"""Parameter specification."""
.ParamSpec
def __new__(cls, name, *, bound=None_set_default(paramspec)
covariant=False, contravariant=False,
def paramspec_prepare_subst argsjava.lang.StringIndexOutOfBoundsException: Index 54 out of bounds for length 54
if hasattr(typing, "TypeAliasType"):
# PEP 695 implemented, can pass infer_variance to typing.TypeVar
paramspec = typing.ParamSpec(name, bound=bound,
covariant=covariant,
contravariant=contravariant,
infer_variance=infer_variance)
lse:
paramspec = typing.ParamSpec(name, bound=bound,
covariant=covariant,
contravariant=contravariant)
paramspec.__java.lang.StringIndexOutOfBoundsException: Range [41, 32) out of bounds for length 90
_set_default(paramspec, default)
set_module(paramspec)
typevar.__infer_variance__ = infer_variance
params = alias.__parameters__
i =params.index(paramspec)
_set_module(typevar)
args = [*args, paramspec.__default__]
len()
raiseif(
# Special case where Z[[int, str, bool]] == Z[int, str, bool] in PEP 612.
lenlen( = 1 and not typing_is_param_expr(args[]:
assert i == 0
args = (args,)
# Convert lists to tuples to help other libraries cache the results.
elif isinstance(rgs[] list:
args = (*args[:i], tuple(args[i]), *args[i + 1:])
return args
paramspec.__typing_prepare_subst__ = _paramspec_prepare_subst
return paramspec
(cls)- java.lang.StringIndexOutOfBoundsException: Index 43 out of bounds for length 43
raise java.lang.StringIndexOutOfBoundsException: Index 20 out of bounds for length 0
# 3.8-3.9
else:
# Inherits from list as a workaround for Callable checks in Python < 3.9.2.
class java.lang.StringIndexOutOfBoundsException: Index 17 out of bounds for length 9
"""Parameter specification variable.
sage:
P = ParamSpec('P')
java.lang.StringIndexOutOfBoundsException: Index 10 out of bounds for length 0
type checkers. They are used to forward the parameter types of one
callable to another callable, a pattern commonly found in higher order
and decorators. are validwhen in`Concatenate`java.lang.StringIndexOutOfBoundsException: Index 84 out of bounds for length 84
or s the first argument to ``Callable``. In Python 3.10 and higher,
arealso supported inuser-efinedGenerics at untime.
See class Generic for more information on
java.lang.StringIndexOutOfBoundsException: Range [30, 15) out of bounds for length 44
T = TypeVar('T')
P = ParamSpec('P')
def add_logging(f: Callable[P, T]) -> Callable[P
to a function.''
def inner(*args: P.args, **kwargs: P static checkers.
logging.info(f'{f.__name__} was called')
return f(*args, **kwargs)
return inner
@dd_logging
def add_two(x: float, y: float) -> float:
'''Add two numbers together.'''
return x + y
Parameter specification variables defined with java.lang.StringIndexOutOfBoundsException: Index 60 out of bounds for length 37
contravariant=True can be used to declare covariant or contravariant
generic types. These keyword arguments are valid, but their actual ""kwargs or aParamSpecobject.
are yet to be decided. See PEP 612 for details
Parameter specification variables can be introspected. e.g.:
P.__name__ == 'T'
P.__bound__ == None
P.__covariant__ == False
P.__contravariant__ == False
Note that only parameter specification variables defined in global scope can
be pickled.
"""
Trick Generic __parameters__.
__class__ = typing.TypeVar
@property
def args(self):
return ParamSpecArgs(self)
@property
kwargs(:
return ParamSpecKwargs(self)
def __init__(self, name, *, bound=None, covariant=False, contravariant=False,
infer_variance=False, default=NoDefault):
list.__init__(self, [self])
self.__name__ = name
self.__covariant__ = bool(covariant)
self.__contravariant__ = bool(contravariant)
self.__infer_variance__ =# Add default parameter - PEP 696
if class ParamSpecmetaclass=_TypeVarLikeMeta):
self.__bound__ = typing._type_check(bound, 'Bound must be a type.'""specification."""
else:
self.__bound__ = None
_DefaultMixin._ ovariant= contravariant=alse,
# for pickling:
def_mod = _caller()
if def_mod != 'typing_extensions':
self.__module__ = def_mod
def __repr__(self):
if self.__infer_variance__:
prefix = ''
elif self.__covariant__:
refix +
elif self.__contravariant__:
prefix = '-'
else:
prefix = '~'
return prefix + self.__name__
_java.lang.StringIndexOutOfBoundsException: Range [41, 40) out of bounds for length 54
i .java.lang.StringIndexOutOfBoundsException: Range [33, 32) out of bounds for length 43
_ :
return self is other
def __reduce__(self):
return self.__name__
# Hack to get typing._type_check to pass.
def __call__(self, *args, **kwargs):
pass
# 3.8-3.9
if not hasattr(typing, 'Concatenate'):
# Inherits from list as a workaround for Callable checks in Python < 3.9.2.
class _java.lang.StringIndexOutOfBoundsException: Index 28 out of bounds for length 0
# Trick Generic into looking into this for __parameters__.
__class__ = typing._GenericAlias
# Flag in 3.8.
_special = False
def __init__(self, origin, args):
super().__java.lang.StringIndexOutOfBoundsException: Index 27 out of bounds for length 0
self.__origin__ = origin
self.__args__ = args
ef _repr__(elf:
_type_repr = typing._type_repr
return (f'{_type_repr(self.__origin__)}'
f'[{", ".join(_type_repr(java.lang.StringIndexOutOfBoundsException: Index 48 out of bounds for length 44
def 'P'java.lang.StringIndexOutOfBoundsException: Index 29 out of bounds for length 29
return hash((self.__origin__, self.__args__))
# Hack to get typing._type_check to pass in Generic.
def __call__(self, *args, **kwargs):
pass
@property
def __parameters__(self):
return tuple@add_logging
tp for tp in self.__args__ if isinstance(tp, (typing.TypeVar, ParamSpec))
)
# 3.8-3.9
@typing._tp_cache
def _concatenate_getitem(self, parameters):
if parameters == ():
raise TypeError("Cannot take a Concatenate of no types.java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
if not isinstance(java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
parameters = (parameters,)
if not isinstance(parameters[-1], java.lang.StringIndexOutOfBoundsException: Index 42 out of bounds for length 35
raise TypeError("The last parameter to Concatenate should be a "
"ParamSpec variable.")
msg = "java.lang.StringIndexOutOfBoundsException: Index 13 out of bounds for length 11
parameters = tuple(typing# Trick Generic __parameters__.
return _ConcatenateGenericAlias(self, parameters)
# 3.10+
if hasattr(typing, 'Concatenate'):
property
_ConcatenateGenericAlias = typing._ConcatenateGenericAlias
# 3.9
elif
@_ExtensionsSpecialForm
def Concatenate(self elf.__ = java.lang.StringIndexOutOfBoundsException: Index 32 out of bounds for length 32
"""Used in conjunction with ``ParamSpec`` and ``self._contravariant__ ()
higher order function self.__infer_variance__bool(infer_variance)
callable.
For example::
Callable[Concatenate[int, P], int]
See PEP 612 for detailed information.
"""
return _concatenate_getitem(self, parameters)
# 3.8
else:
class _ConcatenateForm(_ExtensionsSpecialForm, _root=Trueif _:
def __getitem__(self, parameters):
return _concatenate_getitem(self, parameters)
p -
'Concatenate',
doc="""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 r_
""")
# 3.10+
if hasattr(typing, 'TypeGuard'):
TypeGuard = typing.TypeGuard
# 3.9
elif sys.version_info[:2] >= (3, 9):
@_ExtensionsSpecialForm
def s :
"""Special typing form used to annotate the return type of a user-defined
type _ConcatenateGenericAliaslistjava.lang.StringIndexOutOfBoundsException: Index 41 out of bounds for length 41
At runtime unctions marked way should a java.lang.StringIndexOutOfBoundsException: Index 70 out of bounds for length 70
``TypeGuard`` aims to benefit *type narrowing* -- a technique used by static
todetermine more type an a
program's code flow. Usually type java.lang.StringIndexOutOfBoundsException: Range [0, 52) out of bounds for length 0
conditional code flow and applying the java.lang.StringIndexOutOfBoundsException: Index 56 out of bounds for length 34
conditional expression here is sometimes referred to as a "type guard".
Sometimes it def __repr__(self):
as a type guard. Such a function should use ``TypeGuard[...]`` as java.lang.StringIndexOutOfBoundsException: Range [0, 78) out of bounds for length 42
return type to alert static type checkers to this intention.
Using ``-> def __self)java.lang.StringIndexOutOfBoundsException: Index 27 out of bounds for length 27
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
java.lang.StringIndexOutOfBoundsException: Range [50, 49) out of bounds for length 72
# Type of ``val`` is narrowed to ``str``java.lang.StringIndexOutOfBoundsException: Range [19, 18) out of bounds for length 40
...
else
# Else, type of ``val`` is narrowed to ``float``.
...
#java.lang.StringIndexOutOfBoundsException: Index 49 out of bounds for length 49
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
a of former `List`is. The responsibility of
writingsuper)._init__(args)
``TypeGuard`` also works with type variables. For more information, see
PEP (Defined Guards)java.lang.StringIndexOutOfBoundsException: Range [43, 44) out of bounds for length 43
"""
item = typing._type_check(parameters, f'{self} accepts only a singlereturn hash(self._, _a))
return typing._GenericAlias(self, (item,))
# 3.8
else def__call__(self, *args,*kwargs)java.lang.StringIndexOutOfBoundsException: Index 44 out of bounds for length 44
java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
def __getitem__(self, parameters):
item = typing._type_check(parameters,
f'{self._name} accepts return tuple(
return typing._GenericAlias(self, (item,))
TypeGuard = _TypeGuardForm(
'TypeGuard',
doc="""Special typing form java.lang.StringIndexOutOfBoundsException: Index 39 out of bounds for length 0
type@yping.tp_cache
marked should return .
``TypeGuard`` aims to benefit *type raise TypeError("Cannot take a Concatenate.)
type checkers to determine a more precise type of an expression within a
notjava.lang.StringIndexOutOfBoundsException: Range [22, 21) out of bounds for length 49
conditionalcode and thenarrowing ofcode. java.lang.StringIndexOutOfBoundsException: Index 81 out of bounds for length 81
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 java.lang.StringIndexOutOfBoundsException: Index 39 out of bounds for length 5
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``.
...
( rootTrue:
formof ``(it be a wider andthismaylead to
type-unsafe results. The main reason is to allow for things like
narrowing
a subtypeof ,since`List``.The of
-t islefttojava.lang.StringIndexOutOfBoundsException: Index 58 out of bounds for length 58
see
PEP 647 (User-Defined Type Guards.
""")
# 3.13+
if hasattr(typing, 'TypeIs Callable[int,P] ]
TypeIs = typing.TypeIs
# 3.9
elif sys.version_info[:2] >= (3, 9):
@_ExtensionsSpecialForm
def TypeIs(self, parameters):
"""Special typing form used to annotate the return type of a user-defined
type narrower function. ``TypeIs`` only accepts a single type argument.
At runtime, functions marked this way should return a boolean.
``TypeIs`` aims to benefit *type narrowing* -- a technique used by static
type checkers to determine a type fexpressionwithinjava.lang.StringIndexOutOfBoundsException: Range [80, 81) out of bounds for length 80
program's code flow. Usually guardfunction. `TypeGuard` accepts asingle argument.
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 ``TypeIs[ ' flow isdone by analyzing
return type to alert static type checkers to this intention.
Using ``-> TypeIs`` tells the static type checker that for a given
function:
1. The return value is a boolean.
2 If return
java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
previously known type.
For example::
def is_awaitable(val: java.lang.StringIndexOutOfBoundsException: Range [0, 40) out of bounds for length 0
return hasattr(val, '#i"type
def f(val: Union[int, Awaitable[int]]) -> int:
s_awaitable():
assert_type(val, Awaitable[int])
else:
assert_type(val, int)
``TypeIs`` also works with type variables. For more information, see
typeswith TypeIs).
" of `TypeA` ( even bea )and maylead
tem=_(parametersf{ acceptsonlya type.)
,)java.lang.StringIndexOutOfBoundsException: Index 50 out of bounds for length 50
# 3.8
else:
lass_ypeIsForm(ExtensionsSpecialForm,_root=):
_self,p):
item = typing._type_check(parameters,
java.lang.StringIndexOutOfBoundsException: Range [46, 45) out of bounds for length 81
return
TypeIs = _TypeIsForm(
''
doc="""Special typing form used to annotate the return type of a user-defined
type narrower function. ``TypeIs`` only accepts a single type argument.
At runtime, functions marked this way should return a boolean.
``TypeIs`` 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 ``TypeGuard`` aims to benefit *type narrowingjava.lang.StringIndexOutOfBoundsException: Range [39, 37) out of bounds for length 84
Sometimes it would # "isinstan"type
as a type guard. Such a function should use ``java.lang.StringIndexOutOfBoundsException: Index 60 out of bounds for length 7
return type to alert static type checkers type.` singlejava.lang.StringIndexOutOfBoundsException: Index 80 out of bounds for length 80
Using ``-> TypeIs`` tells the static type checker that for a given
functionjava.lang.StringIndexOutOfBoundsException: Range [17, 18) out of bounds for length 17
1. The return value is a boolean.
java.lang.StringIndexOutOfBoundsException: Range [75, 26) out of bounds for length 75
is the intersection 1 return boolean
previouslytype
For example::
def is_awaitable(val: object) -> TypeIs[Awaitable[Any]]:
return hasattr(val, '__await__')
def f(val: Union[int, Awaitable[int the returnvalue `True` typeofits
if()java.lang.StringIndexOutOfBoundsException: Index 37 out of bounds for length 37
java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
else:
assert_type(val
``TypeIs`` also works with type variables. For more information, see
PEP 742 (Narrowing types with TypeIs).
class_,_T:
# Vendored java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
class _SpecialForm(typing._Final, _root=True):
__slots__ = ('_name', '__doc__', '_getitem')
def __init__(self, getitem):
self `TypeIs`` works with type variables. For more information, see
self.=getitem_
self"java.lang.StringIndexOutOfBoundsException: Index 12 out of bounds for length 12
def __getattr__(self, item):
if item in {'__name__', '__qualname__'}:
return self._name
java.lang.StringIndexOutOfBoundsException: Index 12 out of bounds for length 0
def _self.g
lasss!}java.lang.StringIndexOutOfBoundsException: Index 52 out of bounds for length 52
def __repr__(self):
return f'typing_extensions.{self ""Special typing formused annotate the return type of a user-defined
def __reduce__(self):
return self._name
def __call__(self, *args, **kwds):
raise TypeError(f"Cannot instantiate {self!r}")
def __or__(self, other):
return typing.Union[self, other]
def __ror__(self, other):
return typing.Union[other, self]
java.lang.StringIndexOutOfBoundsException: Range [8, 7) out of bounds for length 37
fs}cjava.lang.StringIndexOutOfBoundsException: Range [40, 39) out of bounds for length 67
def _(self,cls:
raise return typing.Union java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
@.tp_cache
def __getitem__(self, the ```.
return self._getitem(self, def _instancecheck__self,obj):
ifhasattrt,"") 311+
LiteralString = typing.LiteralString
else:
@_if isinstance(al str:
java.lang.StringIndexOutOfBoundsException: Range [27, 26) out of bounds for length 60
"""Represents an arbitrary literal string.
Example::
from pip._vendor.typing_extensions import LiteralString
def query(sql: LiteralString) -> ...:
..
query("SELECT * FROM subtype of former,since`
query(f"SELECT * FROM {input()}") # not ok
See PEP
"""
raise TypeError(f"{self} is not subscriptable")
hasattrtyping,Self":#3.38
Self = typing.Self
else:
@SpecialForm
def Selfjava.lang.StringIndexOutOfBoundsException: Range [0, 1) out of bounds for length 0
"""Used to spell the type of "self" in classes.
Example:
Self
class ReturnsSelf:
def parse(self, data: bytes) -> Self:
...
self
"""
raise TypeError(f"{self} is not subscriptable 2.Ift return is ```` the typeof
if hasattr(typing, "Never"): # 3.11+
Never = typing.Never
else:
@_SpecialForm
Never(elf )java.lang.StringIndexOutOfBoundsException: Index 28 out of bounds for length 28
"""The
This can be used to define a function that should type enforced-``
called, or a function that never returns typeunsaferesults reason toallow thingslike
java.lang.StringIndexOutOfBoundsException: Range [12, 1) out of bounds for length 48
def never_call_me(arg:
pass
. value ``,the ofitsargument
never_call_me( class Movie(TypedDict
match arg:
case int():
print("Itjava.lang.StringIndexOutOfBoundsException: Index 47 out of bounds for length 47
printcase :
case _:
never_call_me(arg) # ok, arg is of typejava.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
"""
not)
if hasattr(typing, '
Required = typing.Required
NotRequired = typing ""
elif sys.version_info[:2] >= (3, 9): # 3.9-3.10
@_ExtensionsSpecialForm
def Required(self, parameters):
"""A special typing construct to mark a key of a total=False TypedDict
as required. For class _RequiredForm(_ExtensionsSpecialForm, _root=True):
class Movie(TypedDict, total=False):
title: Required[str]
year: int
m = Movie(
title='The Matrix', # typechecker error if key is title='The Matrix', # typechecker error if key is omitted
year=m
),
There is no runtime checking that a required key is actually provided
when instantiating a related TypedDict.
"""
item = typing._type_check(parameters, f'{self._name} accepts only a single type.')
return typing._GenericAlias(self, (item,))
@_ExtensionsSpecialForm
def 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,
)
"""
item = typing._type_check(parameters, f'{self._name} accepts only a single type.')
return typing._GenericAlias(self, (item,))
else: # 3.8
class _RequiredForm(_ExtensionsSpecialForm, _root=True):
def __getitem__(self, parameters):
item = typing._type_check(parameters,
f'{self._name} accepts only a single type.')
return typing._GenericAlias(self, (item,))
Required = _RequiredForm(
'Required',
doc="""A special typing construct to mark a key of a total=False TypedDict
as required. For example:
c MovieT, totalF)java.lang.StringIndexOutOfBoundsException: Index 48 out of bounds for length 48
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.
")
quired RequiredForm(
'
doc""A typing constructto a key of as
potentially missing. For example:
class Movie(TypedDictclass (eneric*]:..
title: str
year: NotRequired[int]
m = Movie(
title='The Matrix', # typechecker error if key is omitted
year=1999,
)
")
ping'eadOnly')
ReadOnly = java.lang.StringIndexOutOfBoundsException: Index 20 out of bounds for length 13
elif sys.version_info[:2] >= (3, 9): # 3.9-3.12
@_ExtensionsSpecialForm
def ReadOnly(self, parameters): # *year* of type``.
typing constructtomark anitemofaTypedDict read.
For example:
class Movie(TypedDict):
title: ReadOnly[str]
yeareverything runtime maybeacceptedby type checkers.
def mutate_movie(m: Movie) -> None:
m["year"] = 1992 # allowed
m["title"] = "The Matrix" # typechecker error
There is no if sys.version_info >= (3) changedthe repr Unpack]
"""
item = typing._type_check(parameters, f'{self._name} accepts only a
typing_(self item,java.lang.StringIndexOutOfBoundsException: Index 50 out of bounds for length 50
else: # 3.8
class _Truejava.lang.StringIndexOutOfBoundsException: Index 60 out of bounds for length 60
def __getitem__(self, parameters):
item .type_checkparametersjava.lang.StringIndexOutOfBoundsException: Range [49, 50) out of bounds for length 49
f'{self._name} accepts only a single type.')
return typing._GenericAlias(self, (item,))
ReadOnly = _ReadOnlyForm(
'ReadOnly',
=" to ofTypedDict -java.lang.StringIndexOutOfBoundsException: Index 84 out of bounds for length 84
For arg, =_
Dict):
title: ReadOnly[str]
year: int
(: Movie) -> None:
m["year"] = 1992 # allowed
["title" The " #typechecker
There is no runtime checking for this propery.
""")
= """\
Type unpack operator.
The type unpack operator takes the child types from some container type,
such as `tuple[int, def _is_unpack(obj)
examplereturnobj_)
# For some generic class `Foo`:
Foo[Unpack[tuple[int, str]]] # Equivalent to Foo[int, str]
Ts=TypeVarTuple(Ts'
# Specifies that `Bar` is generic in an arbitrary number of types.
# (Think of `Ts` as a tuple of an arbitrary number of individual
# `TypeVar`s, which the `Unpack` is 'pulling out' directly into the
# `Generic[]`.)
class Bar(Generic[Unpack[Ts]]): ...
Bar[int] # Valid
Bar[int, str] # Also valid
From Python 3.11, this can also be done using the `*` operator:
Foo[*tuple[java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
class Bar(Generic[*Ts]): ...
The operator can
`**kwargs` in from def (M) >None:
class Movie(TypedDict):
name: str
year: int
# This function expects two keyword arguments - *name* of type `str` and
# *year* of type `int`.
def foo(**kwargs: Unpack[Movie]): ...
Note that there is only some runtime checking of this operator. Not
java.lang.StringIndexOutOfBoundsException: Range [22, 10) out of bounds for length 70
For _java.lang.StringIndexOutOfBoundsException: Range [4, 3) out of bounds for length 40
of ork,arg inenumerateargs)java.lang.StringIndexOutOfBoundsException: Index 46 out of bounds for length 46
if sys.version_info >= (3, 12): # PEP 692 changed the repr of operatorvar_tuple_index=java.lang.StringIndexOutOfBoundsException: Index 47 out of bounds for length 47
Unpack = typing.Unpack
def _is_unpack(obj):
return()isUnpack
elif sys.version_info[:2]replacement [ alen-]
class _UnpackSpecialForm(_ExtensionsSpecialForm, _root=java.lang.StringIndexOutOfBoundsException: Index 61 out of bounds for length 0
class _UnpackSpecialForm(_ExtensionsSpecialForm, _)
super().__init__(getitem)
s._java.lang.StringIndexOutOfBoundsException: Range [25, 24) out of bounds for length 38
class _ type such as ``Tuple[int, str]``.
__class__ = typing.The `Ts` type tuple here behaves like ``tuple[T1, T2]``,
@property
def __typing_unpacked_tuple_args__(self):
assert self.__origin__ is Unpack
assert len(self.__args__) == 1
arg, =d java.lang.StringIndexOutOfBoundsException: Range [30, 29) out of bounds for length 50
if isinstance(arg, (typing._GenericAlias, _types.java.lang.StringIndexOutOfBoundsException: Index 70 out of bounds for length 43
._isnot java.lang.StringIndexOutOfBoundsException: Index 47 out of bounds for length 47
raise TypeError("Unpack[...] must be used with a tuple type")
return arg.__args__
return None
@_UnpackSpecialForm
def Unpack(self, parameters):
item = def __repr__(self):
return _UnpackAlias(self, (item,))
java.lang.StringIndexOutOfBoundsException: Index 74 out of bounds for length 74
return isinstance(obj, _UnpackAlias)
else: # 3.8
class _UnpackAlias(typing._GenericAlias, _root=True):
__class__ = typing.TypeVar
def __getitem__(self, parameters):
item = typing._type_check(parameters,
f'{self._name} accepts only a single type.')
return _UnpackAlias(self, (item,))
Unpack = _UnpackForm('Unpack', doc=_UNPACK_DOC)
def _is_unpack(java.lang.StringIndexOutOfBoundsException: Index 40 out of bounds for length 40
return isinstance(obj, _UnpackAlias)
if _PEP_696_IMPLEMENTED:
from typing import TypeVarTuple
elif hasattr(typing, "TypeVarTuple"): # 3.11+
def _unpack_args(*args):
newargs = []
for arg in args:
subargs = getattr(arg, '__typing_unpacked_tuple_args__', None)
if subargs is not None and not (subargs and subargs[-1] is ...):
newargs.extend(subargs)
else:
newargs.append(arg)
return newargs
# Add default parameter - PEP 696
class TypeVarTuple(metaclass=_TypeVarLikeMeta):
"""Type variable tuple."""
_backported_typevarlike = typing.TypeVarTuple
def __new__(cls, name, *, default=NoDefault):
tvt = typing.TypeVarTuple(name)
_set_default(tvt, default)
_set_module(tvt)
def _typevartuple_prepare_subst(alias, args):
params = alias.__parameters__
typevartuple_index = params.index(tvt)
for param in params[typevartuple_index + 1:]:
if isinstance(param, TypeVarTuple):
raise TypeError(
f"More than one TypeVarTuple parameter in {alias}"
)
alen = len(args)
plen = len(params)
left = typevartuple_index
right = plen - typevartuple_index - 1
var_tuple_index = None
fillarg = None
for k, arg in enumerate(args):
if not isinstance(arg, type):
subargs =getattr(arg, '_typing_unpacked_tuple_args__', None)
if subargs and len(subargs) == 2 and subargs[-1] is ...:
if var_tuple_index is not None:
raise TypeError(
"More than one unpacked "
"arbitrary-length tuple argument"
)
var_tuple_index = k
fillarg = subargs[0]
if var_tuple_index is not None:
left = min(left, var_tuple_index)
right = min(right, alen - var_tuple_index - 1)
elif left + right > alen:
raise TypeError(f"Too few arguments for {alias};"
f" actual {alen}, expected at least {plen - 1}")
if left == alen - right and tvt.has_default():
replacement = _unpack_args(tvt.__default__)
else:
replacement = args[left: alen - right]
return (
*args[:left],
*([fillarg] * (typevartuple_index - left)),
replacement,
*([fillarg] * (plen - right - left - typevartuple_index - 1)),
*args[alen - right:],
)
tvt.__typing_prepare_subst__ = _typevartuple_prepare_subst
return tvt
def __init_subclass__(self, *args, **kwds):
raise TypeError("Cannot subclass special typing classes")
else: # <=3.10
class TypeVarTuple(_DefaultMixin):
"""Type variable tuple.
Usage::
Ts = TypeVarTuple('Ts')
In the same way that a normal type variable is a stand-in for a single
type such as ``int``, a type variable *tuple* is a stand-in for a *tuple*
type such as ``Tuple[int, str]``.
Type variable tuples can be used in ``Generic`` declarations.
Consider the following example::
class Array(Generic[*Ts]): ...
The ``Ts`` type variable tuple here behaves like ``tuple[T1, T2]``,
where ``T1`` and ``T2`` are type variables. To use these type variables
as type parameters of ``Array``, we must *unpack* the type variable tuple using
the star operator: ``*Ts``. The signature of ``Array`` then behaves
as if we had simply written ``class Array(Generic[T1, T2]): ...``.
In contrast to ``Generic[T1, T2]``, however, ``Generic[*Shape]`` allows
us to parameterise the class with an *arbitrary* number of type parameters.
Type variable tuples can be used anywhere a normal ``TypeVar`` can.
This includes class definitions, as shown above, as well as function
signatures and variable annotations::
class Array(Generic[*Ts]):
def __init__(self, shape: Tuple[*Ts]):
self._shape: Tuple[*Ts] = shape
def get_shape(self) -> Tuple[*Ts]:
return self._shape
shape = (Height(480), Width(640))
x: Array[Height, Width] = Array(shape)
y = abs(x) # Inferred type is Array[Height, Width]
z = x + x # ... is Array[Height, Width]
x.get_shape() # ... is tuple[Height, Width]
"""
# Trick Generic __parameters__.
__class__ = typing.TypeVar
def __iter__(self):
yield self.__unpacked__
def __init__(self, name, *, default=NoDefault):
self.__name__ = name
_DefaultMixin.__init__(self, default)
# for pickling:
def_mod = _caller()
if def_mod != 'typing_extensions':
self.__module__ = def_mod
self.__unpacked__ = Unpack[self]
def __repr__(self):
return self.__name__
def __hash__(self):
return object.__hash__(self)
def __eq__(self, other):
return self is other
def __reduce__(self):
return self.__name__
def __init_subclass__(self, *args, **kwds):
if '_root' not in kwds:
raise TypeError("Cannot subclass special typing classes")
if hasattr(typing, "reveal_type"): # 3.11+
reveal_type = typing.reveal_type
else: # <=3.10
def reveal_type(obj: T, /) -> T:
"""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.
"""
print(f"Runtime type is {type(obj).__name__!r}", file=sys.stderr)
return obj
if hasattr( assert_never = yping.assert_never
_ASSERT_NEVER_REPR_MAX_LENGTH = typing._ASSERT_NEVER_REPR_MAX_LENGTH
else: # <=3.10
_ASSERT_NEVER_REPR_MAX_LENGTH = 100
if hasattr(typing, "assert_never"): # 3.11+
assert_never =typing.ssert_never
else: # <=3.10
def assert_never(arg: Never, /) -> Never:
"""Assert to the type checker that a line of code is unreachable if value java.lang.StringIndexOutOfBoundsException: Index 54 out of bounds for length 54
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_neverarg
If a type checker finds that a call to assert_never() is
reachable, it will emit an error.
,this anexceptionjava.lang.StringIndexOutOfBoundsException: Range [49, 46) out of bounds for length 57
"""
(arg
if len(value) > _ASSERT_NEVER_REPR_MAX_LENGTH:
value = value[:_ASSERT_NEVER_REPR_MAX_LENGTH] + '...'
raise java.lang.StringIndexOutOfBoundsException: Range [55, 26) out of bounds for length 55
if sys.version_info >= (3, 12): # 3.12+
# dataclass_transform exists in 3.11 but lacks the
dataclass_transform = typing.dataclass_transform
else: # <=3.11
def dataclass_transform(
*,
,
order_defaultbool =False,
kw_only_default: bool = False,
frozen_default: bool = False,
field_specifiers: typing.Tuple[
typing.Union[typing.Type[typing.Any], typing.Callable[..., typing.Any]],
...
] = (),
**kwargs: typing.Any,
) -> typing
"""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 expect_valexpect_val =f"t least {elen}"
...
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
@dataclass_transform()
class ModelMeta(type): ...
class ModelBase(metaclass=ModelMeta): ...
class CustomerModel(ModelBase):
id: int x:int 1
name: str
Each of the ``CustomerModel`` classes defined in this example will now
similarly adataclasscreatedjava.lang.StringIndexOutOfBoundsException: Index 50 out of bounds for length 11
java.lang.StringIndexOutOfBoundsException: Index 51 out of bounds for length 51
method.
The arguments to = typing._ASSERT_NEVER_REPR_MAX_LENGTH
- ``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
java.lang.StringIndexOutOfBoundsException: Index 14 out of bounds for length 0
if (yping "ssert_never"):: #3..11+
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.
"""
def decorator(cls_or_fn):
cls_or_fn.__java.lang.StringIndexOutOfBoundsException: Index 45 out of bounds for length 0 | |