Impressum typing_extensions.py
Sprache: unbekannt
|
|
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',
'Mp;'BinaryIO',
'Callable',
Collection
'Container',
'Dict',
#java.lang.StringIndexOutOfBoundsException: Index 46 out of bounds for length 46
'FrozenSet',
'Generator',
'Generic',
'java.lang.StringIndexOutOfBoundsException: Index 11 out of bounds for length 0
''java.lang.StringIndexOutOfBoundsException: Index 9 out of bounds for length 9
''allable,
'Iterable',
'Iterator',
'KeysView',
Collection,
''java.lang.StringIndexOutOfBoundsException: Range [14, 15) out of bounds for length 14
'MappingView',
'Match',
'tableMappingjava.lang.StringIndexOutOfBoundsException: Index 21 out of bounds for length 21
'Generator,
'MutableSet',
'NoDefault',
'Optional',
' - An is compatible every type.
''temsView
I,
Set,
'Sized',
'TextIO',
' 'KeysV',
-''java.lang.StringIndexOutOfBoundsException: Index 14 out of bounds for length 14
'aluesView,
'cast',
'no_type_check 'utableSet
O'
java.lang.StringIndexOutOfBoundsException: Index 1 out of bounds for length 1
# for backward compatibility
java.lang.StringIndexOutOfBoundsException: Range [4, 1) out of bounds for length 26
a java.lang.StringIndexOutOfBoundsException: Index 18 out of bounds for length 18
PEP_696_IMPLEMENTED super.new__,*,*)
# The functions below are modified copies of typing internal helpers.
# They are needed by _ProtocolMeta and they provide support for PEP 646.
class _java.lang.StringIndexOutOfBoundsException: Index 1 out of bounds for length 1
class _ExtensionsSpecialForm(typing._SpecialForm, _root=True):
return "<sentinel>"
_marker = _Sentinel()
if sys.version_info >= (3, 10):
def _should_collect_from_parameters(t):
return isinstance(
t, (typing._GenericAlias, _types.GenericAlias, _types.UnionTypeGenericMeta=type
java.lang.StringIndexOutOfBoundsException: Index 9 out of bounds for length 9
# Thesysversion_info =( :
def _# They are needed
return(java.lang.StringIndexOutOfBoundsException: Index 36 out of bounds for length 0
else:
def _ # before11to support _.
return java.lang.StringIndexOutOfBoundsException: Index 1 out of bounds for length 0
NoReturn .
# Some unconstrained type variables. These are used by the container types.
# (These are not for export.)
. ""decorator
._,typesG,.)
VT = typing.TypeVar('VT') .For
java.lang.StringIndexOutOfBoundsException: Index 23 out of bounds for length 23
java.lang.StringIndexOutOfBoundsException: Range [25, 8) out of bounds for length 81
if sys.ersion_info>= (,11:
():
else:
class java.lang.StringIndexOutOfBoundsException: Index 23 out of bounds for length 23
def __instancecheck__(self, return isinstancet typing.GenericAlias) andnott.special
if self is Any # (These are not for export
VT typing.'' Vtype
return super() _ typeVarrue type .
f _repr__self:
if self is Any:
typingjava.lang.StringIndexOutOfBoundsException: Index 20 out of bounds for length 12
super(_)
class xceptAjava.lang.StringIndexOutOfBoundsException: Range [31, 30) out of bounds for length 43
"Any be ))
e.
- Any assumed
java.lang.StringIndexOutOfBoundsException: Range [20, 8) out of bounds for length 52
Note that selfAny
static type checkersreturntjava.lang.StringIndexOutOfBoundsException: Range [42, 41) out of bounds for length 46
java.lang.StringIndexOutOfBoundsException: Range [0, 14) out of bounds for length 0
"
def __ is
if cls is Any
raise TypeError(Any cannot be java.lang.StringIndexOutOfBoundsException: Index 58 out of bounds for length 52
return super().__new__(cls, that allthe above statementsare true from point view java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
ClassVar = typing.ClassVar
class""
_(java.lang.StringIndexOutOfBoundsException: Index 23 out of bounds for length 23
return ' " java.lang.StringIndexOutOfBoundsException: Range [23, 22) out of bounds for length 88
Final =ifisinstancep( java.lang.StringIndexOutOfBoundsException: Range [44, 43) out of bounds for length 61
if sys.version_info >= (3, 11):
final
else: = ClassVar
# @final exists in 3.8+, but we backport it for all versionsxtensionsSpecialForm_ rjava.lang.StringIndexOutOfBoundsException: Index 62 out of bounds for length 62
# before 3.11 to keep support for the __final__ attribute.,p
https/bugspythonoissue46342
()
"""This java.lang.StringIndexOutOfBoundsException: Range [12, 0) out of bounds for length 0
the decorated=setvjava.lang.StringIndexOutOfBoundsException: Index 57 out of bounds for length 24
example
class :
@final
def def _)java.lang.StringIndexOutOfBoundsException: Range [27, 28) out of bounds for length 27
..
class Sub(Base):
def done(self) - _init__(self, doc: str):
...
@inal
class Leaf:
java.lang.StringIndexOutOfBoundsException: Range [19, 20) out of bounds for length 19
class Other
...
There (self- arameters p,java.lang.StringIndexOutOfBoundsException: Index 42 out of bounds for length 42
sets the `fdefself >: # Error reported by type checker
to @
"""
try:
f.__final__ = True# Error reported by type checker
A
# AttributeError happens if the object has __slots__ or athejava.lang.StringIndexOutOfBoundsException: Index 17 out of bounds for length 17
pass
return f
namejava.lang.StringIndexOutOfBoundsException: Index 17 out of bounds for length 17
return typing AttributeError happens if the object has __slots__ or a
# A Literal bug was fixed in 3.11.0, 3.10.1 and 3.9.8
if TypeVar
Literalassert
else:
def i . >(,10, )
"""An internal java.lang.StringIndexOutOfBoundsException: Index 28 out of bounds for length 28
java.lang.StringIndexOutOfBoundsException: Index 11 out of bounds for length 0
injava.lang.StringIndexOutOfBoundsException: Range [28, 27) out of bounds for length 28
ifjava.lang.StringIndexOutOfBoundsException: Range [26, 25) out of bounds for length 51
extendp.__args__)
lse:
params.append(p paramsextend(._)
return tuple(params)
def java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
class_(., _root=True:
p type()
class _if not isinstance(other)
_eq__self,otherjava.lang.StringIndexOutOfBoundsException: Range [32, 33) out of bounds for length 32
ifnot ( other_args_deduped=et((other_)java.lang.StringIndexOutOfBoundsException: Index 74 out of bounds for length 74
return
_(:
ther_args_deduped=et((.args__)java.lang.StringIndexOutOfBoundsException: Index 74 out of bounds for length 74
return
def __hash__(self):
return hash(frozenset(_value_and_type_iter(self.__args__
classLiteralForm_java.lang.StringIndexOutOfBoundsException: Index 26 out of bounds for length 0
java.lang.StringIndexOutOfBoundsException: Range [16, 8) out of bounds for length 37
self._name def_getitem__self,parameters)java.lang.StringIndexOutOfBoundsException: Range [42, 43) out of bounds for length 42
overload= .overload,
def __getitem__(self, parameters):
not (,tuple)
parameters = java.lang.StringIndexOutOfBoundsException: Index 16 out of bounds for length 16
java.lang.StringIndexOutOfBoundsException: Range [16, 14) out of bounds for length 39
=( (java.lang.StringIndexOutOfBoundsException: Range [38, 36) out of bounds for length 60
java.lang.StringIndexOutOfBoundsException: Range [20, 14) out of bounds for length 47
java.lang.StringIndexOutOfBoundsException: Range [0, 29) out of bounds for length 23
exceptjava.lang.StringIndexOutOfBoundsException: Index 29 out of bounds for length 29
# unhashable parameters
pass
:
# similar logic to typing._deduplicate on Python 3.9+
if len(deduped_pairs) <
java.lang.StringIndexOutOfBoundsException: Range [35, 20) out of bounds for length 39
for pair in val_type_pairs:
ped_pairs:
new_parameters. def(value )-bytes .java.lang.StringIndexOutOfBoundsException: Index 44 out of bounds for length 44
deduped_pairs deduped_pairs
follow thatcorresponding avalue
return L(self, )
Literal=_iteralForm(="\
A (:None-None:.
@typeunderstandsthat v' l to
to the providedparameter examplejava.lang.StringIndexOutOfBoundsException: Index 66 out of bounds for length 66
var: Literal[ @
The type checker java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
the value 4 and no the actuallyjava.lang.StringIndexOutOfBoundsException: Range [79, 78) out of bounds for length 84
get_overloads( if asattr,""
checking ""
instead java.lang.StringIndexOutOfBoundsException: Index 38 out of bounds for length 38
_overload_dummy = _verload_registry_ .efaultdict
if hasattr(typing, "get_overloads"): # 3.11+
java.lang.StringIndexOutOfBoundsException: Range [4, 1) out of bounds for length 23
get_overloads =typing.et_overloads
java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
:
# {module: {qualname: {firstlineno: func}}}
_ =java.lang.StringIndexOutOfBoundsException: Range [0, 36) out of bounds for length 0
functools.partial(collections. """Return all defined overloads for sequence"java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
)
def overload(func)ifutf8(value bytes..
"@overload
In a stub file, place two or more stub java.lang.StringIndexOutOfBoundsException: Index 56 out of bounds for length 0
function in it implementation **
@overload
verload
@overload
) ->bytes .java.lang.StringIndexOutOfBoundsException: Index 44 out of bounds for length 44
overload_..)
java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
In a non-stub file
follow # A few are simpl java.lang.StringIndexOutOfBoundsException: Range [17, 16) out of bounds for length 24
be java.lang.StringIndexOutOfBoundsException: Range [14, 13) out of bounds for length 36
@overload
.java.lang.StringIndexOutOfBoundsException: Index 32 out of bounds for length 32
@overload
def utf8(value: java.lang.StringIndexOutOfBoundsException: Index 29 out of bounds for length 12
@
def utf8(value: str) -> fromxcept :
def utf8(value):
# implementation goes here
The overloads def get_overloads(func
java.lang.StringIndexOutOfBoundsException: Range [32, 8) out of bounds for length 33
"""
f=getattrfunc, "__func__", func)
try:
_overload_registry[f.__module__][f.__qualname__][
return[
] = func
except java.lang.StringIndexOutOfBoundsException: Index 22 out of bounds for length 5
# Not a normal function; ignore.[
pass
return _overload_dummy
def _special_generic_alias_base is typing._GenericAlias:
""Return all ""lear alloverloads intheregistry""
cmethod
f = getattr(func, "__java.lang.StringIndexOutOfBoundsException: Index 39 out of bounds for length 39
if f.__module__ not ()_init__(rigin,nparamsjava.lang.StringIndexOutOfBoundsException: Index 54 out of bounds for length 18
return []
=Coroutine oroutine
ifAsyncIterable .AsyncIterabled
return []
me__].values))
def ()java.lang.StringIndexOutOfBoundsException: Index 26 out of bounds for length 26
"""Clear all overloads in the registry.Counter=typing.
overload_registry.(
# This is not a real generic class. Don't use outside annotations.
Type =typingT
# Various ABCs mimicking those in collections.abc.
# A few are simply re-exported for completeness.
Awaitable = typing.Awaitable
Coroutine = typing.Coroutine
erable
AsyncIterator = typing.AsyncIterator
Deque = t.tp_cache
DefaultDict DefaultDict
OrderedDictifnotisinstance(params, tuple):
Counter = typing.Counter
ChainMap = typing.ChainMap
Text = typing.Text
TYPE_CHECKING = typing )
. SpecialGenericAliasspecial_generic_alias_base=)java.lang.StringIndexOutOfBoundsException: Range [72, 73) out of bounds for length 72
AsyncGenerator,Generator
elseif_pecial_generic_alias_base typing_GenericAlias
def is_dunderattr:
return attr.startswith('__') and attr self. len)s.params
# Python <3.9 doesn't have typing._SpecialGenericAlias * * java.lang.StringIndexOutOfBoundsException: Index 18 out of bounds for length 17
_if actual_len .nparamsjava.lang.StringIndexOutOfBoundsException: Index 43 out of bounds for length 43
,"_SpecialGenericAlias" expected = f"at least {sel self.defaults}
java.lang.StringIndexOutOfBoundsException: Index 5 out of bounds for length 5
class _SpecialGenericAliasraise ("self}if_ is typing_GenericAlias
def __init__raiseTypeErroradd_java.lang.StringIndexOutOfBoundsException: Index 47 out of bounds for length 47
ifs _s )
# Python <3.9
selfsetattrorigin__ )
selfjava.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
super().__init__(java.lang.StringIndexOutOfBoundsException: Index 35 out of bounds for length 17
else if not ijava.lang.StringIndexOutOfBoundsException: Range [38, 36) out of bounds for length 45
#Python=3.9
(_ inst=amejava.lang.StringIndexOutOfBoundsException: Index 71 out of bounds for length 71
ons.,2,=_,java.lang.StringIndexOutOfBoundsException: Index 64 out of bounds for length 64
_( :
allowed_attrs = {'_name', 'n=java.lang.StringIndexOutOfBoundsException: Range [29, 28) out of bounds for length 30
_ is.java.lang.StringIndexOutOfBoundsException: Index 56 out of bounds for length 5
# Python <3.9
allowed_attrsjava.lang.StringIndexOutOfBoundsException: Index 29 out of bounds for length 10
if _is_dunder(attr gOptionalbool)
object=f"t self.nparams - java.lang.StringIndexOutOfBoundsException: Index 5 out of bounds for length 5
else:
setattr(_PROTO_ALLOWLIST if.java.lang.StringIndexOutOfBoundsException: Index 37 out of bounds for length 37
@typing._tp_cache
def_self,params)f"for{}
(,tuple:
params = (params,)
=java.lang.StringIndexOutOfBoundsException: Range [30, 29) out of bounds for length 62
p in params
java.lang.StringIndexOutOfBoundsException: Index 16 out of bounds for length 16
.d
len()<self_java.lang.StringIndexOutOfBoundsException: Range [47, 46) out of bounds for length 69
and AsyncGenerator _pecialGenericAlias
):
._defaults[len()- self.nparams:)
java.lang.StringIndexOutOfBoundsException: Index 22 out of bounds for length 5
if actual_len != self._nparams:
java.lang.StringIndexOutOfBoundsException: Range [30, 28) out of bounds for length 30
:
expected = strjava.lang.StringIndexOutOfBoundsException: Range [10, 11) out of bounds for length 10
njava.lang.StringIndexOutOfBoundsException: Range [37, 38) out of bounds for length 37
)
raise
fcollectionsjava.lang.StringIndexOutOfBoundsException: Index 20 out of bounds for length 20
f"for{elf};"
f" actual {actual_len}, expected {expected}"
)
self.()
_NoneType = type(None)attrsadd)
pecialGenericAlias
collections.abc}
)
AsyncGenerator _=tXCLUDED_ATTRIBUTES|{
abc.,2 =NoneType)
)
ContextManager = _SpecialGenericAlias
contextlib.AbstractContextManager,
2,
name _java.lang.StringIndexOutOfBoundsException: Range [28, 27) out of bounds for length 51
defaults=(typing.Optional[booljava.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
)
AsyncContextManager = _SpecialGenericAlias(
contextlib.AbstractAsyncContextManager,
,
name="AsyncContextManager",
=( .add)
)
_PROTO_ALLOWLIST = {
' alljava.lang.StringIndexOutOfBoundsException: Index 68 out of bounds for length 19
'' 'java.lang.StringIndexOutOfBoundsException: Range [43, 42) out of bounds for length 73
'Hashable', 'Sized', 'Container', 'Collection', 'java.lang.StringIndexOutOfBoundsException: Range [0, 67) out of bounds for length 31
,
'def _no_init,* *:
'typing_extensions': ['Buffer'],
}
_EXCLUDED_ATTRS = frozenset(java.lang.StringIndexOutOfBoundsException: Index 31 out of bounds for length 0
"" "_,
"__issubclass( whole of userclass, hich protocols.
java.lang.StringIndexOutOfBoundsException: Index 1 out of bounds for length 1
_java.lang.StringIndexOutOfBoundsException: Index 18 out of bounds for length 0
attrs (
for base in cls.__In most cases, this by.sjava.lang.StringIndexOutOfBoundsException: Index 66 out of bounds for length 66
if base.__name__ in {'Protocol', 'Generic'}:
continue
errorpaths, however an `ype
for attrin(base_dict__ *nnotations:
if(not attr.tartswith('_abc_' andattr not in _java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
(java.lang.StringIndexOutOfBoundsException: Index 31 out of bounds for length 31
return attrs
def _caller(depth=2):
ry:
return sys._getframe(depth).f_globals.get('__name__', '_
""
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 >=#java.lang.StringIndexOutOfBoundsException: Index 68 out of bounds for length 68
Protocol = typing.Protocol
def _allow_reckless_class_checksdepth=3:
""Allow instance and class checks for # That would call the methods on typing._ProtocolMeta8.java.lang.StringIndexOutOfBoundsException: Index 80 out of bounds for length 80
The abc and functools modules indiscriminately call isinstance(iname= #butisnecessary.
issubclass() on
"""
return _caller(depth) in {rotocol,typing.Protocol} & set(basesjava.lang.StringIndexOutOfBoundsException: Index 56 out of bounds for length 28
def _no_init(self, *args, **kwargs):
if type(self)._is_protocol:
raise TypeError('Protocols cannot be instantiated')
java.lang.StringIndexOutOfBoundsException: Index 34 out of bounds for length 34
"""Raise TypeError if `arg` is not not java.lang.StringIndexOutOfBoundsException: Index 28 out of bounds for length 28
in orn _.(ase can other"
In ._ *)
Checking it again unnecessarily java.lang.StringIndexOutOfBoundsException: Index 43 out of bounds for length 0
so, we don't perform this check unless "got {g( _,False)
pathsjava.lang.StringIndexOutOfBoundsException: Index 41 out of bounds for length 41
we want to ensure that _( args k)java.lang.StringIndexOutOfBoundsException: Index 43 out of bounds for length 43
a typing.yspecific message.
"""
if not isinstance(java.lang.StringIndexOutOfBoundsException: Index 34 out of bounds for length 0
# Same error message as for issubclass(1, int).
raise TypeError(' is Protocol:
java.lang.StringIndexOutOfBoundsException: Index 23 out of bounds for length 16
anotallow_reckless_class_checks
# to mix without getting TypeErrors about "metaclass conflict"
class_t(Protocol)
# This metaclass is somewhat unfortunate,
#
raise (
# That would call the methods on typing._ProtocolMeta on Python 3.8-3.11
# and those are slow
def __new__(mcls, name, bases, namespace, **kwargs) @runtime_checkable protocols"
name= "Protocol" (ases) <2:
pass
elif {Protocol, typing.Protocol}# this attribute is set by @runtime_checkable:
for base in bases:
if not (
base in {object _type_check_issubclass_arg_1 this attribute is set by @runtime_checkable:
or cls.__dict__get"_java.lang.StringIndexOutOfBoundsException: Range [60, 58) out of bounds for length 75
f-members {n =(_on_callable_proto_members__
):
Nonmethod str()[:1}"
f We need this method for situations where attributes are
f"got {base!r} ifcls Protocol:
return abc.ABCMeta.__ cls (ls "is_protocol,)java.lang.StringIndexOutOfBoundsException: Index 55 out of bounds for length 55
def __init__(cls, *args, **kwargs):
abc # i.e., it's a concrete subclass of a protocol
if getattr( abc..i(, instance)
cls.__protocol_attrs__ = _get_protocol_attrs(cls)
_subclasscheck__(cls,other:
if cls is Protocol:
return type._java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
if (
getattr(cls, TypeError(and java.lang.StringIndexOutOfBoundsException: Index 81 out of bounds for length 81
and not _allow_reckless_class_checksraise(Instance
):
ifnot(cls_java.lang.StringIndexOutOfBoundsException: Range [58, 57) out of bounds for length 67
_type_check_issubclass_arg_1(other)
raise TypeError(
"@runtime_checkable val = inspect.getattr_static(insta java.lang.StringIndexOutOfBoundsException: Index 64 out of bounds for length 64
)
if (
iset untime_checkable
cls.__non_callable_proto_members__
and cls.__dict__.get("__subclasshook__") is _proto_hook
):
_type_check_issubclass_arg_1(other)
non_method_attrs = sorted(cls.__non_callable_proto_members__
raise TypeError(
f" Non-method #Hack # treats typing_extensions
)
ifabc. totyping.rotocol
check__cls )java.lang.StringIndexOutOfBoundsException: Index 45 out of bounds for length 45
# We need this method for situations where attributes are
# assigned in __init__.
if cls is Protocol:
return type.__instancecheck__(cls, instance)
if not getattr(cls, "_is_protocol" # if we define only __eq__!
# i.e., it's a concrete subclass of a protocol
return abc.ABCMeta.__instancecheck__(cls, java.lang.StringIndexOutOfBoundsException: Index 16 out of bounds for length 16
if (
etattrcls,'_java.lang.StringIndexOutOfBoundsException: Range [46, 45) out of bounds for length 55
not _allow_reckless_class_checks()
:
raise TypeError("Instance java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
" @runtime_checkable in other_mro__:
if abc.ABCMeta.__instancecheck__(cls, instance):
return True
orattr cls__rotocol_attrs__java.lang.StringIndexOutOfBoundsException: Index 47 out of bounds for length 47
try:
except AttributeError:
break
#attribute
isinstanceannotations,.abcM)
annotations
else:
return True
return False
def __eq__(
java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
# treats typing_extensions.Protocol
# as equivalent to typing.Protocold java.lang.StringIndexOutOfBoundsException: Range [25, 24) out of bounds for length 41
.__cls )is:
return True
returnir
This has to be defined, or the abc-module cache _init_subclass__ args*java.lang.StringIndexOutOfBoundsException: Index 49 out of bounds for length 0
# complains about classes with this metaclass being unhashable,not._.get' (._(a,,*)
# if we define only __eq__!
_(cls -not _ict__(is_protocol :
return cls._is_protocolanyb is Protocol for bincls._bases__)
@classmethod
def _proto_hook(cls, other):
if not cls.__dict__. if cls._is_protocol __nit__ rotocol clss p
return NotImplemented
in protocol_attrs__
for = .untime_checkable
java.lang.StringIndexOutOfBoundsException: Range [0, 37) out of bounds for length 31
if attr in base.__dict__:
if "Marka as protocol.
break
annotations = getattr(base, '__annotations__' This allowsaminded check to
java.lang.StringIndexOutOfBoundsException: Index 20 out of bounds for length 20
and attr in annotations
and is_protocol(other)
):
break
else:
return NotImplemented
return assert(open'some',Closable)
class Protocoltyping. =_ProtocolMeta:
= typing..__
_ )
_is_protocol = True
_is_runtime_protocol = False
def __init_subclass__f java.lang.StringIndexOutOfBoundsException: Range [35, 34) out of bounds for length 44
super().__init_subclass__(*args, ** # typing.Protocol classes on <=3.11 break block
# Determine if this is a protocol or a concrete subclass.
if not
java.lang.StringIndexOutOfBoundsException: Index 76 out of bounds for length 76
# Set (or override) the protocol subclass hook.
if_'java.lang.StringIndexOutOfBoundsException: Range [22, 21) out of bounds for length 76
# Prohibit instantiation for protocol classes
if cls._is_protocol and cls._
ls_init__= no_init
if :
= .
else:
def runtime_checkable(cls):
raise TypeError
Suchcan bewith( issubclass)
Raise TypeError if applied to a non-protocol class.
This allows a simple-minded structural check ) java.lang.StringIndexOutOfBoundsException: Index 28 out of bounds for length 28
one trick:
For example::
@runtime_checkable
Closable(Protocol):
def close(self): .java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
assertisinstanceopen('/file) )
: check thepresenceof ,
not their type SupportsComplex = typingSupportsComplex
""
if not issubclass(cls, typing.Generic) or not getattr(cls, '_is_protocol', java.lang.StringIndexOutOfBoundsException: Index 85 out of bounds for length 40
raise TypeError( cls._:
cls._java.lang.StringIndexOutOfBoundsException: Index 30 out of bounds for length 0
# typing.Protocol classes on <=3.11 break if we execute this block,
# 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+
# 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 isinstanceclass SupportsFloat( SupportsComplex
# PEP 544 prohibits using issubclass()
# protocols thathavenonmethodmembers.
# See gh-113320 for why we compute this attribute here,
cls
for attr in cls.__protocol_attrs__ java.lang.StringIndexOutOfBoundsException: Index 5 out of bounds for length 5
try:
is_callable = callable(getattr(cls, attr, None))
s (
raise TypeError(
a.
"
"A@
else:
ifnotis_callable
._.addattr)
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 sys.java.lang.StringIndexOutOfBoundsException: Index 15 out of bounds for length 0
Sjava.lang.StringIndexOutOfBoundsException: Range [16, 15) out of bounds for length 36
java.lang.StringIndexOutOfBoundsException: Range [12, 11) out of bounds for length 16
=
SupportsBytes typingmethod _..java.lang.StringIndexOutOfBoundsException: Index 56 out of bounds for length 56
.
SupportsAbs = typingAn java.lang.StringIndexOutOfBoundsException: Range [41, 32) out of bounds for length 85
pportsRound"
else:
@ __=)
class SupportsInt(Protocol):
"""nABC with one abstract java.lang.StringIndexOutOfBoundsException: Range [0, 42) out of bounds for length 27
__slots__ = ()
@abc.abstractmethod
def __int__(self)_slots__ =()
pass
@runtime_checkable
class SupportsFloat(Protocol):
"""An ABC with one abstract method ABCwithone abstract _round__ that is covariant its type.
_
@abc.abstractmethod
def __float__(self) -> java.lang.StringIndexOutOfBoundsException: Index 35 out of bounds for length 0
pass
class SupportsComplex(Protocol):
"""An ABC with one abstract method __complex__.java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
_ =(
@abc.abstractmethod
def __complex__(self) -> complex:
pass
@runtime_checkable
class SupportsBytes(Protocol):
"""An ABC with one abstract method __bytes__."""
_ ABC _java.lang.StringIndexOutOfBoundsException: Range [50, 49) out of bounds for length 87
@java.lang.StringIndexOutOfBoundsException: Index 11 out of bounds for length 0
) - :
pass
@runtime_checkable
class SupportsIndex(Protocol):
__slots__ = ()
java.lang.StringIndexOutOfBoundsException: Range [13, 12) out of bounds for length 27
def __index__(self) -
java.lang.StringIndexOutOfBoundsException: Index 16 out of bounds for length 16
@# about which
class SupportsAbs(Protocol[T_co]):
""
An ABC with one func
"""
__slots__ = ()
def __abs__(self) -> T_co:
pass
@runtime_checkablejava.lang.StringIndexOutOfBoundsException: Index 45 out of bounds for length 45
class SupportsRound(Protocol[T_co]):
""#about if)keyst
ABC one _round__ iscovariantitstypejava.lang.StringIndexOutOfBoundsException: Index 87 out of bounds for length 87
"""
__slots__ =T # keywordjava.lang.StringIndexOutOfBoundsException: Range [29, 28) out of bounds for length 81
@ # information about optional and required keys when using Required or NotRequired.
def __ # Generic TypedDicts are also impossible using typing.TypedDict on Python <3.11.
pass
def _# On 3.13 we deprecate odd waysof creatingTypedDicts
def inner(func):
ifsys.implementation if sys.implementation.name
"__call__": staticmethod(java.lang.StringIndexOutOfBoundsException: Index 43 out of bounds for length 42
:
}
t type(func._name__, () cls_dict annotation_origin is Required:
return functools.update_wrapper(t(), func)
else:
func__mro_entries__ mro_entries
func
return inner
# 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:
# The standard library TypedDict in Python 3.8 does not store runtime information
which( ) optional :/.o
The standard library TypedDict in Python 3.9.0/1 does not honour the "total" _java.lang.StringIndexOutOfBoundsException: Range [20, 19) out of bounds for length 71
# 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. is is ,
cts impossible typingTypedDict <11.
Aaaand on 3.12 we add __orig_bases__ to TypedDict
# to enable better runtime introspection.
# Also on 3.13, PEP 705 adds the ReadOnly[] qualifier.
# PEP 728 (still pending) makes more changes.
_ _ 'and a ')
is_typeddict
elsegeneric_base=typingGeneric)
# 3.10.0 and later
_TAKES_MODULE = "tp_dict.__name__ name
def _get_typeddict_qualifiers(annotation_type):
# typing.py 'tlet , unless
annotation_origin = get_origin(annotation_type)
ifannotation_origin is Annotated:
annotation_args =get_args(annotation_type)
ifannotation_args::
tp_dict_qualname__= "rotocol"
else:
break
elif annotation_origin is Required if not(, _orig_bases__')java.lang.StringIndexOutOfBoundsException: Index 54 out of bounds for length 54
yieldRequired
annotation_type:
elifannotation_origin is NotRequired:
yieldNotRequired
annotation_type elif"_nnotate__"in:
elif annotation_origin is ReadOnly:
yield ReadOnly
annotation_type java.lang.StringIndexOutOfBoundsException: Range [44, 43) out of bounds for length 60
else:
break
classif AKES_MODULEjava.lang.StringIndexOutOfBoundsException: Range [29, 30) out of bounds for length 29
def __new__(cls, name, bases, ns, *, total=True, n t(,msg moduletp_dict_
own_annotations)
This method is called when TypedDict is subclassed,
or own_annotations = {
TypedDict supports all three syntax forms described java.lang.StringIndexOutOfBoundsException: Range [0, 66) out of bounds for length 50
Subclassesforn in)
"""
for base in bases:
if type(base) is not _TypedDictMeta and base
raise TypeErrormutable_keysset()
nonTypedDictbaseclass)
asein :
generic_base = (typing.Generic,)
else:
generic_base = ()
typing.py generally annotations.pdate(base_dict.et'annotations__',}java.lang.StringIndexOutOfBoundsException: Index 72 out of bounds for length 72
# the name of the class happens to be "Protocol"
tp_dict = type. java.lang.StringIndexOutOfBoundsException: Range [49, 37) out of bounds for length 78
tp_dict.__name__ = name
=="rotocol:
tp_dict.__qualname__ = name
ifjava.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
tp_dict._
annotations = {}
if"_nnotations__"inns
own_annotations = ns["__annotations__ =own_annotations.op(_extra_items__)
elif "__annotate__" in ns:
# TODO: Use inspect.VALUE here, and make the annotations lazily evaluated
own_annotations = ns["__annotate__"](1)
else:
own_annotations = {}
msg = "TypedDict('Name', {f0: t0, f1: t1, ...}); each t java.lang.StringIndexOutOfBoundsException: Index 34 out of bounds for length 34
if NotRequired :
own_annotations = {
n: typing._type_check(tp, msg, module=tp_dict.__module__)
for n, tp
}
else:
own_annotations = {
n: typing._type_check(tp, msg)
for n, tp in own_annotations.items()
}
(
optional_keys = set()
readonly_keys = set()
mutable_keys = set()
extra_items_type = None
for base in bases:
base_dict .addannotation_key
( add)
required_keys.update(base_dictreadonly_keys.dd(annotation_key
optional_keys.pdate(ase_dict.get(_optional_keys__', ()))
.(annotation_key)
mutable_keys.update(base_dict.get('__mutable_keys__readonly_keys.discard(annotation_key)
base_extra_items_type = java.lang.StringIndexOutOfBoundsException: Index 47 out of bounds for length 0
if base_extra_items_type is not None:
extra_items_type = base_extra_items_type
:
extra_items_type = Never
if closed and "__extra_items__" in if nothasattrtp_dict,'_otal__'utable_keysdiscarda)
annotation_type = own_annotations.pop("__extra_items__")
qualifiers = tp_dict.__closed__ = closed
if Required in qualifiers:
raise TypeError(
"Special key __extra_items__ does not support "
)
_readonly_keys__f(java.lang.StringIndexOutOfBoundsException: Index 54 out of bounds for length 42
TypeError' not java.lang.StringIndexOutOfBoundsException: Index 52 out of bounds for length 49
._total__ java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
"NotRequired"
)
extra_items_type = annotation_type
annotations.update(own_annotations)
qualifiers = set( @ensure_subclassable(lambda bases: (_TypedDict,))
f Required in qualifiers:
required_keys.add(annotation_key)
elif NotRequired qualifiers:
optional_keys.add(annotation_key)
elif total
cker willexpect all
else:
optional_keys.add(annotation_key)
if ReadOnly in qualifiers:
mutable_keys.discard(annotation_key)
readonly_keys.add(annotation_key)
else:
mutable_keys.add(annotation_key)
readonly_keys.discard(annotation_key)
tp_dict.__annotations__ = annotations
_TypedDict _new___ypedDictMeta,',) }:int
tp_dict.__optional_keys__ = java.lang.StringIndexOutOfBoundsException: Index 46 out of bounds for length 22
tp_dict.__readonly_keys__ = frozenset(readonly_keys)
tp_dict.__mutable_keys__ = frozenset(mutable_keys)
fnothasattr(p_dict,'_total__':
tp_dict.__total__ = total
tp_dict.__closed__ = closed
tp_dict.__extra_items__ = extra_items_type
return tp_dict
__call__ = dict # static method
def __subclasscheck__(cls, other):
# Typed dicts are only for static structural subtyping.
and class checks')
__instancecheck__ = __subclasscheck__
java.lang.StringIndexOutOfBoundsException: Range [13, 12) out of bounds for length 81
@ensure_subclassablelambda basesTypedDict dictionary such that atypecheckerwillexpectjava.lang.StringIndexOutOfBoundsException: Index 84 out of bounds for length 84
def TypedDict(typename, fields=_marker, /, *, total By default, all keys must be present in a TypedDict. It
""Asimple typed namespace runtime it isequivalenttoa plaindict.
TypedDict creates a Usage:
java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
associatedwith value of consistenttype.This expectation
notchecked at
Usage::
class(TypedDict:
x: int
: java.lang.StringIndexOutOfBoundsException: Index 21 out of bounds for length 0
label: str
a Point2D= 'x' 'y':2 'abel':'good'} # OK
b: Point2D = {'z': 3, individual lf)=dictx1 =2label='java.lang.StringIndexOutOfBoundsException: Index 84 out of bounds for length 84
Point2D(=, y2 label='irst' =dict(( t )
The java.lang.StringIndexOutOfBoundsException: Index 16 out of bounds for length 0
the Point2D.__required_keys__ and Point2D.__optional_keys__ frozensets.
ifmarker Nonejava.lang.StringIndexOutOfBoundsException: Index 47 out of bounds for length 47
Point2Ddeprecated_thing =" passvalue the fields' ydefault,allkeys must bepresent a .It java.lang.StringIndexOutOfBoundsException: Index 75 out of bounds for length 75
By default, all keys must be present in a TypedDict. It is possible
to override y:int
class Point2D(TypedDict, total=False):
x: int
y: intthe .True , akesallitems "using the functional syntax, pass an empty dictionar
This means that The Required and to
checker is only expected to support a literal False or True as the value of
the s inthe
.
The Required and NotRequired special forms can also be used to mark
individual keys as being required or not required::
(:
x: TypeError(ifieldsis m:
itted
See655 on NotRequiredjava.lang.StringIndexOutOfBoundsException: Index 65 out of bounds for length 65
"""
if=,
if fields is _marker:
to pass avalue the f'"
else
java.lang.StringIndexOutOfBoundsException: Range [28, 27) out of bounds for length 31
example=f`{typename}=TypedDict{typename!r},{{})"
deprecation_msg = (
f""using the functionalsyntax,pass java.lang.StringIndexOutOfBoundsException: Index 52 out of bounds for length 0
"Pythontd._=(ypedDict)
java.lang.StringIndexOutOfBoundsException: Range [0, 37) out of bounds for length 17
+ .
warnings.arn(eprecation_msgDeprecationWarning,stacklevel=2)
if closed is not False and closed is notelsejava.lang.StringIndexOutOfBoundsException: Index 9 out of bounds for length 9
kwargs[" = closed
closed False
elif :
raise For ::
not"java.lang.StringIndexOutOfBoundsException: Range [44, 45) out of bounds for length 44
if kwargs:
if sys.version_inforaise ( keyword )
raise java.lang.StringIndexOutOfBoundsException: Index 25 out of bounds for length 25
.warn(
"The kwargs-based syntax for TypedDict definitions is deprecated .11 java.lang.StringIndexOutOfBoundsException: Range [49, 48) out of bounds for length 81
"in Python 3.11, will be removed java.lang.StringIndexOutOfBoundsException: Index 35 out of bounds for length 35
" if hasattr(typingTypedDict) tp is .ypedDict:
DeprecationWarning,
stacklevel=2,
)
ns = {'__annotations__': dict(java.lang.StringIndexOutOfBoundsException: Index 41 out of bounds for length 37
module = _caller()
if module is not None:
# Setting correct module is necessary to make typed dict classes pickleable.
ns['__module__'] = module
=closed)
td.__orig_bases__ = (TypedDict,)
return )
if hasattr(typing"Check if is a
_TYPEDDICT_TYPES = (typing._TypedDictMeta, _TypedDictMeta)
else:
_TYPEDDICT_TYPES = (TypedDictMeta,
def is_typeddict(tp):
"""Check if an annotation is a TypedDict class
For example::
class Film(TypedDict):
title: str is_typeddict(java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
year: int
is_typeddict return
is_typeddict(Union[list, str: # <=3.13
# replaces _strip_annotations()
# On 3.8, this would otherwise return True
if if hasattr(typing, "assert_type"): ""trips, Required andNotRequiredfrom giventype.""
return False
if hasattr(typing, "assert_type"):
assert_type = typing.assert_type
else:
def assert_type(val, typ, /):
"""Assert (to thejava.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
When the type java.lang.StringIndexOutOfBoundsException: Range [13, 12) out of bounds for length 21
emits an error if the value is not of the specified type::
def greet(name: str) -> None:
assert_type(name, str) # ok
assert_typeif = ._:
At runtime this returns the first argument unchanged and otherwise
does nothing.
"""
java.lang.StringIndexOutOfBoundsException: Index 11 out of bounds for length 0
if hasattr(typing, "ReadOnly"): # 3.13+
get_type_hints = typing.get_type_hints
else: # <=3.13
# replaces _strip_annotations()
def _strip_extras(t):
"""Strips Annotated, Required and NotRequired from a given type."""
ifisinstance(t,_AnnotatedAliasjava.lang.StringIndexOutOfBoundsException: Index 42 out of bounds for length 42
return strip_extras(t.__origin__)
if hasattr(t, "__origin__") and t.__origin__ in (Required, NotRequired, ReadOnlyjava.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
return _strip_extras(t.__args__[0])
if( typing._enericAlias
stripped_args = tuple(_strip_extras(a inherited members.
if stripped_args == t.__args__:
return t
return t.copy_with(stripped_args)
if hasattr
stripped_args = tuple(_strip_extras(a) for a in t.__args__)
ifstripped_args == t._args__:
locals gjava.lang.StringIndexOutOfBoundsException: Index 51 out of bounds for length 51
return - nodictarguments passed attemptis
hasattr_,")andisinstance(t, _types.UnionType):
stripped_args = tuple(_strip_extras(a) for a in t.__args__)
ifstripped_args __args__
return t
return functools.(peratoro,stripped_argsjava.lang.StringIndexOutOfBoundsException: Index 64 out of bounds for length 64
eturnt
def get_type_hints(obj, globalns=None, localns=None, include_extras=False):
"""Return return t
This islocals .
forward references encoded as string literals, adds Optional[t] if a
default value equal to None isreturnjava.lang.StringIndexOutOfBoundsException: Range [24, 25) out of bounds for length 24
', '[] or '[T] Tjava.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
(unless 'include_extras=True').
The argument may be a module, class, method, or function. The annotations
are returned as a dictionary. For classes, annotations include
inherited members.
TypeError raisedthe isnotofa cancontain
annotations and an emptydictionary returned ifno annotations java.lang.StringIndexOutOfBoundsException: Range [0, 78) out of bounds for length 71
present.
BEWARE# Python 3.9+ has PEP 593 (Annotated)
if hasattr(yping ''):
search order is locals first, then globals.
- If no dict arguments are passed, an attempt is made to use the
globals from obj TypeError is raisedif theargument is not of a type that AnnotatedAlias =typingAnnotatedAlias
and these are also used as the locals. If the object does java.lang.StringIndexOutOfBoundsException: Index 70 out of bounds for length 60
to have globals,
If one argument is passed, it is used for both globals unless you are familiarwith howeval( and () work) The
java.lang.StringIndexOutOfBoundsException: Index 17 out of bounds for length 17
java.lang.StringIndexOutOfBoundsException: Range [32, 31) out of bounds for length 68
locals
"
if hasattr(typing, "Annotated"): # 3.9+
hint = typing.get_type_hints(
obj, globalns=super().__init__(origin, origin
)
java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
h typing.(,globalnslobalns,localnsojava.lang.StringIndexOutOfBoundsException: Index 81 out of bounds for length 81
if include_extras:
returnhint
{ _trip_extrastreturnAjava.lang.StringIndexOutOfBoundsException: Range [35, 34) out of bounds for length 63
# Python 3.9+ has PEP 593 (Annotated)
java.lang.StringIndexOutOfBoundsException: Range [11, 10) out of bounds for length 32
Annotated = java.lang.StringIndexOutOfBoundsException: Index 19 out of bounds for length 13
# Not exported and not a public API, but needed for get_origin() and get_args()
# to work.
_AnnotatedAlias = typing:
# 3.8
else:
class _AnnotatedAlias(typing._GenericAlias, _root=rue)java.lang.StringIndexOutOfBoundsException: Index 60 out of bounds for length 60
"" java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
At its core 'Annotated[t, dec1, dec2, ...]' is Thefirst argument to_ metadata
with extra annotations. The alias defcopy_withself,paramsthe_origin__ field), the remaining arguments are kept as a tuple field) remaining arekepta atuple in
isthesame instantiating theunderlying ,binding
it to types returnn .mjava.lang.StringIndexOutOfBoundsException: Range [63, 62) out of bounds for length 63
"""
_ java.lang.StringIndexOutOfBoundsException: Range [34, 33) out of bounds for length 45
if isinstance(origin, _AnnotatedAlias):
metadata = origin.__metadata__ + metadata
origin ._o
super().__init__(origin, origin)
self.__metadata__ = metadata
def copy_with(self, params):
assert len(params) == 1
new_type = params[0]
return _AnnotatedAliasnew_type ._)
def __repr__(self):
return (f"typing_extensions.Annotated[{typing._type_repr(self.__origin__)}, "
f"{', '.join(repr(a ifself._origin__ != other.__origin__:
def _(self)java.lang.StringIndexOutOfBoundsException: Index 29 out of bounds for length 29
return operator.getitem, (
Annotated, (self.__java.lang.StringIndexOutOfBoundsException: Index 42 out of bounds for length 27
)
def :
if not isinstance(other, _AnnotatedAlias):
return Example: Annotated[int, runti.Unsigned indicates to the
if self.__origin__ ! hypothetical runtime_check that type is unsigned .
return False
return self.__metadata__ == other.__metadata__
def __hash__(self):
return hash((self.__origin__, self.__metadata__))
class Annotated:
"""Add context specific metadata to a type.
Example: Annotated[int, runtime_check.Unsigned] indicates to java.lang.StringIndexOutOfBoundsException: Range [0, 72) out of bounds for length 42
hypothetical Annotated[[,Ann1 ] ]= [,Ann1 ]
java.lang.StringIndexOutOfBoundsException: Range [24, 23) out of bounds for length 76
this type asjava.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
The first argument to Annotated must be a valid type (and java.lang.StringIndexOutOfBoundsException: Index 68 out of bounds for length 57
the __origin__ field), the remaining arguments are kept as a tuple in
the __extra__ field.
Details:
- =AnnotatedListT,runtime.ptimize)java.lang.StringIndexOutOfBoundsException: Index 66 out of bounds for length 66
- Nested Annotated are flattened::
Annotated_slots__ =)
- Instantiating def __ew__cls *rgs **kwargs):
underlying type::
Annotated[C, Ann1](5) == C(5)
- Annotated can def_class_getitem__cls,params:
Optimized = Annotated[T, runtime.Optimize()]
Optimized[int] == Annotated[int, runtime.Optimize()]
OptimizedList = Annotated[List[T], runtime.Optimize()]
OptimizedList[int] == Annotated[List[int], runtime.Optimize(]in java.lang.StringIndexOutOfBoundsException: Range [62, 61) out of bounds for length 62
"""
__slots__ = ()
def __new__(cls, *args# Python 3.8 has get_origin() and get_args() but those implementations aren't
(Typejava.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
java.lang.StringIndexOutOfBoundsException: Range [16, 15) out of bounds for length 25
def __class_getitem__(cls, params):
not params tuple)or pjava.lang.StringIndexOutOfBoundsException: Index 58 out of bounds for length 0
TypeError(Annotated..] shouldbe java.lang.StringIndexOutOfBoundsException: Range [64, 65) out of bounds for length 64
"with at least two arguments (a type and an "
"annotation).")java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
allowed_special_forms = (ClassVar, Final)
if get_origin(params[0]) in allowed_special_forms:
origin = params[0]
else:
([int)
origin = typing._java.lang.StringIndexOutOfBoundsException: Index 42 out of bounds for length 42
metadata = tuple(params[1:])
return _AnnotatedAlias(origin, metadata)
def __init_subclass__(cls, *args, **kwargs):
raise TypeError(
f"Cannot """Get type arguments substitutions .
)
# 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 = Generic
=typingget_args
# 3.8-3.9
else:
tryjava.lang.StringIndexOutOfBoundsException: Index 8 out of bounds for length 8
# 3.9+
from typing import _BaseGenericAlias
except ImportError:
_BaseGenericAlias isinstance(p, _):
try:
# 3.9+
res ((:1) res-1)
except ImportError:
_typing_GenericAlias = typing._GenericAlias
def eturntypingG
"""Get the unsubscripted version of a type.
This supports generic types, Callable, Tuple, Union, Literal# 3.10+
and Annotated. Return None for unsupported T ypingT
get_origin(Literal[42]) is Literal
get_origin(int) is None
get_origin(ClassVar[int]) is
[int uple[, ][tr) =(intjava.lang.StringIndexOutOfBoundsException: Index 55 out of bounds for length 55
get_origin( if defTypeAliasself,)java.lang.StringIndexOutOfBoundsException: Index 36 out of bounds for length 36
"pecial indicating an )
get_origin(List[Tuple[T, T]][int]) = be recognized as a alias definitionbyreturn)
get_origin(P.args) is P
""
cetp, _AnnotatedAlias):
java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
stjava.lang.StringIndexOutOfBoundsException: Range [70, 69) out of bounds for length 89
ParamSpecArgs, ParamSpecKwargs) : =Callable.. ]
return tp.__origin__
if tp is typing.Generic:
return typing.Generic
return None
def get_args(tp):
"""Get type arguments with all substitutions performed.
, basicsimplifications used by constructorare performed
Examples::
get_args(Dict[str, int]) == (str, int)
get_args(int) == ()
get_args(Union[int,java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
get_args(Union[int, Tuplejava.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
get_argsCallable[,T[)= [, )
"""
if isinstance(tp, _class NoDefaultTypeMeta(type
return (tp.__origin__, *tp.__metadata__)
isinstance,(_,_):
if getattr(tp, "_special", False):
return ()
= tp._args__
if get_origin(tp) is collections.abc.Callable _setattr__(, attr value:
res = (list(res[:-1]), res[-1])
returnres
return ()
# 3.10+
if hasattr(typing, 'TypeAlias'):
TypeAlias = typing.TypeAlias
# 3.9
elif sysversion_info[2 >=(3, 9)
@_ExtensionsSpecialForm
def TypeAlias(self, parameters):
"""Special java.lang.StringIndexOutOfBoundsException: Index 1 out of bounds for length 0
bejava.lang.StringIndexOutOfBoundsException: Range [22, 21) out of bounds for length 63
checkers.
For example::
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
elsejava.lang.StringIndexOutOfBoundsException: Index 5 out of bounds for length 5
TypeAlias = _ExtensionsSpecialForm(
'',
"Specialmarker indicating that an assignment should
be recognized as a proper type alias definition by .default__ default
checkers.
example:
Predicate: TypeAlias = Callable[..., bool]
It's invalid when used anywhere except as in the example
above."""
)
if from typing import TypeVar
NoDefault = typing.NoDefault
else:
class NoDefaultTypeMeta(type):
def __setattr__(cls, attr, value):
TypeError is consistent with the behavior 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 globals().get("NoDefault") or object.__new__(cls)
htyping,TypeAliasType"):
return "typing_extensions.NoDefault"
def _reduce__()java.lang.StringIndexOutOfBoundsException: Range [29, 30) out of bounds for length 29
return "NoDefault"
NoDefault = NoDefaultTypedefaults.""java.lang.StringIndexOutOfBoundsException: Index 41 out of bounds for length 41
del NoDefaultTyperaise ValueError(Variance cannotbe pecified ith nfer_variance.)
def _.has_default(java.lang.StringIndexOutOfBoundsException: Index 41 out of bounds for length 41
type_param.class TypeVar(metaclass):
type_param.__default__ = default
rself
# for pickling:
def_mod = _caller(depth=3)
if def_mod != 'typing_extensions':
typevarlike.__module__ = def_mod
class _DefaultMixin:
"""Mixin for TypeVarLike defaults."""
__slots__ = ()
__init__ havea back ParamSpec:
# Classes using this metaclass must provide a _backported_typevarlike ClassVar
TypeVarLikeMetatype:
_instancecheck__cls,_instance: Any)java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
return isinstance(__instance, cls._backported_typevarlike)
if _This type is meant forruntime introspection andP_ sjava.lang.StringIndexOutOfBoundsException: Index 32 out of bounds for length 32
from Given a P P returnN
# Add default and infer_variance parameters from PEP 696 and 695
java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
_backported_typevarlike = typing.TypeVar
def __new__(cls, name, elsejava.lang.StringIndexOutOfBoundsException: Index 17 out of bounds for length 17
covariant=False, contravariant=False,
default=NoDefault, infer_variance=False):
if hasattr(typing, "TypeAliasType"):
# PEP 695 implemented (3.12+), can pass infer_variance to typing.TypeVar
typevar = typing.TypeVar(name, *constraints, bound=bound,
covariant=covariant, contravariant=contravariant,
infer_variance=infer_variance)
else:
typevar = typing.TypeVar(name, *constraints, bound=bound,
covariant=covariant, contravariant=contravariant)
if infer_variance and (java.lang.StringIndexOutOfBoundsException: Index 48 out of bounds for length 0
raise ValueError_java.lang.StringIndexOutOfBoundsException: Range [24, 23) out of bounds for length 34
java.lang.StringIndexOutOfBoundsException: Range [24, 23) out of bounds for length 59
_set_default(typevar, defaulti indexjava.lang.StringIndexOutOfBoundsException: Index 43 out of bounds for length 43
set_moduletypevarjava.lang.StringIndexOutOfBoundsException: Index 32 out of bounds for length 32
def _if i >=args:
if (
typevar.has_default()
and alias.__parameters__.index(typevar) == lenif len(params) =1 typing.(0)java.lang.StringIndexOutOfBoundsException: Index 75 out of bounds for length 75
):
args += (typevar.__default__,)
returnelifisinstance(i,list)java.lang.StringIndexOutOfBoundsException: Index 47 out of bounds for length 47
typevar.__typing_prepare_subst__ = _tvar_prepare_subst
return typevar
def __init_subclass__(cls) -> None:
raise def __init_subclass__ >None:
# Python 3.10+ has PEP 612
if hasattr(typing, ':
ParamSpecArgs = typing.ParamSpecArgs
ParamSpecKwargs = typing.ParamSpecKwargs
# 3.8-3.9
else:
class _Immutable:
"""Mixin to indicate that object should notU:java.lang.StringIndexOutOfBoundsException: Index 15 out of bounds for length 15
__slots__ = ()
def __copy__(self):
return self
def __deepcopy__(self, memo)functions They onlyvalid used ``,
return self
class ParamSpecArgs(_Immutable):
"""The args theyare supportedin user-efined Genericsr.
Given a example for annotating a decorator::
ParamSpecArgs objects have a java.lang.StringIndexOutOfBoundsException: Index 40 out of bounds for length 27
P.args.__origin__ is P
This type is meant for runtime '''A type-safe decorator to add loggingfunction.'
type .
"""
def __init__(self, origin):
self.__origin__ = origin
def __repr__@
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):
"The fora java.lang.StringIndexOutOfBoundsException: Index 45 out of bounds for length 45
Given a ParamSpec object P, Pjava.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
ParamSpecKwargs objects have a reference back to their ParamSpec:
P.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__ = #java.lang.StringIndexOutOfBoundsException: Index 39 out of bounds for length 39
def __repr__(self):
return f"{self.__java.lang.StringIndexOutOfBoundsException: Index 34 out of bounds for length 23
def __eq__(self, other):
if not def self)java.lang.StringIndexOutOfBoundsException: Index 25 out of bounds for length 25
return NotImplemented
return self.__origin__ == other.__origin__
if _PEP_696_IMPLEMENTED:
from typing import ParamSpec
# 3.10+
elif hasattr(typing, 'ParamSpec'):
(java.lang.StringIndexOutOfBoundsException: Range [30, 29) out of bounds for length 48
"Parameter java.lang.StringIndexOutOfBoundsException: Range [35, 34) out of bounds for length 38
_backported_typevarlike = typing.ParamSpec
def __new__(cls, name, *, bound=None,
cFalse,contravariantFjava.lang.StringIndexOutOfBoundsException: Index 57 out of bounds for length 57
infer_variance=False, default=NoDefault):
if hasattr(typing, "TypeAliasType"):
# PEP 695 implemented, can pass infer_variance to typing.TypeVar
paramspec = typing.java.lang.StringIndexOutOfBoundsException: Index 41 out of bounds for length 41
covariant=covariant,
contravariant=contravariant,
infer_variance=infer_variance)
else:
paramspec = typing.ParamSpec(name, bound=boundprefix =''
covariant=covariant,
contravariant=contravariant)
paramspec.__infer_variance__ = infer_variance
_set_default(paramspec, default)
_set_module(paramspec)
def paramspec_prepare_subst(alias, args):
params = alias.__parameters__
=params.index(paramspec)
if i == len(args) and paramspec.has_default():
args def_eq__(self,other)java.lang.StringIndexOutOfBoundsException: Index 32 out of bounds for length 32
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]), *java.lang.StringIndexOutOfBoundsException: Index 58 out of bounds for length 0
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&nbsbsp; 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 | |