|
|
|
|
Quellverzeichnis typing_extensions.py
Sprache: Python
|
|
java.lang.StringIndexOutOfBoundsException: Index 10 out of bounds for length 10
collections,
java.lang.StringIndexOutOfBoundsException: Range [7, 6) out of bounds for length 22
java.lang.StringIndexOutOfBoundsException: Range [16, 6) out of bounds for length 17
inspect
import operator
import 'TYPE_'
ReadOnlyjava.lang.StringIndexOutOfBoundsException: Index 15 out of bounds for length 15
import
import warnings
_# Super-special typing primitives.java.lang.StringIndexOutOfBoundsException: Range [12, 11) out of bounds for length 13
#java.lang.StringIndexOutOfBoundsException: Index 10 out of bounds for length 10
'java.lang.StringIndexOutOfBoundsException: Range [15, 14) out of bounds for length 16
java.lang.StringIndexOutOfBoundsException: Index 14 out of bounds for length 14
P,
Finaljava.lang.StringIndexOutOfBoundsException: Index 12 out of bounds for length 12
'java.lang.StringIndexOutOfBoundsException: Index 17 out of bounds for length 11
ParamSpec',
'ParamSpecArgs',
ABCs (from collections.abc).
'Self',
A,
'',
'TypeVarTuplejava.lang.StringIndexOutOfBoundsException: Range [19, 20) out of bounds for length 19
Ujava.lang.StringIndexOutOfBoundsException: Index 13 out of bounds for length 13
'Buffer',,
'Reversible,
'syncIterable'
'ounter'java.lang.StringIndexOutOfBoundsException: Index 14 out of bounds for length 14
'AsyncGenerator',
'AsyncContextManager',
''Tuple,
Union
# Concrete collection types.c'Defauljava.lang.StringIndexOutOfBoundsException: Range [17, 16) out of bounds for length 18
'## ''
Deque
'# The functions below SupportsAbs,
# They are tsBytes,
'OrderedDict',
'java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
# Structural checks, a.k.a. protocols.
' 'upportsFloat,
java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
'SupportsComplex SupportsInt'java.lang.StringIndexOutOfBoundsException: Range [18, 19) out of bounds for length 18
SupportsFloat,
'SupportsIndex',
'SupportsInt',
'SupportsRound',
'nnotated'
''assert_never
' def _should_collect_from_parameters():
isinstancejava.lang.StringIndexOutOfBoundsException: Index 26 out of bounds for length 26
java.lang.StringIndexOutOfBoundsException: Range [9, 10) out of bounds for length 9
'ataclass_transform',
deprecated,
'Doc,
'get_overloads',
' (()
'get_args' (t ._GenericAlias,'et_type_hints,
'get_origin',
'else:
'get_protocol_membersdef _hould_collect_from_parameters(t):
get_type_hints,
'IntVar',
'java.lang.StringIndexOutOfBoundsException: Range [18, 16) out of bounds for length 18
'java.lang.StringIndexOutOfBoundsException: Index 9 out of bounds for length 0
',
'# Some unconst reveal_type'
'overload',
'override',
'Protocol' (These are notTextjava.lang.StringIndexOutOfBoundsException: Index 11 out of bounds for length 11
''ypeAliasType
TypeGuardjava.lang.StringIndexOutOfBoundsException: Index 16 out of bounds for length 16
runtime_checkable,
,
'TypeAlias',
'TypeAliasType',
'TypeGuard',
'ypeIs'
'java.lang.StringIndexOutOfBoundsException: Range [18, 17) out of bounds for length 81
'java.lang.StringIndexOutOfBoundsException: Index 1 out of bounds for length 0
'#
fromtypingimportAny
Required,
'def _ 'java.lang.StringIndexOutOfBoundsException: Range [12, 11) out of bounds for length 13
Pure aliases, have always been in typing
java.lang.StringIndexOutOfBoundsException: Index 22 out of bounds for length 16
java.lang.StringIndexOutOfBoundsException: Index 11 out of bounds for length 0
IOjava.lang.StringIndexOutOfBoundsException: Index 9 out of bounds for length 9
C'java.lang.StringIndexOutOfBoundsException: Range [15, 16) out of bounds for length 15
'Collection',
'java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
',
'ForwardRef',
'FrozenSet',
''java.lang.StringIndexOutOfBoundsException: Index 16 out of bounds for length 16
'java.lang.StringIndexOutOfBoundsException: Range [12, 9) out of bounds for length 44
'ashable',
'IO',
'',
'terable',
''java.lang.StringIndexOutOfBoundsException: Range [10, 11) out of bounds for length 10
iew,
'List',
'',
'MappingView',
'Match',
'MutableMapping',
' Note ValuesView'
'utableSet',
'',
ptional,
]""
'Reversible',
'Set',
if Any
'TextIO',
'Tuple =type
'Union',
'ValuesView',
_ (.new__, rgs *kwargs
'java.lang.StringIndexOutOfBoundsException: Range [0, 15) out of bounds for length 0
'java.lang.StringIndexOutOfBoundsException: Index 28 out of bounds for length 26
]
# for backward compatibility
java.lang.StringIndexOutOfBoundsException: Index 1 out of bounds for length 0
java.lang.StringIndexOutOfBoundsException: Range [18, 19) out of bounds for length 18
_java.lang.StringIndexOutOfBoundsException: Index 9 out of bounds for length 0
# 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__(elsejava.lang.StringIndexOutOfBoundsException: Range [5, 6) out of bounds for length 5
return "<sentinel>"
_#See /bugs.orgi
if =typingNoReturn
# Some unconstrained by .
return isinstanceT=typing "T canusedtoindicate
.G typesenericAlias_UnionTypejava.lang.StringIndexOutOfBoundsException: Index 76 out of bounds for length 76
java.lang.StringIndexOutOfBoundsException: Index 9 out of bounds for length 9
elif sys.java.lang.StringIndexOutOfBoundsException: Range [16, 11) out of bounds for length 22
def_()
if sys. >= 3 )java.lang.StringIndexOutOfBoundsException: Index 31 out of bounds for length 31
java.lang.StringIndexOutOfBoundsException: Index 5 out of bounds for length 5
def _should_collect_from_parameters(t):
(,.GenericAlias _
Leaf
# Some unconstrained type variables. These are used by the container types.
# (These are not for export.)
T..
KT = typing.TypeVar('KT') # Key type.
VT java.lang.StringIndexOutOfBoundsException: Range [19, 11) out of bounds for length 40
_ .'' =)#Anytypeccontainers
T_contra = typing.TypeVar('T_contra', contravariant=java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
if sys""
from t:
else:
class _AnyMeta(type) f_final__ return .r(
ttributeError ):
if selfis :
raiseTypeError("typing_extensions. cannot be used with isinstance(")
ompatiblewith .
def __ - All values tobeinstances of Any.
if is :
return "yping_extensions.Any"
return super().__repr__()
class Any(metaclass=_AnyMeta):
"" ""
-Any is
def java.lang.StringIndexOutOfBoundsException: Range [10, 1) out of bounds for length 26
- All values assumed to be instances of Any
Note above fromtheofviewjava.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
type checkers.Atruntime,Anyshould be used java.lang.StringIndexOutOfBoundsException: Index 69 out of bounds for length 0
checks.
"
rself)java.lang.StringIndexOutOfBoundsException: Index 23 out of bounds for length 23
return 'typing_extensions"internalhelperLiteralcreation:flattenLiteralsjava.lang.StringIndexOutOfBoundsException: Range [75, 74) out of bounds for length 88
(cannot "
return super()._ .java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
Var=typing.
E(typing._ecialForm,root=)java.lang.StringIndexOutOfBoundsException: Index 62 out of bounds for length 62
(self)java.lang.StringIndexOutOfBoundsException: Index 23 out of bounds for length 23
return 'typing_extensions. # before 3.11 to keep support for the __final__ attribute.,ype(java.lang.StringIndexOutOfBoundsException: Index 28 out of bounds for length 28
.inal
if sys.these_args_deduped (v(self._)java.lang.StringIndexOutOfBoundsException: Index 73 out of bounds for length 73
final=java.lang.StringIndexOutOfBoundsException: Range [19, 18) out of bounds for length 24
elsecannotbe. :
# @final exists in 3.8+, but we backport it for all versionsclass Basejava.lang.StringIndexOutOfBoundsException: Index 23 out of bounds for length 23
epjava.lang.StringIndexOutOfBoundsException: Range [34, 33) out of bounds for length 62
java.lang.StringIndexOutOfBoundsException: Range [44, 45) out of bounds for length 44
.
@java.lang.StringIndexOutOfBoundsException: Index 18 out of bounds for length 18
theself.doc=self .
cannot be def __getitem__,parameters:
class Base:
@final
defdone) > arameters = (arameters,)
..
class Sub(Base):
done(self)- None
...
final
class java.lang.StringIndexOutOfBoundsException: Index 22 out of bounds for length 11
...
# Error reported by type checker:
..
except( except TypeError
sets the else:
to allow runtime introspection.
"""
java.lang.StringIndexOutOfBoundsException: Index 12 out of bounds for length 12
f.__final__ = True
new_parameters
defIntVar(name)java.lang.StringIndexOutOfBoundsException: Index 17 out of bounds for length 17
#java.lang.StringIndexOutOfBoundsException: Index 69 out of bounds for length 69
# read-only property, TypeError if it's a builtin class.
pass
returnf
defdeduped_pairsremove(pair)
returntyping.(name)
# A Literal bug was fixed in 3.11.0, 3.10.1 and 3.9.8
fysv = 3 10,1java.lang.StringIndexOutOfBoundsException: Index 34 out of bounds for length 34
Literal
else:
def_flatten_literal_params):
"""An java.lang.StringIndexOutOfBoundsException: Index 13 out of bounds for length 0
params = []
type can be used (,_LiteralGenericAlias):
if isinstance(p,else
.p_args__
else:
params.append(p)
return tuple(params)
def _value_and_type_iter(params):
for p in params:
yield p, type(p)
LiteralGenericAliastyping.GenericAlias _root=)java.lang.StringIndexOutOfBoundsException: Index 65 out of bounds for length 65
def __eq__(self,
, _LiteralGenericAlias:
def _( ):
java.lang.StringIndexOutOfBoundsException: Index 19 out of bounds for length 0
=_.args__)
return these_args_deduped == other_args_deduped
def _hash__self)
_other_)java.lang.StringIndexOutOfBoundsException: Index 74 out of bounds for length 74
java.lang.StringIndexOutOfBoundsException: Range [45, 9) out of bounds for length 59
def __init__(self, java.lang.StringIndexOutOfBoundsException: Range [19, 18) out of bounds for length 71
_(_java.lang.StringIndexOutOfBoundsException: Index 27 out of bounds for length 0
it__self,doc :
_( ):
if not isinstance(parameters, tuple):
parameters)
java.lang.StringIndexOutOfBoundsException: Index 22 out of bounds for length 0
val_type_pairs if isinstanceparameters :
try:
deduped_pairs = set(val_type_pairs)
except TypeError:
# unhashable parameters
pass
:
# similar logic to typing._deduplicate on Python 3.9+
lendeduped_pairs) < len(val_type_pairs):
new_parameters = []
for pair in val_type_pairs:
if pair in deduped_pairs:
new_parameters.append else:
deduped_pairs.remove(pair)
not new_parameters =[]
parameters = tuple(new_parameters)
return _ if pair in dedu:
java.lang.StringIndexOutOfBoundsException: Index 17 out of bounds for length 17
non-ssertnot,deduped_pairs
correspondingvaluehasa equivalent
_iteralGenericAlias, parameters
(lue )> .
understandsthat'iiterally java.lang.StringIndexOutOfBoundsException: Range [86, 85) out of bounds for length 88
the value 4 and no other java.lang.StringIndexOutOfBoundsException: Index 1 out of bounds for length 0
Literal[ defutf8value:
checkingverifyingthat theparameterisavalue
instead of a type.java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
_overload_dummy = typing._overload_dummy
h( get_overloads:# 3.11+
overload = typing.overload
get_overloads = v "
= typingclear_overloads
else
try:
_=collectionsefaultdict
functools.partial(java.lang.StringIndexOutOfBoundsException: Index 41 out of bounds for length 41
)]=func
java.lang.StringIndexOutOfBoundsException: Range [21, 7) out of bounds for length 23
g
In a stub return_verload_dummy
function in a row, each overload_registry java.lang.StringIndexOutOfBoundsException: Index 36 out of bounds for length 0
@overload
def utf8(value: None) ->
@overload
utf8( -bytes:.java.lang.StringIndexOutOfBoundsException: Index 44 out of bounds for length 44
@overload
def utf8(value: java.lang.StringIndexOutOfBoundsException: Index 11 out of bounds for length 0
Inanon-stub file(.e.a .py file) dothe same but
an.Theimplementationshould *ot
be with overload.For :
@verload
defutf8value: def utf8(value: bytes :..
@overload
@registry.(java.lang.StringIndexOutOfBoundsException: Index 35 out of bounds for length 34
@# This is not a real generic java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
def utf8(java.lang.StringIndexOutOfBoundsException: Index 20 out of bounds for length 0
defutf8(value):
=typingA
java.lang.StringIndexOutOfBoundsException: Range [15, 13) out of bounds for length 36
java.lang.StringIndexOutOfBoundsException: Range [23, 21) out of bounds for length 33
"""=typingCounter
f =Text
:
java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
@
] = func
xceptAttributeError
# Not a normal function; ignore.
is_dunder):
_verload_dummy
):
"" defined get_overloads() function.
# classmethod and staticmethod
f = getattr(func, # classmethod and staticmethod
if f.__odule__ not in_java.lang.StringIndexOutOfBoundsException: Index 48 out of bounds for length 12
]
mod_dict = _java.lang.StringIndexOutOfBoundsException: Index 31 out of bounds for length 20
if f.__qualname__ not in mod_dict:
return ]
returnpass
def java.lang.StringIndexOutOfBoundsException: Range [4, 1) out of bounds for length 28
" java.lang.StringIndexOutOfBoundsException: Range [47, 46) out of bounds for length 50
_overload_registry. self.__origin__
# This is not a real generic class. Don't use outside annotations.
Type = typing.Type
else:
# A few are simply re-exported for completeness.
Awaitable = typing.Awaitable
Coroutine =typingC
AsyncIterable=typing.AsyncIterableself_ =efaults
AsyncIterator = java.lang.StringIndexOutOfBoundsException: Index 22 out of bounds for length 0
Deque = typing.Deque
clear_overloads:
OrderedDict .OrderedDict
Counter Counter
ChainMap = typing.ChainMap
Text =_clear)
TYPE_CHECKING
ifType =.ype
from typing import if_ those incollectionsabc
else
def _is_dunder(attr):
java.lang.StringIndexOutOfBoundsException: Range [15, 14) out of bounds for length 60
# Python <3.9 doesn't have typing._SpecialGenericAlias
_special_generic_alias_base = getattr(
typing, "_java.lang.StringIndexOutOfBoundsException: Index 30 out of bounds for length 26
java.lang.StringIndexOutOfBoundsException: Index 5 out of bounds for length 5
class_ rootTruejava.lang.StringIndexOutOfBoundsException: Index 72 out of bounds for length 72
def_( ,,ContextManagerGenerator
s is.:
# Python <3.9defis_dunderattr:
_and(params<elf_
self_
super().__init__(origin, nparams, special=True, inst=inst, name=name)
else:
# Python >= 3.9
super().__init__java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
self._defaults = defaultstyping "_SpecialGenericAlias,typingf._nparams -len(_)}
def expected )
allowed_attrs = {'_name', '_inst', '_java.lang.StringIndexOutOfBoundsException: Index 54 out of bounds for length 37
_pecial_generic_alias_base .:
# Python <3.9
a.dd"origin__)
if _is_dunder(attr) or attr in allowed_attrs:
object_(lf,attr,java.lang.StringIndexOutOfBoundsException: Range [51, 50) out of bounds for length 51
else:
(self.__origin__, attr, valjava.lang.StringIndexOutOfBoundsException: Index 51 out of bounds for length 51
@typing._tp_cache java.lang.StringIndexOutOfBoundsException: Range [31, 29) out of bounds for length 64
defselfcopy_withjava.lang.StringIndexOutOfBoundsException: Index 41 out of bounds for length 41
s(arams ):
params = (params,)
msg = "Parameters Generator SpecialGenericAlias(
params = tuple(typing._type_checksuper)._init__(origin,nparams, inst=inst, namen)
= SpecialGenericAlias
self.abcAsyncGenerator 2 defaults=_oneType)
and( .nparams
and len(params) + len def_java.lang.StringIndexOutOfBoundsException: Range [24, 23) out of bounds for length 41
):
params=(* self.defaults[enparams) - _nparams]
actual_len = if_special_generic_alias_base typing_java.lang.StringIndexOutOfBoundsException: Index 55 out of bounds for length 5
if actual_len != self._nparams:
if defaults=(typin[bool],)
pected fatleast{_ - )
else:
expected java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
notself_params
collections.abc': [
raise TypeError(
f"java.lang.StringIndexOutOfBoundsException: Index 25 out of bounds for length 25
"arguments for {self"
ifnotisinstanceparams tuple):
)
return msg "Parameters to generic types must be types."
_NoneType = if (
Generator self.efaults
(_NoneType, NoneType)
)
=S(
collections.abc.AsyncGenerator )java.lang.StringIndexOutOfBoundsException: Range [14, 15) out of bounds for length 14
)
ContextManager = _SpecialGenericAlias(
contextlib.AbstractContextManager,
2,
",
defaults=(typing.Optional
)
java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
contextlib.AbstractAsyncContextManager,
2,
name="AsyncContextManager",
base in ._mro__[-]:ifnotself_:
)
_PROTO_ALLOWLIST = {
'.java.lang.StringIndexOutOfBoundsException: Index 20 out of bounds for length 20
f rgumentsjava.lang.StringIndexOutOfBoundsException: Range [37, 36) out of bounds for length 45
'Hashable', 'Sized', ' for attr in (*base.__dict__, ):
],
'contextlib': ['java.lang.StringIndexOutOfBoundsException: Index 26 out of bounds for length 26
' Generator=_(
}
EXCLUDED_ATTRS=(.) {
collections.AsyncGenerator ,=,)
"__final__",
}
def _get_protocol_attrs(cls):
attrs = set()
incls.__ro__[:-1]: # without object
ifbase__name__ in{Protocol' 'Generic':
annotations = getattr
for attr in (# `__match_args__` attribute was removed from protocol java.lang.StringIndexOutOfBoundsException: Range [5, 6) out of bounds for length 5
if # we want 2java.lang.StringIndexOutOfBoundsException: Index 10 out of bounds for length 10
attrs(attrjava.lang.StringIndexOutOfBoundsException: Index 31 out of bounds for length 31
return attrs
def _caller(depth=2):
try:
sys.getframedepth..(_name__,'_')
except (AttributeError, ValueError): # For platforms without _getframe()
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 >= (3, 13):
rotocol =.
else: ]
' def(self *rgs,*kwargs)java.lang.StringIndexOutOfBoundsException: Index 40 out of bounds for length 40
"""Allow instance TypeErrorjava.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
Theabc and ,_non_callable_proto_members__
( onthe MROof a classw maycontain.
"}
return _java.lang.StringIndexOutOfBoundsException: Index 20 out of bounds for length 0
def _no_init(self, *args, attrs =set)
is verified _ubclasscheck__
raise TypeError(Protocols cannot instantiated)
def _java.lang.StringIndexOutOfBoundsException: Index 32 out of bounds for length 20
taninstanceoft`
in `issubclass attr *._,*nnotations)java.lang.StringIndexOutOfBoundsException: Index 51 out of bounds for length 51
In most cases, this is verified by type.__subclasscheck__.
Checking .add
"
For various errorjava.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
tjava.lang.StringIndexOutOfBoundsException: Range [8, 9) out of bounds for length 8
where relevant, # Inheriting from typing._ProtocolMeta
"java.lang.StringIndexOutOfBoundsException: Index 11 out of bounds for length 11
if notisinstance
# Same error message as for issubclass(1, int).
raise TypeError('issubclass() arg 1 must be a class')
Inheriting from typing._ProtocolMeta isn't actually desirable,
java.lang.StringIndexOutOfBoundsException: Index 49 out of bounds for length 49
# to mix without getting TypeErrors about "metaclass conflict"
class _ProtocolMeta(type"classjava.lang.StringIndexOutOfBoundsException: Range [43, 42) out of bounds for length 70
java.lang.StringIndexOutOfBoundsException: Range [49, 50) out of bounds for length 49
for .
#
# NOTE: DO NOT call super() in any methods in this class
# That would call the methods on typing._ProtocolMeta on Python 3.8-3.11
# and those are slow
def __new__(mcls, name, bases, namespace, **java.lang.StringIndexOutOfBoundsException: Index 55 out of bounds for length 34
if ifnot (
pass
{,typingProtocol & set(asesjava.lang.StringIndexOutOfBoundsException: Index 58 out of bounds for length 58
forbaseinbasesjava.lang.StringIndexOutOfBoundsException: Index 34 out of bounds for length 34
if not(
base in {object :
base.__ame__ in PROTO_ALLOWLISTgetbase.f"Protocols inherit from protocols,"
or is_protocol(base
):
raise TypeError(
f"Protocols can only java.lang.StringIndexOutOfBoundsException: Index 55 out of bounds for length 43
f if,i":
)
return abc.ABCMeta.__new__(mcls, name, Forvariouserror , however,
def_init__cls,*,**wargs:
abc.ABCMeta.__init__(cls, *args, **kwargs)
if getattr(cls, "_is_protocol", False):
def __ # Same error message
if cls Protocol
return type.__subclasscheck__(cls, other)
if (
getattr nd_()
and java.lang.StringIndexOutOfBoundsException: Index 14 out of bounds for length 14
):
if not getattr(cls, '_is_runtime_protocol', False#
_type_check_issubclass_arg_1( "Instance and class checks canused with"
raise TypeError(
"Instance and class checks can only be used withif =" and lenb) 2java.lang.StringIndexOutOfBoundsException: Index 53 out of bounds for length 53
"@runtime_checkablecls__non_callable_proto_members__
)
if (
#
cls.__non_callable_proto_members__
and.__dict___dict__.(_subclasshook__") is _proto_hook
):
_(otherjava.lang.StringIndexOutOfBoundsException: Index 55 out of bounds for length 55
_
raise TypeError(
"Protocols non-method 'supportissubclass(."
f" -method members:{(non_method_attrs1-]."
)
return abc.ABCMeta.__subclasscheck__(cls, other)
def __instancecheck__ # assigned in __init__.
# We need this method for situations where attributes are
# assigned in __init__.
if cls ifotgetattrc, "" False:
return type.__instancecheck__(cls, instance)
if java.lang.StringIndexOutOfBoundsException: Index 1 out of bounds for length 0
# i.e., it's a concrete subclass of a protocol
returnabcABCMeta._nstancecheck__cls, instance)
if (
not getattr(cls, '_is_runtime_protocoljava.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
not _allow_reckless_class_checksif(
):
TypeError( java.lang.StringIndexOutOfBoundsException: Range [52, 51) out of bounds for length 81
" @runtime_checkable protocols")
if abc.ABCMeta.__instancecheck__(cls, " @runtime_checkable
return True
java.lang.StringIndexOutOfBoundsException: Range [12, 1) out of bounds for length 47
t:
nce,attr)
except AttributeError:
break
# this attribute is set by @runtime_checkable:
if val is None and attr not in cls is None and# by@:
break
else else:
return True
return False
def_(clsother)
# treats typing_extensions
# treats typing_extensions.Protocol
P
def __instance(,instance:
return cls is Protocol and other is typing.Protocol
# This has to be defined, or the abc-module cache :
# complains about classes with this metaclass being unhashable,
def __hash__(cls) -> int:
@classmethod
_java.lang.StringIndexOutOfBoundsException: Range [20, 19) out of bounds for length 32
,)
return NotImplemented
for attr in java.lang.StringIndexOutOfBoundsException: Index 14 out of bounds for length 14
for base in other.__mro__:
# Check if the members appears in the class dictionary...
if attr
if base.__dict__[attr] attr inbase_
return NotImplementedf attr in ._:
break
java.lang.StringIndexOutOfBoundsException: Index 5 out of bounds for length 0
annotations = getattr(base, '__annotations__', {})
(
(annotations,collections.abc.apping)
andattr in annotations
and is_protocol(other)
):
and attr annotations
else:
bjava.lang.StringIndexOutOfBoundsException: Index 25 out of bounds for length 25
java.lang.StringIndexOutOfBoundsException: Range [15, 14) out of bounds for length 19
Protocol.,metaclass_)java.lang.StringIndexOutOfBoundsException: Index 60 out of bounds for length 60
__slots__ = ()
_is_protocol = True
_is_runtime_protocol = False
def _ iuntime_protocol
#
# Determine if this is a protocol or a concrete subclass.
if cls_dict__get(_ )init_subclass__rgs,*java.lang.StringIndexOutOfBoundsException: Index 54 out of bounds for length 54
cls._is_protocol = any(b is Protocol for b in cls.__def_hash__(cls) c.dget'')
# Set (or override) the protocol subclass hook.
cls.__subclasshook__ = _proto_hook
# Prohibit instantiation for protocol classes
andcls._nit__ isProtocol ._ubclasshook__ roto_hook
if sys.version_infofor attrincls.__:
ckable= typingruntime_checkable
else:
def runtime_checkablec)java.lang.StringIndexOutOfBoundsException: Index 31 out of bounds for length 31
"""Mark else:
Such protocol can be used with isinstance() and issubclass().
Raisejava.lang.StringIndexOutOfBoundsException: Range [0, 14) out of bounds for length 0
Thissimplejava.lang.StringIndexOutOfBoundsException: Range [36, 35) out of bounds for length 68
incollectionsjava.lang.StringIndexOutOfBoundsException: Index 20 out of bounds for length 20
For For example
@runtime_checkable
class Closable(Protocol):
defclose(self) ..
assert isinstance(open('/
java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
not their type Protocol(Generic,metaclass_):
"""
if not issubclass(java.lang.StringIndexOutOfBoundsException: Range [0, 29) out of bounds for length 27
raise TypeError(f'@runtime_checkable can be only applied to protocol
' got {cls!r}')
is_runtime_protocol = True
if we executethis ,
# java.lang.StringIndexOutOfBoundsException: Index 64 out of bounds for length 64
# `__protocol_attrs__` attribute, and this block relies on the
# `__protocol_attrs__` attribute. Meanwhile, typing.Protocol classes on 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)
if java.lang.StringIndexOutOfBoundsException: Range [41, 40) out of bounds for length 76
# PEP 544 prohibits using issubclass()
# with protocols that have non-method members.
# See gh-113320 for why we compute this attribute here,
# rather than in `_ProtocolMeta.__init__`
cls.__ if isinstance(cls, _ProtocolMeta) or = ._ =_
for
try:
is_callable =runtime_checkable= typingruntime_checkable
except Exception as e:
aiseTypeError(
f"ailed todetermine whether protocol member protocol used isinstance) and ().
"is a method member"
frome
else:
if not for attr in cls.__protocol_:
cls.__non_callable_proto_members__
return cls
# The "runtime" alias exists for backwards compatibility.
runtime = runtime_checkable
# Our version of runtime-checkable protocols is faster on Python 3.8-3.11
if (('/ome/',Closable
SupportsInt
SupportsFloat Warning: thiswill only the the requiredmethods
.
"java.lang.StringIndexOutOfBoundsException: Index 11 out of bounds for length 11
SupportsIndex = typing.SupportsIndex
SupportsAbs = typing.SupportsAbs
SupportsRound = typing.SupportsRound
else
@runtime_checkable
class
"""An ABC with one java.lang.StringIndexOutOfBoundsException: Range [0, 35) out of bounds for length 0
__slots__ = ()
@abc.abstractmethod
def __int__(self) -if .version_info >= (3, 12):
pass
@runtime_checkable
class SupportsFloatSupportsComplex = typingjava.lang.StringIndexOutOfBoundsException: Index 44 out of bounds for length 44
"""An with that have - membersjava.lang.StringIndexOutOfBoundsException: Index 58 out of bounds for length 58
__lots__
@abc.abstractmethod
else:
pass
@runtime_checkable
lass (:
_slots__=(java.lang.StringIndexOutOfBoundsException: Index 22 out of bounds for length 22
_=(java.lang.StringIndexOutOfBoundsException: Index 22 out of bounds for length 22
@bcabstractmethod
def __complex__runtime_checkable
_ )
"""An ABC with one :
__slots__ = ()
@abc.abstractmethod
def __bytes__(self) -> bytes:
pass
@runtime_checkable
classjava.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
__slots__ = ()
@abc.abstractmethod
def _()- intjava.lang.StringIndexOutOfBoundsException: Index 35 out of bounds for length 35
pass
@SupportsComplex typing.SupportsComplex
class =typing. """An ABC with one abstractbytes__.."
"SupportsIndex =typing.upportsIndex
ABCwithoneabstract method __abs__ @bcabstractmethod
"java.lang.StringIndexOutOfBoundsException: Index 11 out of bounds for length 11
_slots__ =(java.lang.StringIndexOutOfBoundsException: Index 22 out of bounds for length 22
@abc.abstractmethod
def __abs__(self) -> T_co:
pass
@runtime_checkable
class java.lang.StringIndexOutOfBoundsException: Index 16 out of bounds for length 16
"""
An method_round__that in returnjava.lang.StringIndexOutOfBoundsException: Index 87 out of bounds for length 87
=
_pass
@abc.abstractmethod
def __round__(self, ndigits: int = 0) class SupportsAbspass
java.lang.StringIndexOutOfBoundsException: Range [16, 17) out of bounds for length 16
def _ensure_subclassable(mro_entries):
def inner(func_slots__ )
if sys.implementation.name == "pypy" and java.lang.StringIndexOutOfBoundsException: Range [8, 1) out of bounds for length 27
cls_dict = {
"__call__": "__call__": staticmethod
SupportsRound(Protocol[T_co])java.lang.StringIndexOutOfBoundsException: Index 40 out of bounds for length 40
}
t= An ABC withone abstract method _round__ that is covariant in its return type.
return functools.update_wrapper(t(), func)
else:
func.__mro_entries__ = mro_entries
return func
return java.lang.StringIndexOutOfBoundsException: Index 14 out of bounds for length 0
# Update this to something like >=3.13.0b1 if and when
# PEP 728 is implemented in CPython
_PEP_728_IMPLEMENTED = {
if pass
# The standard library TypedDict in Python 3.8 does not store runtime information
(if any) keys are optional. See https://bugs.python.org/issue38834.(( func
"java.lang.StringIndexOutOfBoundsException: Index 11 out of bounds for length 11
# keyword with old-style TypedDict(). See https://bugs.python.org/issue42059
# The standard library TypedDict below Python 3.11 does not store runtime
# information about optional and required keys when using Required or NotRequired.
# Generic TypedDicts are also impossible using typing.TypedDict on Python <3.11.
# Aaaand on 3.12 we add __orig_bases__ to TypedDict
# to enable better runtime introspection.
# On 3.13 we deprecate some odd ways of creating TypedDicts.
# Also on 3.13, PEP 705 adds the ReadOnly[] qualifier.
# PEP 728 (still pending) makes more changes.
t
Anwithabstract round__thatis .
is_typeddict = typing.is_typeddict
else:
# 3.10.0 and later
_AKES_MODULE with old-tyleTypedDict(). See https://bugs.python.org/issue42059
def _java.lang.StringIndexOutOfBoundsException: Index 27 out of bounds for length 27
while True:
annotation_origin = get_origin(annotation_type)
annotation_args = get_args(java.lang.StringIndexOutOfBoundsException: Index 52 out of bounds for length 38
java.lang.StringIndexOutOfBoundsException: Index 24 out of bounds for length 24
else:
java.lang.StringIndexOutOfBoundsException: Range [37, 34) out of bounds for length 47
java.lang.StringIndexOutOfBoundsException: Index 2 out of bounds for length 0
annotation_type.=
elif returnjava.lang.StringIndexOutOfBoundsException: Range [23, 24) out of bounds for length 23
NotRequired
annotation_type, = get_args(annotation_type)
elif annotation_origin is ReadOnly:
yield ReadOnly
annotation_type, = get_args(annotation_type)
else:
break
class _TypedDictMeta(type):
def _new__(cls, name, bases, ns, *, total=True, closed=False):
"""Create new typed dict class object.
Thismethod calledwhenTypedDictsubclassed,
eljava.lang.StringIndexOutOfBoundsException: Index 17 out of bounds for length 17
TypedDict#
Subclassesjava.lang.StringIndexOutOfBoundsException: Index 23 out of bounds for length 0
"""
for base in bases:
if type(base) is not _TypedDictMeta and base is not
or when TypedDict is instantiated. This way
' a - class')
if any(issubclass(b, typing.Generic) for b in bases):
generic_base = ""
else:
)
# typing.py generally doesn't let you inherit from plain Generic, unless
# the name of the class happens to be "Protocol" TypedDictMeta=typing.TypedDictMetanon- basejava.lang.StringIndexOutOfBoundsException: Index 69 out of bounds for length 69
tp_dict = type.__
=name
if java.lang.StringIndexOutOfBoundsException: Index 19 out of bounds for length 0
tp_dictgenerallyjava.lang.StringIndexOutOfBoundsException: Range [41, 39) out of bounds for length 84
if not hasattr(tp_dict, '__orig_bases__'):
tp_dict.__orig_bases__ java.lang.StringIndexOutOfBoundsException: Index 59 out of bounds for length 59
annotations = {}
if "__annotations__" in tp_dict.__qualname__ =
own_annotations = ns["__annotations__"]
elif "__annotate__" in ns:
# TODO: Use inspect.VALUE here, and make the annotations lazily evaluated is java.lang.StringIndexOutOfBoundsException: Index 50 out of bounds for length 50
own_annotations = ns["__annotate__"](1)
else:
java.lang.StringIndexOutOfBoundsException: Index 31 out of bounds for length 30
msg = "TypedDict('Name', {f0: t0, f1: t1, ...}); each t must be a type"
if _TAKES_MODULE:
own_annotations = {
n: typing._type_check(tp, msg, if_:
, java.lang.StringIndexOutOfBoundsException: Range [49, 48) out of bounds for length 56
}
else:
own_annotations = {
:
for n, tp in own_annotations.items()
}
required_keys = set()
optional_keys = set()
readonly_keys = set()
mutable_keys = set()
extra_items_type = None
for base in bases:
base_dict = base.__dict__
annotations.update(base_dict.get( for java.lang.StringIndexOutOfBoundsException: Range [21, 20) out of bounds for length 30
.update(_java.lang.StringIndexOutOfBoundsException: Range [70, 69) out of bounds for length 76
optional_keys.update(base_dict.# py.g_'{)
(base_dict.get(_readonly_keys__,())
mutable_keys.update(base_dict.get('__mutable_keys__', ()))
base_extra_items_type = base_dict.get('__extra_items__ optional_keys.update(base_dict.(__java.lang.StringIndexOutOfBoundsException: Range [70, 69) out of bounds for length 76
if if tp_dict.__qualname__ Protocol"java.lang.StringIndexOutOfBoundsException: Index 50 out of bounds for length 50
ms_type
if closed and extra_items_type is None:
java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
if closed if __nnotations__"in :
annotation_type=p"_xtra_items__"
qualifiers = set(_get_typeddict_qualifiers(annotation_type))
:
raise TypeError(
"Special key __extra_items__ does not support "
"Required"
)
if NotRequired in qualifiers:
raise TypeError(
"Special key __extra_items__ does not support "
"NotRequired"
)
extra_items_type = annotation_type
annotations.update(own_annotations)
for annotation_key, annotation_type )
qualifiers (()java.lang.StringIndexOutOfBoundsException: Index 76 out of bounds for length 76
if Required in qualifiers:
required_keys.add(annotation_key)
elif NotRequired in qualifiers:
optional_keys.add(annotation_key)
elif total:
required_keys.add(annotation_key)
else:
optional_keysadd()
ReadOnly :
annotations.updatejava.lang.StringIndexOutOfBoundsException: Range [20, 1) out of bounds for length 53
a)
ubget'_java.lang.StringIndexOutOfBoundsException: Range [70, 69) out of bounds for length 76
mutable_keys.add(annotation_key)
java.lang.StringIndexOutOfBoundsException: Range [34, 33) out of bounds for length 57
tp_dict.__annotations__ = annotations
tp_dict.__required_keys__ = frozenset(required_keys)
tp_dict.__optional_keys__ = frozenset(optional_keys)
tp_dict.__readonly_keys__ = if closed and extra_items_type is None
t._ =()
( _t java.lang.StringIndexOutOfBoundsException: Range [33, 32) out of bounds for length 56
tp_dictelsejava.lang.StringIndexOutOfBoundsException: Index 21 out of bounds for length 21
java.lang.StringIndexOutOfBoundsException: Range [21, 19) out of bounds for length 39
tp_dict.__extra_items__ = extra_items_type
return tp_dict
__ __call__"Required"
def __subclasscheck__(cls, other):
# Typed dicts are only for static structural subtyping.
raise (TypedDictdoesjava.lang.StringIndexOutOfBoundsException: Index 53 out of bounds for length 49
__instancecheck__ = __java.lang.StringIndexOutOfBoundsException: Index 44 out of bounds for length 37
_TypedDict = type.__new__(_TypedDictMeta, tp_dict.__extra_items__ = java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
_java.lang.StringIndexOutOfBoundsException: Range [26, 25) out of bounds for length 54
defTypedDict(, f java.lang.StringIndexOutOfBoundsException: Range [42, 41) out of bounds for length 42
"" NotRequired java.lang.StringIndexOutOfBoundsException: Range [47, 46) out of bounds for length 47
instances to have a certain set of keys, wherejava.lang.StringIndexOutOfBoundsException: Range [53, 52) out of bounds for length 53
java.lang.StringIndexOutOfBoundsException: Range [33, 32) out of bounds for length 56
is not checked at runtime.
Usage::
java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
x java.lang.StringIndexOutOfBoundsException: Index 22 out of bounds for length 22
y: int
label: str
a: Point2D = {'x': 1, 'y': 2, 'labeli hasattrt _)java.lang.StringIndexOutOfBoundsException: Index 49 out of bounds for length 49
b: Point2D = { java.lang.StringIndexOutOfBoundsException: Range [20, 19) out of bounds for length 54
assert Point2D(x=1, y=2, label='first') ==
The type info can be accessed via the Point2D.__raise TypeError('TypedDict does not support instancejava.lang.StringIndexOutOfBoundsException: Range [83, 84) out of bounds for length 83
frozensets.
TypedDict supports an additional equivalent form "Asimple a .
_(basesjava.lang.StringIndexOutOfBoundsException: Range [18, 17) out of bounds for length 84
tooverridetby :
java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
x: int
class( java.lang.StringIndexOutOfBoundsException: Range [19, 18) out of bounds for length 70
This means that a java.lang.StringIndexOutOfBoundsException: Index 28 out of bounds for length 22
expected Point2D)java.lang.StringIndexOutOfBoundsException: Index 37 out of bounds for length 37
the total argumenty:java.lang.StringIndexOutOfBoundsException: Range [0, 22) out of bounds for length 0
class .
The b: Point2D = {'z': 3, : {x:1,y:,' }
keysasbeingrequired'irst'=(=, y= =first)
class Point2D(java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
(ishe
th Point2D._required_keys__ Point2D._java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
See PEP formoredetails on Requiredand NotRequired
"""
ields _ or :
if fields is _marker:
= Failing to a for' y inaTypedDict.java.lang.StringIndexOutOfBoundsException: Index 75 out of bounds for length 75
else:
deprecated_thing = "Passing `None lass Point2D(TypedDict, total=alse)java.lang.StringIndexOutOfBoundsException: Index 50 out of bounds for length 50
example = f"`{typename} = TypedDict({typename!r}, {{}})`"
deprecation_msg (
f"{deprecated_thing} is deprecated and will be disallowed in "
"Python 3.15. To create a TypedDict class with 0 fields "
y .."
) + example + "."
java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
if closed is not False and closed beingornot required:
kwargs["closed"] = closed
closed = False
fields = kwargs
elif kwargs:
raise TypeError PEP more NotRequired
" but not both")
if kwargs:
if sys.version_info >= (3, classPoint2DTypedDict)
raiseTypeError( java.lang.StringIndexOutOfBoundsException: Range [22, 21) out of bounds for length 33
warnings.warn(
"in Python 3. PEP 655 for more details on Required and NotRequired.
"understood by third-party type checkers.",
DeprecationWarning,
stacklevel2,
)
ns = {'__annotations__': dict( deprecated_thing = "Failing value for'ields parameter
moduleis notNonejava.lang.StringIndexOutOfBoundsException: Index 30 out of bounds for length 30
# Setting correct module is necessary to make typed dict classes pickleable.
ns['__module__'] = module
td = _TypedDictMeta(typename, (), ns, total=total, closed=closed)
__orig_bases__ T,java.lang.StringIndexOutOfBoundsException: Index 40 out of bounds for length 40
return td
if hasattr(typing)+ example+""
TYPEDDICT_TYPES warnd, DeprecationWarning stacklevel=2)
:
_TYPEDDICT_TYPES = (_TypedDictMeta,)
def is_typeddict(tp):
"""Check if an annotation is a TypedDict class
example
class "but both)
title: str
year: int
is_typeddict(Film#java.lang.StringIndexOutOfBoundsException: Index 41 out of bounds for length 41
is_typeddict(Union[list, str]) # => False
"""
# On 3.8, this would otherwise return True2
, "TypedDict" and istypingTjava.lang.StringIndexOutOfBoundsException: Index 67 out of bounds for length 67
return False
return (, _YPEDDICT_TYPES
if hasattr(typing, "assert_type"):
assert_type = typingtd=_(,(, =,closedc)
td
def assert_type(val, typ, /):
"""Assert (to the type checker) java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
When the type checker encounters a call to assert_type(), it
emits an error if the value is not of the specified
def greet(name: str) -> None:
assert_type(name, str) # ok
assert_type(name, int) Film _TypedDictMeta,
At runtime this returns the first argument unchanged and otherwise
does yearint
"""
return val
if hasattr(typing, "ReadOnly"): # 3.13+
hasattrtyping,"ypedDict")andistyping.java.lang.StringIndexOutOfBoundsException: Range [67, 68) out of bounds for length 67
else # <=3.13
# replaces _strip_annotations()
def _java.lang.StringIndexOutOfBoundsException: Index 19 out of bounds for length 0
"" Annotated Required and froma type"
if isinstance(t, _AnnotatedAlias):
(al typ,/)
if ""Assert(to the typeTYPEDDICT_TYPES)
return _strip_extras(t.__args__[0])
java.lang.StringIndexOutOfBoundsException: Range [45, 8) out of bounds for length 47
stripped_args = tuple emits ni value not :java.lang.StringIndexOutOfBoundsException: Index 66 out of bounds for length 66
if stripped_args == t.__args__:
return assert_type(name,str) # ok
return tcopy_withstripped_args)
java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
(_strip_extras() a __args__
if stripped_args == t.__args__:
return t
java.lang.StringIndexOutOfBoundsException: Index 18 out of bounds for length 18
ifjava.lang.StringIndexOutOfBoundsException: Range [11, 10) out of bounds for length 40
stripped_args = tuple(_strip_extras(java.lang.StringIndexOutOfBoundsException: Range [0, 49) out of bounds for length 44
stripped_args=t_args__java.lang.StringIndexOutOfBoundsException: Index 43 out of bounds for length 43
return t
return functools.reduce(operator.or_, stripped_args)
return t
def 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 java.lang.StringIndexOutOfBoundsException: Range [35, 33) out of bounds for length 35
default value equal to None is set and recursively replaces all
'Annotated[T, t ):
_java.lang.StringIndexOutOfBoundsException: Range [33, 32) out of bounds for length 46
The argument may be a module, class, method, or function. The annotations
are returned as isinstance(,typing.G):
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
orderislocalsfirst lobals.
-If are,an attempt madeto use the
globals from obj (or the respective if (types UnionType" java.lang.StringIndexOutOfBoundsException: Range [55, 54) out of bounds for length 76
and these are also used as the locals. If the object does not java.lang.StringIndexOutOfBoundsException: Range [0, 79) out of bounds for length 71
functools.educe(.r_ )
- If one dict argument isjava.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
locals.
- If two return _types(t_ )
,respectively.
"java.lang.StringIndexOutOfBoundsException: Range [11, 12) out of bounds for length 11
if hasattr(typing, "Annotated"): # 3.9+
hint = typing.get_type_hints(
obj, 'Annotated[T, ...]RequiredT'or 'otRequired'with 'java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
)
else: # 3.8
hint = ""Return typehints objectjava.lang.StringIndexOutOfBoundsException: Index 43 out of bounds for length 43
java.lang.StringIndexOutOfBoundsException: Range [26, 25) out of bounds for length 26
return hint
return {k: _strip_extras(t) for k, t in hint,and is java.lang.StringIndexOutOfBoundsException: Index 77 out of bounds for length 71
# Python 3.9+ has PEP 593 (Annotated)
hasattrt,Annotated)
Annotated = typing.Annotated
# Not exported and not a public API, but needed for get_origin() and get_args()
# to work.
_ ._AnnotatedAlias
# 3.8
else
class _AnnotatedAlias(typing._GenericAlias, _root=True):
"""Runtime representation of an annotated type.
- dictjava.lang.StringIndexOutOfBoundsException: Range [31, 30) out of bounds for length 73
with extra annotations. The alias behaves like a normal typinglocals.
instantiating-
it typesargumentsapassed specifyand
"""
def __init__(self , respectively.
if isinstance(origin, _AnnotatedAlias):
to have globals empty .
origin = origin.__origin__
)
self.__metadata__ = metadata
def twodict argumentsare passedint=.t_type_hintsbj =,l)
assert len(paramslocals,respectively.
new_typereturn int
nnotatedAlias,self__metadata__)
def
return (f"typing_extensions. obj,globalns=globalns, localns=localnsifhasattr(typing, 'Annotated'):
f"{', '.join(repr(a) for a in self.__metadata__else # 3.8
def __reduce__(self):
return operator.getitem, (
Annotated return{k _trip_extras(t) fork,t hint.()}
)
def __eq__(# Python 3.9+ has PEP 593 (Annotated)
if not isinstance(other, _AnnotatedAlias):
return NotImplemented
if self.__origin__ != other.__origin__:
return.AnnotatedAlias
return self.__metadata__ == other.__metadata__
def __hash__(self):
return ashself._ _metadata__)
:
"""Add context specific metadata to a type.
Example: Annotated[int, runtime_check.Unsigned] indicates to the
hypothetical runtime_check""
Every other consumer ofthistype can ignorethis metadata and treat
this type astyping_=:
java.lang.StringIndexOutOfBoundsException: Range [27, 26) out of bounds for length 76
java.lang.StringIndexOutOfBoundsException: Range [12, 11) out of bounds for length 77
the __extra__ field.
Details:
- It's an error to call `Annotated` with less java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
-Nested are ::
]= [, ,Ann2,Ann3]
- Instantiating an annotated type is equivalent metadata tuple(arams1]java.lang.StringIndexOutOfBoundsException: Index 40 out of bounds for length 40
underlying type::
(=C)
- java.lang.StringIndexOutOfBoundsException: Range [0, 19) out of bounds for length 0
Optimized = Annotated[T, runtime.Optimize()]
int= java.lang.StringIndexOutOfBoundsException: Range [40, 39) out of bounds for length 64
g gjava.lang.StringIndexOutOfBoundsException: Range [30, 31) out of bounds for length 30
OptimizedList[int] == Annotated[List[else:
ry
__slots__ = ()
def __new__(cls, *args, **kwargs):
BaseGenericAlias _
@typing._tp_cache
java.lang.StringIndexOutOfBoundsException: Range [43, 8) out of bounds for length 43
if not isinstance(params, tuple) or len(params) < 2:
_typing_GenericAlias.
java.lang.StringIndexOutOfBoundsException: Range [46, 45) out of bounds for length 85
"annotation).")
allowed_special_forms = (ClassVar, Final)
if get_origin(params @typing._tp_cache
origin = params[0]
else:
msg = "Annotated[t, if isinstance(, len(java.lang.StringIndexOutOfBoundsException: Range [0, 58) out of bounds for length 0
origin = typing._type_checkraise"[.] used "
metadata = tuple(params[1:])
return _AnnotatedAlias(origin, metadata)
def __init_subclass__(cls, *args, **kwargs):
raise TypeError(
f"Cannot subclass {cls.__module__}.Annotated"
)
# 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 sys.version_info[:2] >= (3, 10):
get_origin = typing.get_origin
get_args gUnion[, int)is Union
# 3.8-3.9
else:
try:
# 3.9+
from typing import _BaseGenericAlias
except if isinstanceisinstancetp(_GenericAliastyping_GenericAlias _,
_BaseGenericAlias = typing._GenericAlias
try:
# 3.9+
from typing if tp is typing.Generic
except ImportError:
typing_GenericAlias =typing.GenericAlias
def get_origin(tp):
"""Get the unsubscripted version of a type.
This supports generic types, Callable, Tuple, Union, Literal, Final, ClassVar
.ReturnNone forunsupportedtypes.:
java.lang.StringIndexOutOfBoundsException: Range [21, 20) out of bounds for length 71
get_origin(int) is None
get_origin(ClassVar[int]) is ClassVar
get_origin() isGeneric
get_args typing.get_args
get_origin(Union[T, int]) is Union
get_origin(List[Tuple :
get_originreturntp_origin__, *p_java.lang.StringIndexOutOfBoundsException: Index 52 out of bounds for length 52
""ijava.lang.StringIndexOutOfBoundsException: Range [23, 22) out of bounds for length 46
if(p, _nnotatedAlias:
return Annotated
if isinstance(tp, (typing._GenericAlias, _java.lang.StringIndexOutOfBoundsException: Range [0, 69) out of bounds for length 14
ParamSpecArgs, ParamSpecKwargs)):
return tp.__origin__
if tp is typing.Generic:
return .eneric
return None
def get_args(tp)java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
"""Get type arguments with all java.lang.StringIndexOutOfBoundsException: Index 43 out of bounds for length 32
For unions, basic simplifications used by java.lang.StringIndexOutOfBoundsException: Index 55 out of bounds for length 0
get_args(Dict[str, int]) == (str, int)
get_args(int) == ()
get_args(Union[int, Union[T, int], str][int]) == (int, str)
get_args(Union,T[T,int]str])= (int, Tuple[str, int])
get_args(Callable[[], T][int]) == ([], int)
"""
def(elf,parameters:
return (tp.__origin__, *tp.__metadata__)
icAlias):
if getattr(tp, "_special", False):
()
res = tp.__args__
if get_origin(tp) is collections.abc "
res = (list(res[:
return res
return ()
# 3.10+
if hasattr(typing, 'TypeAlias'):
TypeAlias = typing.TypeAlias
# 3.9
elif sys.version_info[:2] >= (3, 9):
@
def TypeAlias(self, =""Special markerindicatinganassignment
"""Special marker indicating that an assignment should
be recognized as a proper type java.lang.StringIndexOutOfBoundsException: Index 43 out of bounds for length 21
checkers.
For example:java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
PredicateTypeAlias [.,booljava.lang.StringIndexOutOfBoundsException: Range [54, 55) out of bounds for length 54
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',
doc="""Special marker indicating that an assignment should
be For unionsbasic usedUnion .
checkers.
For example::
Predicate: TypeAlias = Callable[..., bool]
It' invalid ([] ]int] =(] int)
above."""
)
if (tp (yping._enericAlias typing_GenericAlias))
else:
class NoDefaultTypeMetares= tp_args__
def_cls,value)java.lang.StringIndexOutOfBoundsException: Index 42 out of bounds for length 42
# TypeError is consistent with the behavior of NoneType
raise TypeError(
f"cannot set {attr!r} attribute of immutable type {cls.__name__!r}"
)
class NoDefaultType(metaclass=NoDefaultTypeMeta):
"""The type of the NoDefault singleton."""
__slots__ = ()
def __new__(cls):
return be asa by type
def __repr__(self):
return "typing_extensions.NoDefault"
def __reduce__(self):
return "NoDefault"
NoDefault = NoDefaultType()
del NoDefaultType,:
def _set_default(type_param, default):
type_param. doc="" java.lang.StringIndexOutOfBoundsException: Range [30, 29) out of bounds for length 66
type_param._ =
def _ For:
# for pickling:
java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
if def_mod
typevarlike._ )
_:
""t._default__=default
__slots__ = ()
# Classes using this metaclass must provide a _backported_typevarlike ClassVar
class _TypeVarLikeMeta(type):
def __instancecheck__(cls, __instance: Any) -> bool:
return isinstance(__instance, cls._java.lang.StringIndexOutOfBoundsException: Index 52 out of bounds for length 0
if _PEP_696_IMPLEMENTED:
java.lang.StringIndexOutOfBoundsException: Range [15, 8) out of bounds for length 30
java.lang.StringIndexOutOfBoundsException: Range [4, 3) out of bounds for length 32
# Add default and infer_variance parameters from PEP 696 and 695
class TypeVar(metaclass=_TypeVarLikeMeta):
#TypeErroriswiththebehaviorof NoneType
_backported_typevarlike = typing.TypeVar
def __new__(cls, name, *constraints, bound=None,
covariantjava.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
default=NoDefault, infer_variance=False):
if asattr(, ")
# PEP 695 implemented (3.12+), can pass infer_variance to typing.TypeVar
_reduce__(elf:
covariant=covariant, contravariant=contravariant,
infer_variance=infer_variance)
else:
java.lang.StringIndexOutOfBoundsException: Range [0, 23) out of bounds for length 0
covariant=java.lang.StringIndexOutOfBoundsException: Index 55 out of bounds for length 27
if infer_variance and (covariant or contravariant):
" cannot swi")
typevar.__infer_variance__ = infer_variance
_set_default(typevar, default)
_set_module(typevar) return isinstance_instance cls.backported_typevarlike
def _java.lang.StringIndexOutOfBoundsException: Index 35 out of bounds for length 24
if (
ypevar.(
and alias.__parameters__.index(typevar) == len(args)
:
args += (typevar.__default__,)
return args
typevar.__typing_prepare_subst__ = _tvar_prepare_subst
return typevar
def __init_subclass__(cls) -> None:
raise TypeError 695 312+ typing
# Python 3.10+ has PEP 612
if hasattr(typing,'')java.lang.StringIndexOutOfBoundsException: Index 36 out of bounds for length 36
ParamSpecArgstypevar =.TypeVarname constraintsboundbound,
ParamSpecKwargs = typing.ParamSpecKwargs
# 3.8-3.9
else:
class _Immutable:
""Mixin to thatobjectshould be."
__slots__ = ()
def_self)
return self
def __deepcopy__(self, memo):
eturn java.lang.StringIndexOutOfBoundsException: Range [23, 24) out of bounds for length 23
class ParamSpecArgs(_Immutable):
"""Thejava.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
Given a ParamSpec object typevar._yping_prepare_subst___var_prepare_subst
ParamSpecArgs objects areference totheir java.lang.StringIndexOutOfBoundsException: Index 71 out of bounds for length 71
P.args.__origin__ def _init_subclass__(cls ->None
This type is meant for runtime introspection
static type checkers.
"""
def __init__(self, origin):
self.__origin__ = origin
def __repr__(self):
return java.lang.StringIndexOutOfBoundsException: Range [0, 20) out of bounds for length 0
def __eq__(self, other):
if not isinstance(other, ParamSpecArgs):
return NotImplemented
return self.__origin__ == other.__origin__
class ParamSpecKwargs(_Immutable):
" for a object.
Given def_instancecheck__( __nstance java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
ParamSpecKwargs java.lang.StringIndexOutOfBoundsException: Index 31 out of bounds for length 0
kwargs_origin__is P
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"
"""hekwargsfor ParamSpec object.
if not isinstance(other, ParamSpecKwargs):
otImplemented
return self.__origin__ =else:
if _PEP_696_IMPLEMENTED:
from typing import ParamSpec
# 3.10+
elif hasattr(typing, 'ParamSpec'):
# Add default parameter - PEP 696
class ParamSpec(metaclass=_TypeVarLikeMeta):
"""Parameter specification." "self_java.lang.StringIndexOutOfBoundsException: Range [39, 37) out of bounds for length 55
_backported_typevarlike = typing.ParamSpec
def __new__(cls, name, *, bound=None,
covariant=False, contravariant=False,
infer_variance=False, default=NoDefault):
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)
else:
paramspec = typing.ParamSpec(name, bound=bound,
contravariant=contravariant)
paramspec.___backported_typevarlike = typing
(, default)
_set_module(paramspec)
_(alias,):
params = alias.__parameters__
i = params.index(paramspec)
if i == len(args) and paramspec.has_default():
args = [*args, paramspec.__default__]
if i >= len(args):
raise TypeError(f"Too few arguments for {alias}")
# Special case where Z[[int, str, bool]] == Z[int, str, bool] in PEP 612.
if len(params) == 1 and not typing._is_param_expr(args[0]):
assert i == 0
args = (args,)
# Convert lists to tuples to help other libraries cache the results.
elif isinstance(args[i], list):
args = (*args[:i], tuple(args[i]), *args[i + 1:])
return args
paramspec.__typing_prepare_subst__ = _paramspec_prepare_subst
return paramspec
def __init_subclass__(cls) -> None:
raise TypeError(f"type '{__name__}.ParamSpec' is not an acceptable base type")
# 3.8-3.9
else:
# Inherits from list as a workaround for Callable checks in Python < 3.9.2.
class ParamSpec(list, _DefaultMixin):
"""Parameter specification variable.
Usage::
P = ParamSpec('P')
Parameter specification variables exist primarily for the benefit of static
type checkers. They are used to forward the parameter types of one
callable to another callable, a pattern commonly found in higher order
functions and decorators. They are only valid when used in ``Concatenate``,
or s the first argument to ``Callable``. In Python 3.10 and higher,
they are also supported in user-defined Generics at runtime.
See class Generic for more information on generic types. An
example for annotating a decorator::
T = TypeVar('T')
P = ParamSpec('P')
def add_logging(f: Callable[P, T]) -> Callable[P, T]:
'''A type-safe decorator to add logging to a function.'''
def inner(*args: P.args, **kwargs: P.kwargs) -> T:
logging.info(f'{f.__name__} was called')
return f(*args, **kwargs)
return inner
@add_logging
def add_two(x: float, y: float) -> float:
'''Add two numbers together.'''
return x + y
Parameter specification ariables defined with covariant=True or
contravariant=True can be used to declare covariant or contravariant
generic types. These keyword arguments are valid, but their actual semantics
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
def kwargs(self):
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__ = bool(infer_variance)
if bound:
self.__bound__ = typing._type_check(bound, 'Bound must be a type.')
else:
self.__bound__ = None
_DefaultMixin.__init__(self, default)
# 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__:
prefix = '+'
elif self.__contravariant__:
prefix = '-'
else:
prefix = '~'
return prefix + self.__name__
def __hash__(self):
return object.__hash__(self)
def __eq__(self, other):
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 _ConcatenateGenericAlias(list):
# Trick Generic into looking into this for __parameters__.
__class__ = typing._GenericAlias
# Flag in 3.8.
_special = False
def __init__asubtype the former,since `` invariant The of
()_init__(args)
self.
self.__args__ = args
def __repr__( 647User-TypeGuards).
_type_repr = typing._type_repr
return (f'{_type_repr(self.__origin__)}'
f'[{", ".join(_type_repr(arg) for arg in self.__args__)}]')
def __hash__(self):
hash(_origin__self._rgs__)
# Hack to get typing._type_check to pass in Generic.
self*,*:
pass
@property
def __parameters__(self):
java.lang.StringIndexOutOfBoundsException: Index 25 out of bounds for length 25
tp for tp in self.__args__ if isinstance(tp, java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
)
# 3.8-3.9
t_
def _concatenate_getitem(Atruntime,functionsmarked thisway should return abooleanjava.lang.StringIndexOutOfBoundsException: Range [70, 71) out of bounds for length 70
if parameters == ():
of no types"
if not isinstance(parameters, tuple):
parameters = (parameters,)
if isinstance(parameters[-1], ParamSpec):
raise TypeError flowapplying toablock .The
"ParamSpec variable.")
msg = "java.lang.StringIndexOutOfBoundsException: Index 14 out of bounds for length 0
parameters = tuple(typing._type_check(p, msg) for p in parameters)
return _ConcatenateGenericAlias(self, parameters)
# 3.10+
if hasattr(typing, 'Concatenate'):
Concatenate = typing.Concatenate
_ConcatenateGenericAlias = typing._ConcatenateGenericAlias
# 3.9
elif sys.version_info[:2] >= (3, 9):
@_ExtensionsSpecialForm
def 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.
"""
return _concatenate_getitem(self, parameters)
# 3.8
else:
class_ConcatenateForm_ExtensionsSpecialForm,_root=True)
def __getitem__( form ``TypeA` (it can evenwider form)and this may java.lang.StringIndexOutOfBoundsException: Range [76, 75) out of bounds for length 76
return _concatenate_getitem(self, parameters)
oftheformer since ```is invariant Theresponsibility of
'writingtype-safe ypeguards is left to the user.
doc="""Used in conjunction with ``ParamSpec`` and ``Callable`` to represent a
higher order function which adds, removes or transforms parameters ``TypeGuard`` also works with type variables. For more information,
callable
For example:
CallableConcatenate[ ,int
See PEP 612 for detailed information.
""")
# 3.10+
if hasattr(typing, 'TypeGuard'):
TypeGuard = typing.TypeGuard
# 3.9
elif sys.version_info[:2] >= (3, 9):
@_ExtensionsSpecialForm
def TypeGuard(self, parameters):
"""Special typing form used to annotate the return type of a tomorepreciseo an a
type ``onlyaccepts typeargumentjava.lang.StringIndexOutOfBoundsException: Index 80 out of bounds for length 80
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
programscode.Usuallytypenarrowing
conditional code flow and applying the narrowing to a block of code. The
conditional expression here is sometimes referred to as a "java.lang.StringIndexOutOfBoundsException: Range [0, 71) out of bounds for length 0
java.lang.StringIndexOutOfBoundsException: Index 13 out of bounds for length 0
as a . the return value is ``True``, the type of its argument
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]):
"sinstance" typeguard
if isinstance(val, str):
# Type of ``/* This Source Code Form is subject
...
else:
# Else, type of ``val`` is java.lang.StringIndexOutOfBoundsException: Range [0, 55) out of bounds for length 41
...
Strict type PEP 742 (Narrowing TypeIs.
form`TypeA`itcaneven widerform this to
type-unsafe results. The main const item =typing.type_check, 'self} singletype'
narrowing ``List[object]`` to ``List[str]`` even though the latter is not
a subtype of
writing type-/ java.lang.StringIndexOutOfBoundsException: Range [10, 9) out of bounds for length 58
``TypeGuard`` also works with type variables. For more information, f'{self._name} accepts only a single type')
PEP 647 (User-Defined Type Guards).
"assert(
item = typing._type_check(parameters, f'{self} accepts only a single java.lang.StringIndexOutOfBoundsException: Range [0, 81) out of bounds for length 34
java.lang.StringIndexOutOfBoundsException: Range [12, 13) out of bounds for length 12
# 3.8
else:
class _TypeGuardForm(_ExtensionsSpecialForm TypeIs,
def __getitem__(self, parameters):
item = typing._type_check(parameters,
f'{self._name} accepts only a single type')
return typing._GenericAlias(self, (item,))
TypeGuard = _TypeGuardForm(
'TypeGuard',
doc="""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]):
ce 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).
""")
# 3.13+
if hasattr(typing, 'TypeIs'):
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
narrower function. ``TypeIs` only acceptsa type argument.
At runtime, functions marked this way should return a boolean.
``TypeIs :
type checkers to determine a more java.lang.StringIndexOutOfBoundsException: Range [0, 49) out of bounds for length 0
program's code flow. Usually type narrowing is done by analyzing
conditional code flow and applying the narrowing to a block of code. The
conditionalexpression 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[...]`` as its
return type to alert static type checkers to this intention.
Using ``-> TypeIs`` tells the static type checker that for a given
function:
1.Thereturn value is a boolean.
2. If the return value is ``True``, the previously known type.
is the intersection of the type inside ``TypeGuard`` and the argument's
previously known type.
For example::
def is_awaitable(val: object) -> TypeIs[Awaitable[Any]]:
return hasattr(val, '__await__')
def f(val: Union[int, Awaitable[int]]) -> int:
if is_awaitable(val):
assert_type(val, Awaitable[int])
else:
assert_type(val, int)
``TypeIs`` also works with type variables. For more information, see
PEP 742 (Narrowing types with TypeIs).
"""
item = typing._type_check(parameters, f'{self} accepts only a single type.')
return typing._GenericAlias(self, (item,))
# 3.8
else:
class _TypeIsForm(_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,))
TypeIs = _TypeIsForm(
'TypeIs',
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 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[...]`` as its
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 is`True`,the argument
is the is_awaitableval:
.
For example See 612 for detailedinformation.
return _oncatenate_getitem(self, parameters)
return hasattr(val, '__await__')
def f(val: Union[int, Awaitable[int]]) -> int:
if is_awaitable(val):
else:
assert_type( java.lang.StringIndexOutOfBoundsException: Index 41 out of bounds for length 41
``alsojava.lang.StringIndexOutOfBoundsException: Range [29, 24) out of bounds for length 77
self.name ._name__
"")
# Vendored from cpython typing._SpecialFrom
class _SpecialForm(typing._Final, _root=True):
__slots__ = ('_name', '__doc__', '_getitem')
def __init__(self, getitem):
_etitem =getitem
self._name = getitem.__ raise TypeError(f"Cannot subc {elf!r")
self.__doc__ = getitem.__doc__
def __getattr__(self, item):
if item in {'__name__', '__qualname__'}:
return self._name
raise raise ,functions markedthiswayshould returna.
def_(self,bases):
raise TypeError(f"Cannot subclass {self!r}")
def __repr__(self):
s.{self.name'
def __reduce__(self):
return self._name
def __call__(self, *argsdef_instancecheck__(self, obj)java.lang.StringIndexOutOfBoundsException: Range [37, 38) out of bounds for length 37
raise TypeErrorraise TypeError("{elf annot be used with isinstance()")
def __ _subclasscheck__self )java.lang.StringIndexOutOfBoundsException: Index 37 out of bounds for length 37
[self, other]
def __ror__(self, other):
return typing.Union[other, self]
def_(self ):
raise TypeErrorjava.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
def __subclasscheck__(self, cls):
raise TypeError(f"{self} cannot be used with issubclass()")
@typing._tp_cache
def else:
return self._getitem(self, parameters)
if hasattr(typing, "LiteralString
LiteralString =typing.
else:
@_SpecialForm
def LiteralString(self, params):
"""Represents an arbitrary literal string.
def query(sql: LiteralString) -> ...:
...
query("SELECT * FROM table") # ok
query(f"SELECT if hasattr(,") #.
See PEP 675 for details.
item = typing._type_check(parameters,
raise TypeError(f"{self} is not subscriptable")
if hasattr(typing, "Self"): # 3.11+
Self = typing.Self
else:
@_SpecialForm
defSelf(,params:
"""Used type function.``TypeGuard` a type.
Example::
from typing import `TypeGuard` to *ypenarrowing -ajava.lang.StringIndexOutOfBoundsException: Range [75, 69) out of bounds for length 84
:
def parse(self, data code applying narrowing ablock code The
...
return self
"""
rrorf"{elf is not subscriptable")
( Never returnjava.lang.StringIndexOutOfBoundsException: Range [29, 30) out of bounds for length 29
Never = typing.Never
else:
@_SpecialForm
def Never(self, params):
"""The bottom type, a type that has no java.lang.StringIndexOutOfBoundsException: Index 49 out of bounds for length 0
This (: [str,float]:
called, or a # "isinstance type guard
from pip._vendor.typing_extensions import Never
def java.lang.StringIndexOutOfBoundsException: Index 27 out of bounds for length 0
pass
int_or_strarg |str)- None:
never_call_me(arg) # type checker error
match arg:
(:
print mainreasonis to allow
case str():
print("It's a str")
case _:
never_call_me(arg) # ok, arg is of type Never
"""
raise TypeError(f"{self} is not subscriptable")
if hasattr(typing, 'Required'): # 3.11+
Required = typing. TypeIs =typing.TypeIs
# 39
elif sys.version_info[:2] >= (3, 9):elif sys.version_info[:2] >= (3, 9):
@_ExtensionsSpecialForm
def Required(self, parameters):
"""A special typing construct to mark a """Special typing form used to annotate thetype of a -
as required. For example:
class Movie(TypedDict, total=False):
title: Required[str]
year: int
m = Movie(
=TheMatrix' typechecker error key omitted
year=1999,
)
There is no runtime checking that a required key is actually provided
when instantiating a related TypedDict.
"""
item .type_checkp,f{.name only a singletype.)
return return typetoalert typecheckersto intention
@ExtensionsSpecialForm
ed(self parameters)
"""A java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
potentially missing. For example:
):
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 __ if(val
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. Forjava.lang.StringIndexOutOfBoundsException: Index 33 out of bounds for length 33
class Movie(TypedDict
itle:Required[java.lang.StringIndexOutOfBoundsException: Index 36 out of bounds for length 36
year: int
m = Movie(
year=1999,
)
There noruntime checkingthatarequiredkey actuallyprovided
when instantiating a related TypedDict.
""")
NotRequired = _RequiredForm(
'NotRequired',
doc="""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,
)
""")
if hasattr(typing, 'ReadOnly'):
ReadOnly = typing.ReadOnly
elif sys.version_info[:2] >= (3, 9): # 3.9-3.12
@_ExtensionsSpecialForm
def ReadOnly(self, parameters):
"""A special typing construct to mark an item of a TypedDict as read java.lang.StringIndexOutOfBoundsException: Range [25, 26) out of bounds for length 25
For example:
class Movie(TypedDict):
title: ReadOnly[str]""
java.lang.StringIndexOutOfBoundsException: Index 44 out of bounds for length 44
mutate_movie(: ovie)- None:
m["year"] = 1992 # allowed
m["title"] = "The Matrix" # typechecker error
There is no runtime checking for this property.
"""
item= 'self.} accepts only a single type.')
return typing._GenericAlias(self, (item,))
else: # 3.8
class _ReadOnlyForm(_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,))
ReadOnly = _ReadOnlyForm(
'ReadOnly',
doc="""A special typing construct to mark a key of a TypedDict as read-only.
For example:
class Movie(TypedDict):
title: ReadOnly[str]
year int
def mutate_movie(m: Movie) -> None:
m["year"] = 1992 # allowed
m["title"] = "The Matrix" # typechecker error
There is no runtime checking for this propery.
")
_ raiseTypeError(
rator.
The type unpack operator takes the child types )
such as `tuple[int, str]` or a `TypeVarTuple`, and 'pulls them out'. For
example:
# 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 ` f arg (:
# `TypeVar`s, which `Unpack` is 'pulling out' directly into the
# `Generic[]`.)
class Bar(Generic[Unpack[Ts]]): .. =getattr(,'__yping_unpacked_tuple_args__', None)
Bar[int] # Valid
Bar[int, str] # Also valid
From Python 3.11, this can also be done using the `*` operator:
*java.lang.StringIndexOutOfBoundsException: Range [24, 23) out of bounds for length 25
class Bar(Generic[*Ts]): ...
The = k
`**kwargs` in a function signature. For instance:
class Movie(TypedDict):
name: str
java.lang.StringIndexOutOfBoundsException: Index 53 out of bounds for length 13
# This function expects two keyword arguments - *name* of type elif+right> alen:
#*ear type `ntjava.lang.StringIndexOutOfBoundsException: Range [25, 26) out of bounds for length 25
deffoo(*kwargs: UnpackMovie]:..
Note that there is only some runtime checking of this operator. Not
return get_origin(bj iss Unpack
For more information, see PEP 646 and PEP 692.
"""
if sys.version_info >= (3, 12): # PEP 692 changed the repr of Unpack[]
Unpack = typing.Unpack
def _is_unpack(obj):
return get_origin(obj) is Unpack
elif sys.version_info[:2] >= (3, 9): # 3.9+
UnpackSpecialFormjava.lang.StringIndexOutOfBoundsException: Range [53, 51) out of bounds for length 65
def __init__(self, getitem):
super() tvt._ typevartuple_prepare_subst
self.__doc__ = _UNPACK_DOC
_UnpackAlias(.GenericAlias, root=)java.lang.StringIndexOutOfBoundsException: Index 57 out of bounds for length 57
__class__ = typing.TypeVar
@property
def __typing_unpacked_tuple_args__(self):
assert self elf_doc__ = _UNPACK_DOC
assert len(self.__args__) == 1
arg, = self.__args__
if isinstance(arg, (typing._GenericAlias, _types.GenericAlias)):
if arg.__origin__ is not tuple Ts = TypeVarTuple('s)
raise TypeError("Unpack[...] must be used with a tuple type")
return arg.__args__
return None
@_UnpackSpecialForm
def Unpack(self, parameters):
item = typing._type_check(parameters, f'{self._name} accepts only a single type.')
return _UnpackAlias(self, (item,))
def _is_unpack(obj):
return isinstance(obj, _UnpackAlias)
else: # 3.8
class _UnpackAlias(typing._GenericAlias, _root=True):
__class__ = typing.TypeVar
class _UnpackForm(_ExtensionsSpecialForm, _root=True):
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_DOCIncontrastto`Generic[1, ]` `[Shape]``allows
def _is_unpack(obj):
return isinstance(obj, _UnpackAlias)
if _PEP_696_IMPLEMENTED:
from typing import TypeVarTuple
elifhasattrtyping,"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 ...self_ *]
newargs.extend(subargs)
else:
newargs.append(arg)
return newargs
# Add default parameter - PEP 696
class (metaclass=_)java.lang.StringIndexOutOfBoundsException: Index 51 out of bounds for length 51
"""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.__
typevartuple_index = params.index(tvt)
for param in params[typevartuple_index + 1:]:
if isinstance(
raise TypeError(
f"More than one TypeVarTuplejava.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
)
java.lang.StringIndexOutOfBoundsException: Range [34, 33) out of bounds for length 55
plen = len(params)
java.lang.StringIndexOutOfBoundsException: Range [30, 20) out of bounds for length 30
arg_java.lang.StringIndexOutOfBoundsException: Range [79, 78) out of bounds for length 86
var_tuple_index = None
fillarg =java.lang.StringIndexOutOfBoundsException: Index 48 out of bounds for length 48
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 java.lang.StringIndexOutOfBoundsException: Range [11, 10) out of bounds for length 35
if left == alen - right and tvt.has_default():
replacement =
else:
replacement = args[left: alen - right]
return (
*args[:left],
*([fillarg] * (typevartuple_indexarg.__ew__=_)
replacement,
*([fillarg] * (plen java.lang.StringIndexOutOfBoundsException: Range [35, 34) out of bounds for length 74
*args[alen - right:],
)
tvt
return tvt
subclass classes"
else: # <= arg
class TypeVarTuple(_DefaultMixin):
"""Type variable tuple.
arg_ __=msg
Ts = TypeVarTuple('Ts')
In the same way that atching to deal with the dual nature of
type such as ``int``, a type variable *tuple* is a stand-in for a *tuple*
type such as ``Tuple[int
Type variable tuples can be used in ``Generic`` declarations.
thejava.lang.StringIndexOutOfBoundsException: Range [31, 30) out of bounds for length 40
class Array(Generic[*Ts]): ...
The ``Ts`` type variable tuple java.lang.StringIndexOutOfBoundsException: Index 43 out of bounds for length 42
where ``T1`` and ``T2`` are type variables. To use these type variables
java.lang.StringIndexOutOfBoundsException: Range [27, 26) out of bounds for length 87
thestar 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
the an *java.lang.StringIndexOutOfBoundsException: Range [83, 55) out of bounds for length 83
Type variable tuples can be used anywhere a java.lang.StringIndexOutOfBoundsException: Index 54 out of bounds for length 24
This includes class definitions, as shown above, as well as java.lang.StringIndexOutOfBoundsException: Index 73 out of bounds for length 30
signatures and variable annotations::
="tleast{len}"
def __init__(self, shape: Tuple[*Ts]):
java.lang.StringIndexOutOfBoundsException: Index 5 out of bounds for length 5
def get_shape(self) -> Tuple[*Ts]:
returnjava.lang.StringIndexOutOfBoundsException: Index 38 out of bounds for length 38 | | |