U vinr@sddlZddlZddlZddlZddlZddlZddlZddlZddlZddl Z ddl Z ddl Z ddl Z ddlZdddddddd d d d d ddddddddddddddddddd d!d"d#d$d%d&d'd(d)d*d+d,d-d.d/d0d1d2d3d4d5d6d7d8d9d:d;dd?d@dAdBdCdDdEdFdGdHdIdJdKdLdMdNdOdPdQdRdSdTdUdVdWdXdYdZd[d\d]d^d_d`dadbdcdddedfdgdhdidjdkdldmdndodpdqdrdsgrZdtZeZe jdukZdve jjkZGdwdxdxZeZe jdykrdzd{Zne jd|krd}d{Znd~d{Ze jZe dZe dZe dZe jddtdZ e jddtdZ!e jdkrddl m"Z"n"GdddeZ#Gddde#dZ"e j$Z$Gddde j%dtdZ&e j'Z'e jdkrpe j(Z(ndd.Z(dd6Z)e jdkre j*Z*nDddZ+ddZ,Gddde j-dtdZ.Gddde&dtdZ/e/ddZ*e j0Z0e1e d-re j2Z2e j3Z3e j4Z4n,e5e6ej5e7Z8dd;Z2dd-Z3dd(Z4e j9Z9e j:Z:e j;Z;e jZ>e j?Z?e j@Z@e jAZAe jBZBe jCZCe jDZDe jdukrddl mEZEmFZFmGZGmHZHnddZIeJe de j-ZKGdddeKdtdZLedZMeLejjHdeMeMfdZHeLejjFdeMfdZFeLejNdde jOePfdZGeLejQdde jOePfdZEdRdd]d^ddZdldTdSdidg ddgdgdZReSe jTddddhBZUddZVdddZWe jdkre jXZXnTdddZYddZZddZ[Gdddee jXZ\e]ddZ^Gdd=d=e j_e\dZXe jdkre j`Z`ndd@Z`e`Zae jdkr:e jbZbe jcZce jdZde jeZee jfZfe jgZge jhZhne`Gdd#d#eXZbe`Gdd!d!eXZce`Gdd d eXZde`GdddeXZee`Gdd"d"eXZfe`GdddeXe Zge`Gdd$d$eXe ZhddɄZie1e dM pe1e dN ZjejrGdd˄deZke1e dMre jlZlnGdd̈́dekdZmemZl[me1e dNrHe jnZnnGddτdekdZoeoZn[oejrj[kdZpepre jqZqe jrZre jsZsndete jujvkZwddӄZxGddՄdeZreyerddiZzeidd؄efdtdendٜddZqe1e dՃre jrerfZ{nerfZ{dd8Zse1e d're j|Z|ndd'Z|e1e dJr:e j}Z}n0ddބZ~ddd5Z}edZMddZdddZe1e d%re jZe jZn$Gddde j-dtdZGdd%d%Ze jdddykre jZe jZnlzddl mZWnek re j-ZYnXzddl mZWnek r$e j-ZYnXdd2Zdd1Ze1e dBrJe jZn.e jddd|krle&ddBZn e&dBddZddZddZGdddZGdddeZerddl mZnGdd d edZe1e dre jZe jZn.GdddZGdddeZGdd d eZe r(ddl mZn2e1e d rHGdddedZnGdddeeZe1e d se1e d sdddddZne jZGdddeZn.e jZe jdk rGddde jdtdZGdddZddZe jdd Ze jdk re jZnLe jddd|k r>e&d dZn(Gd d d e&dtdZedd dZe1e dE rze jZnLe jddd|k re&ddEZn(Gddde&dtdZedEddZe1e dF re jZnLe jddd|k re&ddFZn(Gddde&dtdZedFddZe1e dD r:e jZnfe jddd|k rxGddde&dtdZeddDZn(Gddde&dtdZedDddZGddde jdtdZ%e1e d re jZne%ddZe1e d  re jZne%dd Ze1e dH re jZne%ddHZe1e dK rrHe jZneed<d=d>Ze1e d>rre jZnd?Ze1e d&re jZneed@dAd&Ze jdkre jZnhdtdddd֐dBePePePePe je je j9e j"e jdCe j"ffdCfe j"e jegefdDdEd)Ze1e d<r0e jZn4e jdFe jdCe j"fdGZeed@dHd<Ze jdIkrzejZne dJZGdKd*d*Ze jdykrdLdMZn dNdMZe1e d sefdOdPZn dQdPZesee _ePdRdSdTZeeJe d dhZePdRdUdVZe1e dWrPddXdWZee _ndYdZZeshee _e jdkr|e jZnrdd[d\Ze jZeSd]d^d_hZGd`dadaeZeyeddiZʐdbdcZeie˃efdddZe1ejdrejjZn2Gdeddej̓Ze̠eϡe̠eСe̠eѡe1e d3rLe jZn dfd3Ze jdkrje jZnGdgd:d:Ze jdhkre jZne jdkrdidjZn dkdjZe jdykreSdldmdndodpdqdrdsdtdudvdwh ZGdxdydye j-dtdZGdzdCdCZe1e d7r@e jZe jZn.eePd{d|d7Zee jed{d}d4Ze1e d+re jZnGd~d+d+ZeJe ddZedkrz ddlZWnek rYn"XeJeސddZedk ree߃Zedk reZede1ed0o.ejjdk o.dejjkZGdd/d/ejZerRejZndddejddd0Ze1e d,re jZnTdddddddZdddАdddZddddejeSddd,Ze jZe jZe jZe jZe jZe jZe jZe jZe jZe j_Z_e jZe jZe jZe jZe jZe jZe jZe jZe jZe jZe jZe jZe jZe jOZOe jZe jZe jZe jZe jZe jZe jZe jZe jZe jZe jZe jZdS(NAnyClassVar ConcatenateFinal LiteralString ParamSpec ParamSpecArgsParamSpecKwargsSelfTypeTypeVar TypeVarTupleUnpack Awaitable AsyncIterator AsyncIterable CoroutineAsyncGeneratorAsyncContextManagerBufferChainMapContextManagerCounterDeque DefaultDict NamedTuple OrderedDict TypedDict SupportsAbs SupportsBytesSupportsComplex SupportsFloat SupportsIndex SupportsInt SupportsRound Annotated assert_never assert_typeclear_overloadsdataclass_transform deprecatedDocevaluate_forward_ref get_overloadsfinalFormatget_annotationsget_args get_originget_original_basesget_protocol_membersget_type_hintsIntVar is_protocol is_typeddictLiteralNewTypeoverloadoverrideProtocol reveal_typeruntimeruntime_checkableText TypeAlias TypeAliasTypeTypeForm TypeGuardTypeIs TYPE_CHECKINGNeverNoReturnReadOnlyRequired NotRequired NoDefault NoExtraItems AbstractSetAnyStrBinaryIOCallable Collection ContainerDict ForwardRef FrozenSet GeneratorGenericHashableIO ItemsViewIterableIteratorKeysViewListMapping MappingViewMatchMutableMappingMutableSequence MutableSetOptionalPattern ReversibleSequenceSetSizedTextIOTupleUnion ValuesViewcast no_type_checkno_type_check_decoratorT) rbeta__forward_is_class__c@seZdZddZdS) _SentinelcCsdS)Nz selfryryB/opt/alt/python38/lib/python3.8/site-packages/typing_extensions.py__repr__sz_Sentinel.__repr__N__name__ __module__ __qualname__r}ryryryr|rxsrxrt cCst|tjtjtjfSN) isinstancetyping _GenericAlias_types GenericAlias UnionTypetryryr|_should_collect_from_parameterssrrt cCst|tjtjfSr)rrrrrrryryr|rscCst|tjo|j Sr)rrr_specialrryryr|rsTKTVTT_co) covariantT_contra) contravariantrt )rcs(eZdZfddZfddZZS)_AnyMetacs|tkrtdt|S)Nz6typing_extensions.Any cannot be used with isinstance())r TypeErrorsuper__instancecheck__r{obj __class__ryr|rsz_AnyMeta.__instancecheck__cs|tkr dStS)Nztyping_extensions.Any)rrr}rzrryr|r}sz_AnyMeta.__repr__)rrrrr} __classcell__ryryrr|rs rcs eZdZdZfddZZS)raqSpecial type indicating an unconstrained type. - Any is compatible with every type. - Any assumed to have all methods. - All values assumed to be instances of Any. Note that all the above statements are true from the point of view of static type checkers. At runtime, Any should not be used with instance checks. cs$|tkrtdtj|f||S)NzAny cannot be instantiated)rrr__new__clsargskwargsrryr|rsz Any.__new__)rrr__doc__rrryryrr|rs) metaclassc@seZdZddZdS)_ExtensionsSpecialFormcCs d|jSNztyping_extensions._namerzryryr|r}sz_ExtensionsSpecialForm.__repr__Nr~ryryryr|rsr)_rootc Cs(z d|_Wnttfk r"YnX|S)aThis decorator can be used to indicate to type checkers that the decorated method cannot be overridden, and decorated class cannot be subclassed. For example: class Base: @final def done(self) -> None: ... class Sub(Base): def done(self) -> None: # Error reported by type checker ... @final class Leaf: ... class Other(Leaf): # Error reported by type checker ... There is no runtime checking of these properties. The decorator sets the ``__final__`` attribute to ``True`` on the decorated object to allow runtime introspection. T) __final__AttributeErrorr)fryryr|r.s  cCs t|Sr)rr nameryryr|r6 s)rtrcCs8g}|D]&}t|tr$||jq||qt|S)zJAn internal helper for Literal creation: flatten Literals among parameters)r_LiteralGenericAliasextend__args__appendtuple) parametersparamspryryr|_flatten_literal_paramss   rccs|D]}|t|fVqdSr)type)rrryryr|_value_and_type_itersrc@seZdZddZddZdS)rcCs2t|tstStt|j}tt|j}||kSr)rrNotImplementedsetrr)r{otherZthese_args_dedupedZother_args_dedupedryryr|__eq__!s  z_LiteralGenericAlias.__eq__cCsttt|jSr)hash frozensetrrrzryryr|__hash__(sz_LiteralGenericAlias.__hash__N)rrrrrryryryr|r src@s"eZdZedddZddZdS) _LiteralFormdoccCsd|_||_|_dS)Nr9)r_docr)r{rryryr|__init__,sz_LiteralForm.__init__cCst|ts|f}t|}tt|}z t|}Wntk rDYnTXt|t|krg}|D]$}||kr^||d| |q^|rt |t|}t ||SNr) rrrlistrrrlenrremoveAssertionErrorr)r{rZval_type_pairsZ deduped_pairsZnew_parameterspairryryr| __getitem__0s"     z_LiteralForm.__getitem__N)rrrstrrrryryryr|r+sra A type that can be used to indicate to type checkers that the corresponding value has a value literally equivalent to the provided parameter. For example: var: Literal[4] = 4 The type checker understands that 'var' is literally equal to the value 4 and no other value. Literal[...] cannot be subclassed. There is no runtime checking verifying that the parameter is actually a value instead of a type.rcCsBt|d|}z|t|j|j|jj<Wntk r<YnXtS)aDecorator for overloaded functions/methods. In a stub file, place two or more stub definitions for the same function in a row, each decorated with @overload. For example: @overload def utf8(value: None) -> None: ... @overload def utf8(value: bytes) -> bytes: ... @overload def utf8(value: str) -> bytes: ... In a non-stub file (i.e. a regular .py file), do the same but follow it with an implementation. The implementation should *not* be decorated with @overload. For example: @overload def utf8(value: None) -> None: ... @overload def utf8(value: bytes) -> bytes: ... @overload def utf8(value: str) -> bytes: ... def utf8(value): # implementation goes here The overloads for a function can be retrieved at runtime using the get_overloads() function. __func__)getattr_overload_registryrr__code__co_firstlinenor_overload_dummy)funcrryryr|r;es cCsDt|d|}|jtkrgSt|j}|j|kr2gSt||jS)z6Return all defined overloads for *func* as a sequence.r)rrrrrvalues)rrmod_dictryryr|r-s    cCs tdS)z$Clear all overloads in the registry.N)rclearryryryr|r(s)rrrrXcCs|do|dS)N__) startswithendswith)attrryryr| _is_dundersr_SpecialGenericAliascs<eZdZddddfdd ZddZejd d ZZS) rTNry)instrdefaultscsLttjkr.||_||_tj||d||dntj||||d||_dS)NT)specialrr)rr)_special_generic_alias_baserr __origin___nparamsrr _defaults)r{originZnparamsrrrrryr|rs  z_SpecialGenericAlias.__init__cCsRddddh}ttjkr |dt|s0||kr@t|||nt|j||dS)Nr_instrrr) rrraddrobject __setattr__setattrr)r{rvalZ allowed_attrsryryr|rs    z _SpecialGenericAlias.__setattr__c st|ts|f}dtfdd|D}|jrrt||jkrrt|t|j|jkrr||jt||jd}t|}||jkr|jrd|jt|j}n t|j}|jst|dtd||jkrdndd |d |d |||S) Nz*Parameters to generic types must be types.c3s|]}t|VqdSrr _type_check.0rmsgryr| sz3_SpecialGenericAlias.__getitem__.. at least  is not a generic classToo manyfew arguments for ; actual , expected )rrrrrrr copy_with)r{rZ actual_lenexpectedryrr|rs,    (z _SpecialGenericAlias.__getitem__) rrrrrr _tp_cacherrryryrr|rs  rt)r)rrAbstractContextManagerAbstractAsyncContextManager)zcollections.abc contextlibtyping_extensionsZ__match_args____protocol_attrs____non_callable_proto_members__rcCsbt}|jddD]H}|jdkr$qt|di}|j|D] }|ds:|tkr:||q:q|S)N>rYr=__annotations___abc_)r__mro__rr__dict__r_EXCLUDED_ATTRSr)rattrsbase annotationsrryryr|_get_protocol_attrss  rc Cs6zt|jddWSttfk r0YdSXdS)Nr__main__)sys _getframe f_globalsgetr ValueErrordepthryryr|_callersrrtrucCs t|dkS)zAllow instance and class checks for special stdlib modules. The abc and functools modules indiscriminately call isinstance() and issubclass() on the whole MRO of a user class, which may contain protocols. >abc functoolsN)rrryryr|_allow_reckless_class_checks)sr!cOst|jrtddS)Nz Protocols cannot be instantiated)r _is_protocolrr{rrryryr|_no_init0s r$cCst|tstddS)aRaise TypeError if `arg` is not an instance of `type` in `issubclass(arg, )`. In most cases, this is verified by type.__subclasscheck__. Checking it again unnecessarily would slow down issubclass() checks, so, we don't perform this check unless we absolutely have to. For various error paths, however, we want to ensure that *this* error message is shown to the user where relevant, rather than a typing.py-specific error message. z"issubclass() arg 1 must be a classN)rrrargryryr|_type_check_issubclass_arg_14s r'c@sBeZdZddZddZddZddZd d Zed d d Z dS) _ProtocolMetacKs|dkrt|dkrnZttjht|@rp|D]B}|ttjttjhks,|jt|j gks,t |s,t d|q,t j j||||f|S)Nr=rz5Protocols can only inherit from other protocols, got )rr=rrrrYr_PROTO_ALLOWLISTrrr7rrABCMetar)mclsrbases namespacerrryryr|rNsz_ProtocolMeta.__new__cOs.tjj|f||t|ddr*t||_dS)Nr"F)rr*rrrr rryryr|r^s z_ProtocolMeta.__init__cCs|tkrt||St|ddrtst|ddsBt|td|jr|j dt krt|t |j}tdt |ddd t j||S) Nr"F_is_runtime_protocolLInstance and class checks can only be used with @runtime_checkable protocols__subclasshook__zRProtocols with non-method members don't support issubclass(). Non-method members: rr .)r=r__subclasscheck__rr!r'rr rr _proto_hooksortedrrr*)rrZnon_method_attrsryryr|r2cs*    z_ProtocolMeta.__subclasscheck__c Cs|tkrt||St|dds.tj||St|ddsHtsHtdtj||rZdS|jD]F}zt ||}Wnt k rYqYnX|dkr`||j kr`qq`dSdS)Nr"Fr.r/T) r=rrrrr*r!rr inspectgetattr_staticrr )rinstancerrryryr|r}s(     z_ProtocolMeta.__instancecheck__cCs(tj||dkrdS|tko&|tjkS)NT)rr*rr=rrrryryr|rsz_ProtocolMeta.__eq__returncCs t|Sr)rrrryryr|rsz_ProtocolMeta.__hash__N) rrrrrr2rrintrryryryr|r(Gs   r(cCs|jddstS|jD]n}|jD]Z}||jkrN|j|dkrJtSqt|di}t|tjj r"||kr"t |r"qq"tSqdS)Nr"Fr T) rrrr rrr collectionsrrar7)rrrrrryryr|r3s$       r3cs0eZdZejjZdZdZdZfddZ Z S)r=ryTFcs^tj|||jdds2tdd|jD|_d|jkrBt|_|jrZ|j t j krZt |_ dS)Nr"Fcss|]}|tkVqdSr)r=rbryryr|rsz-Protocol.__init_subclass__..r0) r__init_subclass__rrany __bases__r"r3r0rr=r$rrryr|r@s zProtocol.__init_subclass__) rrrrr=r __slots__r"r.r@rryryrr|r=s c Cst|tjrt|dds&td|d|_t|ts@tj dkrt |_ |j D]^}zt t||d}Wn4tk r}ztd|d|W5d}~XYqNX|sN|j |qN|S) ajMark a protocol class as a runtime protocol. Such protocol can be used with isinstance() and issubclass(). Raise TypeError if applied to a non-protocol class. This allows a simple-minded structural check very similar to one trick ponies in collections.abc such as Iterable. For example:: @runtime_checkable class Closable(Protocol): def close(self): ... assert isinstance(open('/some/file'), Closable) Warning: this will check only the presence of the required methods, not their type signatures! r"Fz@@runtime_checkable can be only applied to protocol classes, got T)rt rNz,Failed to determine whether protocol member z is a method member) issubclassrrYrrr.rr(r version_inforr r callable Exceptionr)rrZ is_callableeryryr|r@s"   rtrDc@s(eZdZdZdZejedddZdS)r#z(An ABC with one abstract method __int__.ryr9cCsdSrryrzryryr|__int__$szSupportsInt.__int__N) rrrrrCrabstractmethodr<rKryryryr|r#sc@s(eZdZdZdZejedddZdS)r!z*An ABC with one abstract method __float__.ryr9cCsdSrryrzryryr| __float__-szSupportsFloat.__float__N) rrrrrCrrLfloatrMryryryr|r!(sc@s(eZdZdZdZejedddZdS)r z,An ABC with one abstract method __complex__.ryr9cCsdSrryrzryryr| __complex__6szSupportsComplex.__complex__N) rrrrrCrrLcomplexrOryryryr|r 1sc@s(eZdZdZdZejedddZdS)rz*An ABC with one abstract method __bytes__.ryr9cCsdSrryrzryryr| __bytes__?szSupportsBytes.__bytes__N) rrrrrCrrLbytesrQryryryr|r:sc@s$eZdZdZejedddZdS)r"ryr9cCsdSrryrzryryr| __index__GszSupportsIndex.__index__N)rrrrCrrLr<rSryryryr|r"Csc@s(eZdZdZdZejedddZdS)rz_ An ABC with one abstract method __abs__ that is covariant in its return type. ryr9cCsdSrryrzryryr|__abs__RszSupportsAbs.__abs__N) rrrrrCrrLrrTryryryr|rKsc@s,eZdZdZdZejdeedddZ dS) r$za An ABC with one abstract method __round__ that is covariant in its return type. ryr)ndigitsr:cCsdSrry)r{rUryryr| __round__]szSupportsRound.__round__N)r) rrrrrCrrLr<rrVryryryr|r$Vscsfdd}|S)NcsRtjjdkrDtjdkrDt|td}t|jd|}t||S|_ |SdS)Npypyr)__call____mro_entries__ry) rimplementationrrF staticmethodrrr update_wrapperrY)rZcls_dictr mro_entriesryr|innercsz#_ensure_subclassable..innerry)r^r_ryr]r|_ensure_subclassablebs r`c@seZdZddZdS) SingletonMetacCstd|d|jdS)Nz cannot set z attribute of immutable type rr)rrvalueryryr|rwszSingletonMeta.__setattr__N)rrrrryryryr|ravsrac@s,eZdZdZdZddZddZddZd S) NoDefaultTypez$The type of the NoDefault singleton.rycCstdpt|SNrMglobalsrrrr;ryryr|rszNoDefaultType.__new__cCsdS)Nztyping_extensions.NoDefaultryrzryryr|r}szNoDefaultType.__repr__cCsdSreryrzryryr| __reduce__szNoDefaultType.__reduce__NrrrrrCrr}rhryryryr|rds rdc@s,eZdZdZdZddZddZddZd S) NoExtraItemsTypez'The type of the NoExtraItems singleton.rycCstdpt|SNrNrfr;ryryr|rszNoExtraItemsType.__new__cCsdS)Nztyping_extensions.NoExtraItemsryrzryryr|r}szNoExtraItemsType.__repr__cCsdSrkryrzryryr|rhszNoExtraItemsType.__reduce__Nriryryryr|rjs rjFmoduleccst|}|tkr*t|}|r||d}qzq|q|tkrDtVt|\}q|tkr^tVt|\}q|tkr|tVt|\}qq|qdSr)r2r%r1rKrLrJ)annotation_typeZannotation_originZannotation_argsryryr|_get_typeddict_qualifierss     rnc@s.eZdZddedddZeZddZeZdS)_TypedDictMetaTNtotalclosed extra_itemscs|D]"}t|tk r|tjk rtdq|dk rH|tk rHtd|dtdd|Drdtjf}nd}ttd|tf||_ j dkr|_ t d s|_ i} d |kr|d } nd |kr|d d } ni} d t rfdd| D} nfdd| D} t} t} t} t}|}|D]f}|j}| |d i| |dd| |dd| |dd||ddq,|rtjdkrd| kr| d}tt|}t|krtdt|krtd|}| | | D]\}}tt|}t|kr*| |n2t|kr@| |n|rR| |n | |t|kr|||| |n||| |q| _t| _t| _t| _ t|_!|_"|_#|_$S)aICreate new typed dict class object. This method is called when TypedDict is subclassed, or when TypedDict is instantiated. This way TypedDict supports all three syntax forms described in its docstring. Subclasses and instances of TypedDict return actual dictionaries. zHcannot inherit from both a TypedDict type and a non-TypedDict base classNzCannot combine closed=z and extra_itemscss|]}t|tjVqdSr)rErrYr>ryryr|rsz)_TypedDictMeta.__new__..ryr=__orig_bases__r  __annotate__rz?TypedDict('Name', {f0: t0, f1: t1, ...}); each t must be a typecs$i|]\}}|tj|jdqS)rl)rrrrntprtp_dictryr| sz*_TypedDictMeta.__new__..csi|]\}}|t|qSryrrwrryr|r|s__required_keys____optional_keys____readonly_keys____mutable_keys__rt__extra_items__z5Special key __extra_items__ does not support Requiredz8Special key __extra_items__ does not support NotRequired)%rrorrYrrNrArdictrrhasattrrt _TAKES_MODULEitemsrrupdaterrrFpoprnrKrLrrJdiscardr rr}r~rr __total__Z __closed__r)rrr,nsrqrrrsrZ generic_baserZown_annotationsZ required_keysZ optional_keysZ readonly_keysZ mutable_keysZextra_items_typeZ base_dictrmZ qualifiersZannotation_keyryrzr|rs                            z_TypedDictMeta.__new__cCs tddS)Nz4TypedDict does not support instance and class checksrr8ryryr|r2Lsz _TypedDictMeta.__subclasscheck__) rrrrNrrrXr2rryryryr|ros  qrorycCstfSr) _TypedDictr,ryryr|Trrpc Ks|tks|dkr|tkrd}nd}d|d|d}|d|d}tj|td d |d k rz|d k rz|dk rz||d <d}|tk r||d<t}|}n |rtd|rtjdkrtdtjdtd d dt|i} t } | dk r| | d<t |d| |||d} t f| _ | S)aqA simple typed namespace. At runtime it is equivalent to a plain dict. TypedDict creates a dictionary type such that a type checker will expect all instances to have a certain set of keys, where each key is associated with a value of a consistent type. This expectation is not checked at runtime. Usage:: class Point2D(TypedDict): x: int y: int label: str a: Point2D = {'x': 1, 'y': 2, 'label': 'good'} # OK b: Point2D = {'z': 3, 'label': 'bad'} # Fails type check assert Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first') The type info can be accessed via the Point2D.__annotations__ dict, and the Point2D.__required_keys__ and Point2D.__optional_keys__ frozensets. TypedDict supports an additional equivalent form:: Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str}) By default, all keys must be present in a TypedDict. It is possible to override this by specifying totality:: class Point2D(TypedDict, total=False): x: int y: int This means that a Point2D TypedDict can have any of the keys omitted. A type checker is only expected to support a literal False or True as the value of the total argument. True is the default, and makes all items defined in the class body be required. The Required and NotRequired special forms can also be used to mark individual keys as being required or not required:: class Point2D(TypedDict): x: int # the "x" key must always be present (Required is the default) y: NotRequired[int] # the "y" key can be omitted See PEP 655 for more details on Required and NotRequired. N2Failing to pass a value for the 'fields' parameter(Passing `None` as the 'fields' parameter`z = TypedDict(z, {})`z is deprecated and will be disallowed in Python 3.15. To create a TypedDict class with 0 fields using the functional syntax, pass an empty dictionary, e.g. r1r stacklevelFTrrrsz@TypedDict takes either a dict or keyword arguments, but not bothrz$TypedDict takes no keyword argumentszThe kwargs-based syntax for TypedDict definitions is deprecated in Python 3.11, will be removed in Python 3.13, and may not be understood by third-party type checkers.r rryrp) _markerwarningswarnDeprecationWarningrNrrrFrrrorrt) typenamefieldsrqrrrsrdeprecated_thingexampledeprecation_msgrrltdryryr|rTsJ9   cCs"ttdr|tjkrdSt|tS)aCheck if an annotation is a TypedDict class For example:: class Film(TypedDict): title: str year: int is_typeddict(Film) # => True is_typeddict(Union[list, str]) # => False rF)rrrr_TYPEDDICT_TYPESryryryr|r8s cCs|S)aAssert (to the type checker) that the value is of the given type. When the type checker encounters a call to assert_type(), it emits an error if the value is not of the specified type:: def greet(name: str) -> None: assert_type(name, str) # ok assert_type(name, int) # type checker error At runtime this returns the first argument unchanged and otherwise does nothing. ry)rtypryryr|r's cCst|trt|jSt|dr<|jtttfkr.rcss|]}t|VqdSrrrryryr|rsrcss|]}t|VqdSrrrryryr|rs)r_AnnotatedAliasrrrrKrLrJrrrrrrrrr reduceoperatoror_)rZ stripped_argsryryr|rs(       rcCs|ttdrtj|||dd}ntj|||d}tjdkrFt||||tjdkrbdd|D}|rj|Sd d|DS) aReturn type hints for an object. This is often the same as obj.__annotations__, but it handles forward references encoded as string literals, adds Optional[t] if a default value equal to None is set and recursively replaces all 'Annotated[T, ...]', 'Required[T]' or 'NotRequired[T]' with 'T' (unless 'include_extras=True'). The argument may be a module, class, method, or function. The annotations are returned as a dictionary. For classes, annotations include also inherited members. TypeError is raised if the argument is not of a type that can contain annotations, and an empty dictionary is returned if no annotations are present. BEWARE -- the behavior of globalns and localns is counterintuitive (unless you are familiar with how eval() and exec() work). The search order is locals first, then globals. - If no dict arguments are passed, an attempt is made to use the globals from obj (or the respective module's globals for classes), and these are also used as the locals. If the object does not appear to have globals, an empty dictionary is used. - If one dict argument is passed, it is used for both globals and locals. - If two dict arguments are passed, they specify globals and locals, respectively. r%T)globalnslocalnsinclude_extras)rrrrcSs,i|]$\}}|t|tkr|nt|jqSry)r2rorrkrryryr|r|-s  z"get_type_hints..cSsi|]\}}|t|qSryrrryryr|r|5s)rrr5rrF_clean_optionalr)rrrrhintryryr|r5s"   cCs&t|tk rdS|jdtk r"dSdS)z detects Union[..., None] patternFr T)r2ror _NoneTyperryryr|_could_be_inserted_optional9s  rc Csf|rt|trdSt|}|s$dS|j}|D],\}}t|r2||ks2||dk rZq2||}|dkrnt}t|tr|dkrt|t j r|j }n"|} t | dr| j } qt| di}|dkr|}n |dkr|}tjdkrt|}nt|t|t j  d}t|||} tjdkr,t| tkr,t| j} | |ksXt t dr2t| t jr2t|t js2| ||<q2dS)N __wrapped__ __globals__r) is_argumentr)rrr _get_defaultsr rrrrr ModuleTyperrrrrrFrV _eval_typer2rorr) rhintsrrrZoriginal_hintsrrcoriginal_valuensobjZoriginal_evaluatedryryr|rDsZ             rcsHeZdZdZfddZddZddZdd Zd d Zd d Z Z S)raKRuntime representation of an annotated type. At its core 'Annotated[t, dec1, dec2, ...]' is an alias for the type 't' with extra annotations. The alias behaves like a normal typing alias, instantiating is the same as instantiating the underlying type, binding it to types is also the same. cs2t|tr|j|}|j}t||||_dSr)rr __metadata__rrr)r{rmetadatarryr|rs   z_AnnotatedAlias.__init__cCs$t|dkst|d}t||jSNrr)rrrr)r{rnew_typeryryr|rsz_AnnotatedAlias.copy_withcCs,dt|jdddd|jDdS)Nztyping_extensions.Annotated[, css|]}t|VqdSr)reprrryryr|rsz+_AnnotatedAlias.__repr__..])r _type_reprrjoinrrzryryr|r}sz_AnnotatedAlias.__repr__cCstjt|jf|jffSr)rgetitemr%rrrzryryr|rhs z_AnnotatedAlias.__reduce__cCs*t|tstS|j|jkrdS|j|jkS)NF)rrrrrr{rryryr|rs   z_AnnotatedAlias.__eq__cCst|j|jfSr)rrrrzryryr|rsz_AnnotatedAlias.__hash__) rrrrrrr}rhrrrryryrr|rs rc@s2eZdZdZdZddZejddZddZ d S) r%aAdd context specific metadata to a type. Example: Annotated[int, runtime_check.Unsigned] indicates to the hypothetical runtime_check module that this type is an unsigned int. Every other consumer of this type can ignore this metadata and treat this type as int. The first argument to Annotated must be a valid type (and will be in the __origin__ field), the remaining arguments are kept as a tuple in the __extra__ field. Details: - It's an error to call `Annotated` with less than two arguments. - Nested Annotated are flattened:: Annotated[Annotated[T, Ann1, Ann2], Ann3] == Annotated[T, Ann1, Ann2, Ann3] - Instantiating an annotated type is equivalent to instantiating the underlying type:: Annotated[C, Ann1](5) == C(5) - Annotated can be used as a generic type alias:: Optimized = Annotated[T, runtime.Optimize()] Optimized[int] == Annotated[int, runtime.Optimize()] OptimizedList = Annotated[List[T], runtime.Optimize()] OptimizedList[int] == Annotated[List[int], runtime.Optimize()] rycOs tddS)Nz&Type Annotated cannot be instantiated.rrryryr|rszAnnotated.__new__cCsnt|trt|dkrtdttf}t|d|kr@|d}nd}t|d|}t|dd}t ||S)NrzUAnnotated[...] should be used with at least two arguments (a type and an annotation).rz$Annotated[t, ...]: t must be a type.r) rrrrrrr2rrr)rrZallowed_special_formsrrrryryr|__class_getitem__s zAnnotated.__class_getitem__cOstd|jddS)NCannot subclass z .Annotated)rrrryryr|r@s zAnnotated.__init_subclass__N) rrrrrCrrrrr@ryryryr|r%s   )_BaseGenericAlias)rcCs>t|trtSt|tjttttfr*|j S|tj kr:tj SdS)a6Get the unsubscripted version of a type. This supports generic types, Callable, Tuple, Union, Literal, Final, ClassVar and Annotated. Return None for unsupported types. Examples:: get_origin(Literal[42]) is Literal get_origin(int) is None get_origin(ClassVar[int]) is ClassVar get_origin(Generic) is Generic get_origin(Generic[T]) is Generic get_origin(Union[T, int]) is Union get_origin(List[Tuple[T, T]][int]) == list get_origin(P.args) is P N) rrr%rr_typing_GenericAliasrrr rrYrryryr|r2s   cCszt|tr|jf|jSt|tjtfrvt|ddr8dS|j}t |t j j krr|dt k rrt|dd|df}|SdS)aGet type arguments with all substitutions performed. For unions, basic simplifications used by Union constructor are performed. Examples:: get_args(Dict[str, int]) == (str, int) get_args(int) == () get_args(Union[int, Union[T, int], str][int]) == (int, str) get_args(Union[int, Tuple[T, int]][str]) == (int, Tuple[str, int]) get_args(Callable[[], T][int]) == ([], int) rFryrNr )rrrrrrrrrr2r=rrREllipsisr)ryresryryr|r1s  cCst|ddS)a&Special marker indicating that an assignment should be recognized as a proper type alias definition by type checkers. For example:: Predicate: TypeAlias = Callable[..., bool] It's invalid when used anywhere except as in the example above.  is not subscriptableNrr{rryryr|rB-s a%Special marker indicating that an assignment should be recognized as a proper type alias definition by type checkers. For example:: Predicate: TypeAlias = Callable[..., bool] It's invalid when used anywhere except as in the example above.csfdd|_|_dS)Ncstk Sr)rMrydefaultryr|rLrz_set_default..) has_default __default__) type_paramrryrr| _set_defaultKsrcCstdd}|dkr||_dS)Nrtrr)rr)Z typevarlikedef_modryryr| _set_modulePs rc@seZdZdZdZeZdS) _DefaultMixinzMixin for TypeVarLike defaults.ryN)rrrrrCrrryryryr|rWsrc@seZdZeedddZdS)_TypeVarLikeMeta)_TypeVarLikeMeta__instancer:cCs t||jSr)r_backported_typevarlike)rrryryr|r`sz"_TypeVarLikeMeta.__instancecheck__N)rrrrboolrryryryr|r_sr)r c@s:eZdZdZejZdddeddddZdddd Z dS) r zType variable.NF)boundrrrinfer_variancec sttdr(tj|f|||||dn4tj|f||||d|rV|sN|rVtd|_t|tfdd}|_S)NrCrrrrrrrz1Variance cannot be specified with infer_variance.cs,r(|jt|kr(|jf7}|Sr)r__parameters__indexrr)aliasrZtypevarryr|_tvar_prepare_substs  z,TypeVar.__new__.._tvar_prepare_subst)rrr r__infer_variance__rr__typing_prepare_subst__) rrrrrrr constraintsrryrr|rms$     zTypeVar.__new__r9cCstdtddS)Ntype 'z(.TypeVar' is not an acceptable base typerbr;ryryr|r@szTypeVar.__init_subclass__) rrrrrr rrMrr@ryryryr|r hs c@s$eZdZdZdZddZddZdS) _Immutablez3Mixin to indicate that object should not be copied.rycCs|Srryrzryryr|__copy__sz_Immutable.__copy__cCs|Srry)r{memoryryr| __deepcopy__sz_Immutable.__deepcopy__N)rrrrrCrrryryryr|rsrc@s(eZdZdZddZddZddZdS) raQThe args for a ParamSpec object. Given a ParamSpec object P, P.args is an instance of ParamSpecArgs. ParamSpecArgs objects have a reference back to their ParamSpec: P.args.__origin__ is P This type is meant for runtime introspection and has no special meaning to static type checkers. cCs ||_dSrrr{rryryr|rszParamSpecArgs.__init__cCs|jjdS)Nz.argsrrrzryryr|r}szParamSpecArgs.__repr__cCst|tstS|j|jkSr)rrrrrryryr|rs zParamSpecArgs.__eq__Nrrrrrr}rryryryr|rs c@s(eZdZdZddZddZddZdS) r a[The kwargs for a ParamSpec object. Given a ParamSpec object P, P.kwargs is an instance of ParamSpecKwargs. 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. cCs ||_dSrrrryryr|rszParamSpecKwargs.__init__cCs|jjdS)Nz.kwargsrrzryryr|r}szParamSpecKwargs.__repr__cCst|tstS|j|jkSr)rr rrrryryr|rs zParamSpecKwargs.__eq__Nrryryryr|r s )rc@s:eZdZdZejZddddedddZdddd Z dS) rzParameter specification.NFrrrrrcs`ttdr tj|||||dntj||||d|_t|tfdd}|_S)NrCrrcs|j}|}|t|kr0r0|jf}|t|krJtd|t|dkrxt|dsx|dkspt|f}n6t ||t r|d|t ||f||dd}|S)NToo few arguments for rr) rrrrrrr_is_param_exprrrrr)rrriZ paramspecryr|_paramspec_prepare_substs    (z3ParamSpec.__new__.._paramspec_prepare_subst)rrrrrrr)rrrrrrrrryrr|rs    zParamSpec.__new__r9cCstdtddS)Nrz*.ParamSpec' is not an acceptable base typerbr;ryryr|r@szParamSpec.__init_subclass__) rrrrrrrrMrr@ryryryr|rs %c@sleZdZdZejZeddZeddZ dddde dd d Z d d Z d dZ ddZddZddZdS)ra'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 variables 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. cCst|Sr)rrzryryr|r7szParamSpec.argscCst|Sr)r rzryryr|r;szParamSpec.kwargsNFrcCspt||g||_t||_t||_t||_|rFt|d|_ nd|_ t ||t }|dkrl||_ dS)NzBound must be a type.r) rrrr __covariant____contravariant__rrr __bound__rrr)r{rrrrrrrryryr|r?s    zParamSpec.__init__cCs2|jr d}n|jrd}n|jr$d}nd}||jS)N+-~)rrrr)r{prefixryryr|r}QszParamSpec.__repr__cCs t|Srrrrzryryr|r\szParamSpec.__hash__cCs||kSrryrryryr|r_szParamSpec.__eq__cCs|jSrrrzryryr|rhbszParamSpec.__reduce__cOsdSrryr#ryryr|rXfszParamSpec.__call__)rrrrrr rpropertyrrrMrr}rrrhrXryryryr|rs/     _type_convert)allow_special_formscCsT|dkrtdSt|trPtjdkr,t|StjdkrBt||dSt|||dS|S)z=For converting None to type(None), and strings to ForwardRef.N)rtr)rtrrv)rlZis_class)rrrrrFrV)r&rlrryryr|rps    csZeZdZejZdZfddZddZddZ dd Z e d d Z d d Z ddZZS)_ConcatenateGenericAliasFcst|||_||_dSr)rrrr)r{rrrryr|rs z!_ConcatenateGenericAlias.__init__cs2tj|jddfdd|jDdS)N[rc3s|]}|VqdSrryrr&rryr|rsz4_ConcatenateGenericAlias.__repr__..r)rrrrrrzryr r|r}sz!_ConcatenateGenericAlias.__repr__cCst|j|jfSr)rrrrzryryr|rsz!_ConcatenateGenericAlias.__hash__cOsdSrryr#ryryr|rXsz!_ConcatenateGenericAlias.__call__cCstdd|jDS)Ncss"|]}t|tjtfr|VqdSr)rrr r)rryryryr|rsz:_ConcatenateGenericAlias.__parameters__..)rrrzryryr|rsz'_ConcatenateGenericAlias.__parameters__cCs|t|dtr&|dd|dj}nHt|dttfrL|dd|dS|ddksnt|dtsntd||j|SNr .MThe last parameter to Concatenate should be a ParamSpec variable or ellipsis.) rrrrrrrrrr{rryryr|rs"_ConcatenateGenericAlias.copy_withc s|jttfkrtd||js0t|dt|ts@|f}tdd|D}|j}|D]}t|dd}|dk r|||}q\t|t r\| |}|t |krt|dt t k r||j f}|t |krtd|t |dkrt|d s|d kst|f}q\t||tr\t||ts\|d|t||f||dd}q\t |}t |}||krtd ||krzd nd d |d|d|tt|j|g}|jD]} t| tr|| qt| tr2| } t| tjrt| s"ttdrt| tjrt| ddrt| dnPt| ttdsHtjn tjtjfr| j} | rtfdd| D} | | } || q|t|S)Nz%Cannot subscript already-subscripted rcss|]}t|VqdSr)rrryryr|rs7_ConcatenateGenericAlias.__getitem__..rrrrrrrrrrrr __unpacked__F is not valid as type argumentc3s|]}|VqdSrry)rxZsubstryr|rs)rrYr=rrrr _unpack_argsrrrrrMrrrrrrziprrrr rr _is_unpackrrrr) r{rrparamprepareralenplennew_argsr&Z subparamssubargsryrr|rs          * (         $_ConcatenateGenericAlias.__getitem__)rrrrrrrrr}rrXrrrrrryryrr|r~s   rcs,eZdZdZfddZfddZZS)rrcst|dttfr&|dd|dSt|dtjrN|dd|dj}n"|ddkspt|dtsptdttj| |Sr ) rrrrrrrrrrrrryr|rsrcsBt|}t|tr>tdd|Dr>ttdd|DS|S)Ncss|]}t|VqdSrrrrryryr|r srcss|] }|VqdSrryrrxryryr|rs)rrrrrAr)r{rrcrryr|r s r)rrrrrrryryrr|rs c@s eZdZdS)_EllipsisDummyN)rrrryryryr|r"sr"cCs|ddkr(tjdkr(|ddtf}tjdkrHt||ttfdd}n t||}|dtk rb|Stdd|jD|_tjd kr|Std d|jD|_|S) Nr .)rtrrrtrrtT)Z_typevar_typesZ_paramspec_tvarscss|]}|tk r|ndVqdS).Nr"rryryr|r$sz,_create_concatenate_alias..rcss|]}|tk r|VqdSrr$rryryr|r)s) rrFr"rr rrrr)rrZ concatenateryryr|_create_concatenate_aliass"     r%cst|dkrtdt|ts |f}|ddksBt|dtsBtddfdd|ddD|df}t||S) Nryz&Cannot take a Concatenate of no types.r .r z/Concatenate[arg, ...]: each arg must be a type.c3s|]}t|VqdSrrrrryr|r9sz'_concatenate_getitem..)rrrrr%rryrr|_concatenate_getitem/s r&cCs t||S)&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. r&rryryr|rCs c@seZdZddZdS)_ConcatenateFormcCs t||Srr(rryryr|rSsz_ConcatenateForm.__getitem__Nrrrrryryryr|r)Rsr)r'cCs t||d}t||fS) Special typing form used to annotate the return type of a user-defined type guard function. ``TypeGuard`` only accepts a single type argument. At runtime, functions marked this way should return a boolean. ``TypeGuard`` aims to benefit *type narrowing* -- a technique used by static type checkers to determine a more precise type of an expression within a program's code flow. Usually type narrowing is done by analyzing conditional code flow and applying the narrowing to a block of code. The conditional expression here is sometimes referred to as a "type guard". Sometimes it would be convenient to use a user-defined boolean function as a type guard. Such a function should use ``TypeGuard[...]`` as its return type to alert static type checkers to this intention. Using ``-> TypeGuard`` tells the static type checker that for a given function: 1. The return value is a boolean. 2. If the return value is ``True``, the type of its argument is the type inside ``TypeGuard``. For example:: def is_str(val: Union[str, float]): # "isinstance" type guard if isinstance(val, str): # Type of ``val`` is narrowed to ``str`` ... else: # Else, type of ``val`` is narrowed to ``float``. ... Strict type narrowing is not enforced -- ``TypeB`` need not be a narrower form of ``TypeA`` (it can even be a wider form) and this may lead to type-unsafe results. The main reason is to allow for things like narrowing ``List[object]`` to ``List[str]`` even though the latter is not a subtype of the former, since ``List`` is invariant. The responsibility of writing type-safe type guards is left to the user. ``TypeGuard`` also works with type variables. For more information, see PEP 647 (User-Defined Type Guards).  accepts only a single type.rrrr{ritemryryr|rEhs,c@seZdZddZdS)_TypeGuardFormcCs"t||jd}t||fSNz accepts only a single typerrrrr.ryryr|rs z_TypeGuardForm.__getitem__Nr*ryryryr|r0sr0r+cCs t||d}t||fS)wSpecial 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 the return value is ``True``, the type of its argument is the intersection of the type inside ``TypeIs`` 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). r,r-r.ryryr|rFs&c@seZdZddZdS) _TypeIsFormcCs"t||jd}t||fSr1r2r.ryryr|rs z_TypeIsForm.__getitem__Nr*ryryryr|r4sr4r3c@seZdZddZdS) _TypeFormFormcCs|Srryrryryr|rX/ s_TypeFormForm.__call__N)rrrrXryryryr|r5, sr5cCs t||d}t||fS)A special form representing the value that results from the evaluation of a type expression. This value encodes the information supplied in the type expression, and it represents the type described by that type expression. When used in a type expression, TypeForm describes a set of type form objects. It accepts a single type argument, which must be a valid type expression. ``TypeForm[T]`` describes the set of all type form objects that represent the type T or types that are assignable to T. Usage: def cast[T](typ: TypeForm[T], value: Any) -> T: ... reveal_type(cast(int, "x")) # int See PEP 747 for more information. r,r-r.ryryr|rD2 sc@seZdZddZddZdS)r5cCs"t||jd}t||fSr1r2r.ryryr|rJ s z_TypeFormForm.__getitem__cCs|Srryrryryr|rXO sr6N)rrrrrXryryryr|r5I sr7c@sneZdZdZddZddZddZdd Zd d Zd d Z ddZ ddZ ddZ ddZ ejddZdS) _SpecialForm)rr_getitemcCs||_|j|_|j|_dSr)r9rrrr{rryryr|rk sz_SpecialForm.__init__cCs|dkr|jSt|dS)N>rr)rr)r{r/ryryr| __getattr__p sz_SpecialForm.__getattr__cCstd|dS)Nrr)r{r,ryryr|rYv sz_SpecialForm.__mro_entries__cCs d|jSrrrzryryr|r}y sz_SpecialForm.__repr__cCs|jSrrrzryryr|rh| sz_SpecialForm.__reduce__cOstd|dS)NzCannot instantiate rr{rkwdsryryr|rX sz_SpecialForm.__call__cCstj||fSrrrorryryr|__or__ sz_SpecialForm.__or__cCstj||fSrr>rryryr|__ror__ sz_SpecialForm.__ror__cCst|ddS)Nz! cannot be used with isinstance()rrryryr|r sz_SpecialForm.__instancecheck__cCst|ddS)Nz! cannot be used with issubclass()r)r{rryryr|r2 sz_SpecialForm.__subclasscheck__cCs |||Sr)r9rryryr|r sz_SpecialForm.__getitem__N)rrrrCrr;rYr}rhrXr?r@rr2rrrryryryr|r8h sr8cCst|ddS)aDRepresents an arbitrary literal string. Example:: from typing_extensions import LiteralString def query(sql: LiteralString) -> ...: ... query("SELECT * FROM table") # ok query(f"SELECT * FROM {input()}") # not ok See PEP 675 for details. rNrrryryr|r scCst|ddS)zUsed to spell the type of "self" in classes. Example:: from typing import Self class ReturnsSelf: def parse(self, data: bytes) -> Self: ... return self rNrrryryr|r scCst|ddS)aThe bottom type, a type that has no members. This can be used to define a function that should never be called, or a function that never returns:: from typing_extensions import Never def never_call_me(arg: Never) -> None: pass def int_or_str(arg: int | str) -> None: never_call_me(arg) # type checker error match arg: case int(): print("It's an int") case str(): print("It's a str") case _: never_call_me(arg) # ok, arg is of type Never rNrrryryr|rH scCs"t||jd}t||fS)A special typing construct to mark a key of a total=False TypedDict as required. For example: class Movie(TypedDict, total=False): title: Required[str] year: int m = Movie( title='The Matrix', # typechecker error if key is omitted year=1999, ) There is no runtime checking that a required key is actually provided when instantiating a related TypedDict. r,r2r.ryryr|rK scCs"t||jd}t||fS)`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, ) r,r2r.ryryr|rL sc@seZdZddZdS) _RequiredFormcCs"t||jd}t||fSNr,r2r.ryryr|r s z_RequiredForm.__getitem__Nr*ryryryr|rC srCrArBcCs"t||jd}t||fS)aA special typing construct to mark an item 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 property. r,r2r.ryryr|rJ1 sc@seZdZddZdS) _ReadOnlyFormcCs"t||jd}t||fSrDr2r.ryryr|rF s z_ReadOnlyForm.__getitem__Nr*ryryryr|rEE srEaA 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. aType unpack operator. The type unpack operator takes the child types from some container type, 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 `Ts` as a tuple of an arbitrary number of individual # `TypeVar`s, which the `Unpack` is 'pulling out' directly into the # `Generic[]`.) class Bar(Generic[Unpack[Ts]]): ... Bar[int] # Valid Bar[int, str] # Also valid From Python 3.11, this can also be done using the `*` operator: Foo[*tuple[int, str]] class Bar(Generic[*Ts]): ... The operator can also be used along with a `TypedDict` to annotate `**kwargs` in a function signature. For instance: class Movie(TypedDict): name: str year: int # This function expects two keyword arguments - *name* of type `str` and # *year* of type `int`. def foo(**kwargs: Unpack[Movie]): ... Note that there is only some runtime checking of this operator. Not everything the runtime allows may be accepted by static type checkers. For more information, see PEP 646 and PEP 692. cCs t|tkSr)r2rrryryr|r srcseZdZfddZZS)_UnpackSpecialFormcst|t|_dSr)rr _UNPACK_DOCrr:rryr|r s z_UnpackSpecialForm.__init__)rrrrrryryrr|rG srGcsDeZdZejdkrejZeddZ eddZ fddZ Z S) _UnpackAliasrcCsV|jtkstt|jdks t|j\}t|tjtj frR|jt k rLt d|jSdSNrz*Unpack[...] must be used with a tuple type) rrrrrrrrrrrrr{r&ryryr|__typing_unpacked_tuple_args__ s +_UnpackAlias.__typing_unpacked_tuple_args__cCs0|jtkstt|jdks tt|jdtSrrrrrrrr rzryryr|#__typing_is_unpacked_typevartuple__ s0_UnpackAlias.__typing_is_unpacked_typevartuple__cs|jr |St|SrrOrrr{rrryr|r s_UnpackAlias.__getitem__) rrrrrFrr rrrLrOrrryryrr|rI s   rIcCs t||jd}t||fSrDrrrrIr.ryryr|r scCs t|tSrrrIrFryryr|r scs:eZdZejZeddZeddZfddZ Z S)rIcCsP|jtkstt|jdks t|j\}t|tjrL|jtk rFt d|jSdSrJ) rrrrrrrrrrrKryryr|rL s  rMcCs0|jtkstt|jdks tt|jdtSrrNrzryryr|rO srPcs|jr |St|SrrQrRrryr|r srS) rrrrr rrrLrOrrryryrr|rI s   c@seZdZddZdS) _UnpackFormcCs t||jd}t||fSrDrTr.ryryr|r s z_UnpackForm.__getitem__Nr*ryryryr|rV srVcCs t|tSrrUrFryryr|r scGsLg}|D]>}t|dd}|dk r<|r0|ddks<||q||q|S)NrLr .)rrr)rZnewargsr&rryryr|r s   r)r c@s,eZdZdZejZedddZddZ dS)r zType variable tuple.rcs2t|t|tfdd}|_S)Ncs|j}|}||ddD]}t|tr td|q t|}t|}|}||d}d} d} t|D]V\} } t| tsnt| dd} | rnt| dkrn| ddkrn| dk rtd| } | d} qn| dk rt || }t ||| d}n,|||krtd |d |d |d|||kr< r._typevartuple_prepare_subst)rr rrr)rrrr]ryr\r|r s    -zTypeVarTuple.__new__cOs tddS)N&Cannot subclass special typing classesrr<ryryr|r@' sTypeVarTuple.__init_subclass__N) rrrrrr rrMrr@ryryryr|r s5c@sTeZdZdZejZddZedddZ ddZ d d Z d d Z d dZ ddZdS)r aType variable tuple. Usage:: Ts = TypeVarTuple('Ts') In the same way that a normal type variable is a stand-in for a single type such as ``int``, a type variable *tuple* is a stand-in for a *tuple* type such as ``Tuple[int, str]``. Type variable tuples can be used in ``Generic`` declarations. Consider the following example:: class Array(Generic[*Ts]): ... The ``Ts`` type variable tuple here behaves like ``tuple[T1, T2]``, where ``T1`` and ``T2`` are type variables. To use these type variables as type parameters of ``Array``, we must *unpack* the type variable tuple using the star operator: ``*Ts``. The signature of ``Array`` then behaves as if we had simply written ``class Array(Generic[T1, T2]): ...``. In contrast to ``Generic[T1, T2]``, however, ``Generic[*Shape]`` allows us to parameterise the class with an *arbitrary* number of type parameters. Type variable tuples can be used anywhere a normal ``TypeVar`` can. This includes class definitions, as shown above, as well as function signatures and variable annotations:: class Array(Generic[*Ts]): def __init__(self, shape: Tuple[*Ts]): self._shape: Tuple[*Ts] = shape def get_shape(self) -> Tuple[*Ts]: return self._shape shape = (Height(480), Width(640)) x: Array[Height, Width] = Array(shape) y = abs(x) # Inferred type is Array[Height, Width] z = x + x # ... is Array[Height, Width] x.get_shape() # ... is tuple[Height, Width] ccs |jVdSr)rrzryryr|__iter__Z szTypeVarTuple.__iter__rcCs4||_t||t}|dkr&||_t||_dS)Nr)rrrrrrr)r{rrrryryr|r] s  zTypeVarTuple.__init__cCs|jSrrrzryryr|r}h szTypeVarTuple.__repr__cCs t|Srrrzryryr|rk szTypeVarTuple.__hash__cCs||kSrryrryryr|rn szTypeVarTuple.__eq__cCs|jSrrrzryryr|rhq szTypeVarTuple.__reduce__cOsd|krtddS)Nrr^rr<ryryr|r@t sr_N)rrrrrr rr`rMrr}rrrhr@ryryryr|r + s, )rr:cCstdt|jtjd|S)aReveal the inferred type of a variable. When a static type checker encounters a call to ``reveal_type()``, it will emit the inferred type of the argument:: x: int = 1 reveal_type(x) Running a static type checker (e.g., ``mypy``) on this example will produce output similar to 'Revealed type is "builtins.int"'. At runtime, the function prints the runtime type of the argument and returns it unchanged. zRuntime type is )file)printrrrstderrrFryryr|r>| s_ASSERT_NEVER_REPR_MAX_LENGTHdr&r:cCs6t|}t|tkr$|dtd}td|dS)a1Assert to the type checker that a line of code is unreachable. Example:: def int_or_str(arg: int | str) -> None: match arg: case int(): print("It's an int") case str(): print("It's a str") case _: assert_never(arg) If a type checker finds that a call to assert_never() is reachable, it will emit an error. At runtime, this throws an exception when called. Nz...z*Expected code to be unreachable, but got: )rrrdr)r&rcryryr|r& s ) eq_default order_defaultkw_only_defaultfrozen_defaultfield_specifiers.)rgrhrirjrkrr:c sfdd}|S)aDecorator that marks a function, class, or metaclass as providing dataclass-like behavior. Example: from typing_extensions import dataclass_transform _T = TypeVar("_T") # Used on a decorator function @dataclass_transform() def create_model(cls: type[_T]) -> type[_T]: ... return cls @create_model class CustomerModel: id: int name: str # Used on a base class @dataclass_transform() class ModelBase: ... class CustomerModel(ModelBase): id: int name: str # Used on a metaclass @dataclass_transform() class ModelMeta(type): ... class ModelBase(metaclass=ModelMeta): ... class CustomerModel(ModelBase): id: int name: str Each of the ``CustomerModel`` classes defined in this example will now behave similarly to a dataclass created with the ``@dataclasses.dataclass`` decorator. For example, the type checker will synthesize an ``__init__`` method. The arguments to this decorator can be used to customize this behavior: - ``eq_default`` indicates whether the ``eq`` parameter is assumed to be True or False if it is omitted by the caller. - ``order_default`` indicates whether the ``order`` parameter is assumed to be True or False if it is omitted by the caller. - ``kw_only_default`` indicates whether the ``kw_only`` parameter is assumed to be True or False if it is omitted by the caller. - ``frozen_default`` indicates whether the ``frozen`` parameter is assumed to be True or False if it is omitted by the caller. - ``field_specifiers`` specifies a static list of supported classes or functions that describe fields, similar to ``dataclasses.field()``. At runtime, this decorator records its arguments in the ``__dataclass_transform__`` attribute on the decorated object. See PEP 681 for details. csd|_|S)N)rgrhrirjrkr)Z__dataclass_transform__)Z cls_or_fnrgrkrjrirrhryr| decorator sz&dataclass_transform..decoratorry)rgrhrirjrkrrmryrlr|r) sI _F)rc Cs(z d|_Wnttfk r"YnX|S)aHIndicate that a method is intended to override a method in a base class. Usage: class Base: def method(self) -> None: pass class Child(Base): @override def method(self) -> None: super().method() When this decorator is applied to a method, the type checker will validate that it overrides a method with the same name on a base class. This helps prevent bugs that may occur when a base class is changed without an equivalent change to a child class. There is no runtime checking of these properties. The decorator sets the ``__override__`` attribute to ``True`` on the decorated object to allow runtime introspection. See PEP 698 for details. T)Z __override__rrr%ryryr|r< s  )rtrurt_Tc@sHeZdZdZeddeejeje e ddddZ e e dd d Z dS) r*aIndicate that a class, function or overload is deprecated. When this decorator is applied to an object, the type checker will generate a diagnostic on usage of the deprecated object. Usage: @deprecated("Use B instead") class A: pass @deprecated("Use g instead") def f(): pass @overload @deprecated("int support is deprecated") def g(x: int) -> int: ... @overload def g(x: str) -> int: ... The warning specified by *category* will be emitted at runtime on use of deprecated objects. For functions, that happens on calls; for classes, on instantiation and on creation of subclasses. If the *category* is ``None``, no warning is emitted at runtime. The *stacklevel* determines where the warning is emitted. If it is ``1`` (the default), the warning is emitted at the direct caller of the deprecated object; if it is higher, it is emitted further up the stack. Static type checker behavior is not affected by the *category* and *stacklevel* arguments. The deprecation message passed to the decorator is saved in the ``__deprecated__`` attribute on the decorated object. If applied to an overload, the decorator must be after the ``@overload`` decorator for the attribute to exist on the overload as returned by ``get_overloads()``. See PEP 702 for details. rcategoryrN)messagerqrr:cCs4t|tstdt|j||_||_||_dS)Nz2Expected an object of type str for 'message', not )rrrrrrrrqr)r{rrrqrryryr|rf s zdeprecated.__init__rfc sv|j|j|jdkr$_Sttrddl}ddlm}j | fdd}t |_ j t|rj | fdd}t|_ n"| fdd}|_ _|_|_Strdddl}ddl}ddl}| fdd }|jrTtjd krJ||}n |jj|__|_|Std dS) Nr) MethodTypecsh|krtjddtjk r6|f||S|jtjkr\|sJ|r\t|jdn|SdS)Nrrpz() takes no arguments)rrrrrrrr)r&rqr original_newrryr|r s z$deprecated.__call__..__new__cstjdd||SNrrprrrrrqroriginal_init_subclassrryr|r@ sz.deprecated.__call__..__init_subclass__cstjdd||Srurvrwrxryr|r@ scstjdd||Srurvrw)r&rqrrryr|wrapper sz$deprecated.__call__..wrapperrJzY@deprecated decorator with non-None category must be applied to a class or callable, not )rrrqrZ__deprecated__rrr typesrsrwrapsr[r@r classmethodrGZasyncio.coroutinesr5 coroutinesiscoroutinefunctionrrFZmarkcoroutinefunction _is_coroutiner) r{r&r rsrr@asyncior5rzry)r&rqrryrtrr|rXw sP           zdeprecated.__call__)rrrrrrrrgr Warningr<rrorXryryryr|r*< s. cCs|dkpt|ttttfSN.)rrrrrr%ryryr|r s  rcCs|dkpt|tttttjfSr)rrrrrrr%ryryr|r s c Cszt|rHt|tjrHt|jdkrHt|jdtrH|rHt |dsHdS|sZt |d|t krt |drr|jst |dt|j}t|}||krv|}t |dr.dd|jD}t dd |D}|dkr|||krdS||kr.t||d ttk r dSt d d |D}||8}d |}tjd kr>dnd}t d||krTdndd|d|d|d| dS)Check correct count for parameters of a generic cls (internal helper). This gives a nice error message in case of count mismatch. rrNrrcSsg|]}t|s|qSryrrryryr| s"_check_generic..css|]}t|tVqdSr)rr rryryr|r s!_check_generic..rcss|]}t|dttk VqdSrNrrMrryryr|r s rr argumentsrrrr z for rr)r5isclassrErrYrrrrrrrrsumrrMrrF)rrelenr expect_valZ num_tv_tuplesnum_default_tvZthingsryryr|_check_generic sJ       rc Cs|st|dt|}||kr|}t|drdd|jD}||krt||dttk r`dStdd|D}||8}d |}td ||krd nd d |d|d|dS)rrrcSsg|]}t|s|qSryrrryryr|r" srrNcss|]}t|dttk VqdSrrrryryr|r/ s rrrrrrrr)rrrrrrMr)rrrrrrryryr|r s&  r9c Csjztd}Wnttfk r(YdSX|jddkr>dS|jd}|tjkpd|t kpd|tj kSdS)NrFrrr) rrrrrrf_localsrrYr=)framerryryr|"_has_generic_or_protocol_as_origin= s rcCs<t|tk rdSt|}t|o:t|dko:t|dtkS)NFrr)r2rr1rrr_TYPEVARTUPLE_TYPES)rrryryr|_is_unpacked_typevartupleS s  r_collect_type_varsc s|dkrtj}gt}d}d}|D]}t|r6d}ndt||rt|ts|kr|rt|dttk }|r||rvtdd}n|rtd|d |t |r fdd |j Dq$t|t r$|D]&}t|gD]}|krڈ |qqq$t S) zCollect all type variable contained in types in order of first appearance (lexicographic order). For example:: _collect_type_vars((T, List[S, T])) == (T, S) NFTr2Type parameter with a default follows TypeVarTupleType parameter 8 without a default follows type parameter with a defaultcsg|]}|kr|qSryryr tvarsryr|r sz&_collect_type_vars..)rr rrrrIrrMrrrrrrr) r{Z typevar_typesenforce_default_orderingdefault_encounteredtype_var_tuple_encounteredrrr collectedryrr|r` s@  c Csg}t}d}d}|D]}t|tr&qt|tr^|D]&}t|gD]}||krB||qBq4qt|dr||kr|rt|dttk }|r|rt d|rd}n|rt d|d||qt |rd}t|dd D]}||kr||qqt|S) zCollect all type variables and parameter specifications in args in order of first appearance (lexicographic order). For example:: assert _collect_parameters((T, Callable[P, T])) == (T, P) FZ__typing_subst__rrTrrrry) rrrr_collect_parametersrrrrMrr) rrrrrrrrrryryr|r s<    rcCsPdd|D}dd|D}tj||||d}||_|j_tjdkrL||_|S)NcSsg|] \}}|qSryryrrxrryryr|r sz!_make_nmtuple..c Ss&i|]\}}|t|d|dqS)zfield z annotation must be a typerrryryr|r| sz!_make_nmtuple..rrlr)r= namedtupler rrrF _field_types)rr{rlrrrnm_tplryryr| _make_nmtuple s rrrr c@seZdZddZdS)_NamedTupleMetac s0t|ks t|D]}|tk r|tjk rtdqtdd|D}dkrTd}ndkrjdd}ni}g}|D]L}|kr||qv|rvtd|dt|dkrd nd d d |qvt || fd d|Ddd}||_ tj|kr*t tdrt tj|_ntjjj} t | |_ D]\} } | tkrRtd| n| tkr2| |jkrxt|| | zt| j} Wntk rYnxXz| | || Wndtk r} zDdt| jd| d|}tjdkr| |n t|| W5d} ~ XYnXq2tj|kr,||S)Nz3can only inherit from a NamedTuple type and Genericcss|]}|tkrtn|VqdSr) _NamedTupler)rrryryr|r sz*_NamedTupleMeta.__new__..r rurzNon-default namedtuple field z cannot follow default fieldsrrrcsg|] }|qSryryr!rryr|r sz+_NamedTupleMeta.__new__..rr_generic_class_getitemz&Cannot overwrite NamedTuple attribute zError calling __set_name__ on z instance z in rJ)rrrrYrrrrrrrrBrr}rrr_prohibited_namedtuple_fieldsr_special_namedtuple_fields_fieldsrr __set_name__ BaseExceptionrrrFZadd_note RuntimeErrorr@)rrr,rrr{ default_names field_namerZ class_getitemkeyrset_namerIrryrr|r sh   2           z_NamedTupleMeta.__new__N)rrrrryryryr|r srcCst|ks ttfSr)rrrrryryr|_namedtuple_mro_entries-s rcKs|tkr:|rd}d}qd}d|d|d}d|d}nF|d krt|rPtd qd }d|d|d}d|d}n |rtd |tks|d krtj|j|d dtdd|}t||td}t f|_ |S)aoTyped version of namedtuple. Usage:: class Employee(NamedTuple): name: str id: int This is equivalent to:: Employee = collections.namedtuple('Employee', ['name', 'id']) The resulting class has an extra __annotations__ attribute, giving a dict that maps field names to types. (The field names are also in the _fields attribute, which is part of the namedtuple API.) An alternative equivalent functional syntax is also accepted:: Employee = NamedTuple('Employee', [('name', str), ('id', int)]) z3Creating NamedTuple classes using keyword argumentszq{name} is deprecated and will be disallowed in Python {remove}. Use the class-based or functional syntax instead.rrz = NamedTuple(z, [])`z{name} is deprecated and will be disallowed in Python {remove}. To create a NamedTuple class with 0 fields using the functional syntax, pass an empty list, e.g. r1Nz\Cannot pass `None` as the 'fields' parameter and also specify fields using keyword argumentsrzIEither list of fields or keywords can be provided to NamedTuple, not bothz3.15)rrrrrv) rrrrformatrrrrrrt)rrrrrrntryryr|r1sH c@seZdZdZdS)raBase class for classes that implement the buffer protocol. The buffer protocol allows Python objects to expose a low-level memory buffer interface. Before Python 3.12, it is not possible to implement the buffer protocol in pure Python code, or even to check whether a class implements the buffer protocol. In Python 3.12 and higher, the ``__buffer__`` method allows access to the buffer protocol from Python code, and the ``collections.abc.Buffer`` ABC allows checking whether a class implements the buffer protocol. To indicate support for the buffer protocol in earlier versions, inherit from this ABC, either in a stub file or at runtime, or use ABC registration. This ABC provides no methods, because there is no Python-accessible methods shared by pre-3.12 buffer classes. It is useful primarily for static checks. N)rrrrryryryr|rwscCsBz|jd|jWStk r<tdt|jdYnXdS)aReturn the class's "original" bases prior to modification by `__mro_entries__`. Examples:: from typing import TypeVar, Generic from typing_extensions import NamedTuple, TypedDict T = TypeVar("T") class Foo(Generic[T]): ... class Bar(Foo[int], float): ... class Baz(list[str]): ... Eggs = NamedTuple("Eggs", [("a", int), ("b", str)]) Spam = TypedDict("Spam", {"a": int, "b": str}) assert get_original_bases(Bar) == (Foo[int], float) assert get_original_bases(Baz) == (list[str],) assert get_original_bases(Eggs) == (NamedTuple,) assert get_original_bases(Spam) == (TypedDict,) assert get_original_bases(int) == (object,) rtz"Expected an instance of type, not N)rrrBrrrrr;ryryr|r3sc@sReZdZdZddZddZddZdd Zd d Ze j d krNd dZ ddZ dS)r:aLNewType creates simple unique types with almost zero runtime overhead. NewType(name, tp) is considered a subtype of tp by static type checkers. At runtime, NewType(name, tp) returns a dummy callable that simply returns its argument. Usage:: UserId = NewType('UserId', int) def name_by_id(user_id: UserId) -> str: ... UserId('user') # Fails type check name_by_id(42) # Fails type check name_by_id(UserId(42)) # OK num = UserId(5) + 1 # type: int cCs|Srryrryryr|rXszNewType.__call__cCs@||_d|kr|dd}||_||_t}|dkr<||_dS)Nr1r r)r rpartitionr __supertype__rr)r{rryrryryr|rszNewType.__init__cs|jGfddd}|fS)NcseZdZfddZdS)z&NewType.__mro_entries__..Dummycs&|j}td|d|dddS)NzGCannot subclass an instance of NewType. Perhaps you were looking for: `z = NewType(rz)`)rr)rZ subcls_nameZ supercls_nameryr|r@sz8NewType.__mro_entries__..Dummy.__init_subclass__N)rrrr@ryrryr|Dummysrr)r{r,rryrr|rYs zNewType.__mro_entries__cCs|jd|jS)Nr1)rrrzryryr|r}szNewType.__repr__cCs|jSr)rrzryryr|rhszNewType.__reduce__rcCstj||fSrr>rryryr|r?szNewType.__or__cCstj||fSrr>rryryr|r@szNewType.__ror__N) rrrrrXrrYr}rhrrFr?r@ryryryr|r:s   rcCs"|dkp t|ttjtjtjtfSz:Corresponds to is_unionable() in unionobject.c in CPython.N)rrrrrrrCrFryryr| _is_unionables rcCs|dkpt|ttjtjtfSr)rrrrrrCrFryryr|rs  rrBrrrrrLrY __reduce_ex__rhrrcs.eZdZddZejdkr&fddZZS)_TypeAliasGenericAliascCs |tkrt||St|j|Sr) _ATTRIBUTE_DELEGATION_EXCLUSIONSrr;rr)r{rryryr|r;!s z"_TypeAliasGenericAlias.__getattr__rcst|}t||_|Sr)rrrr)r{r/resultrryr|r's  z"_TypeAliasGenericAlias.__getitem__)rrrr;rrFrrryryrr|r s rcseZdZdZddedddZeeddfd d Zeed d d Z eed ddZ edddZ e j dkrxd&ddZddZddZddZddZdd Ze j d!krd"d#Zd$d%ZZS)'rCaCreate named, parameterized type aliases. This provides a backport of the new `type` statement in Python 3.12: type ListOrSet[T] = list[T] | set[T] is equivalent to: T = TypeVar("T") ListOrSet = TypeAliasType("ListOrSet", list[T] | set[T], type_params=(T,)) The name ListOrSet can then be used as an alias for the type it refers to. The type_params argument should contain all the type parameters used in the value of the type alias. If the alias is not generic, this argument is omitted. Static type checkers should only support type aliases declared using TypeAliasType that follow these rules: - The first argument (the name) must be a string literal. - The TypeAliasType instance must be immediately assigned to a variable of the same name. (For example, 'X = TypeAliasType("Y", int)' is invalid, as is 'X, Y = TypeAliasType("X", int), TypeAliasType("Y", int)'). ry) type_paramsrc Cst|tstdt|ts$td||_||_d}g}|D]z}t|tttfrXt |rftd|t |dt t k }|r|std|d|rd}t|tr| |q<| |qrrrrz attribute 'z3' of 'typing.TypeAliasType' objects is not writablez0'typing.TypeAliasType' object has no attribute '')rrryryr|rus   z$TypeAliasType._raise_attribute_errorr9cCs|jSrrrzryryr|r}szTypeAliasType.__repr__rrcsT|dkr dS|dkrdSt|tr>dkr>fdd|DSt|djdS)N.rcsg|]}|dqS)r_check_single_paramr  recursionr{ryr|rsz5TypeAliasType._check_single_param.. Subscripting  requires a type.)rrrrr)r{rrryrr|rs  z!TypeAliasType._check_single_paramcs6tjdkr tfdd|DStfdd|DS)Nrc3s|]}|VqdSrrrr/rzryr|rsz2TypeAliasType._check_parameters..c3s$|]}t|djdVqdS)rrN)rrrrrzryr|rs  )rrFrrryrzr|_check_parameterss   zTypeAliasType._check_parameterscCsd|jstdt|ts|f}tjdkr4t||St|}| |}t ||}|j |kr`||_ |S)Nz+Only generic type aliases are subscriptabler) rrrrrrFrrrrrr)r{rZ type_varsrryryr|rs      zTypeAliasType.__getitem__cCs|jSrrrzryryr|rhszTypeAliasType.__reduce__cOs tddS)NzEtype 'typing_extensions.TypeAliasType' is not an acceptable base typerrryryr|r@szTypeAliasType.__init_subclass__cCs tddS)NzType alias is not callablerrzryryr|rXszTypeAliasType.__call__rcCst|s tStj||fSrrrrro)r{rZryryr|r?szTypeAliasType.__or__cCst|s tStj||fSrr)r{rYryryr|r@szTypeAliasType.__ror__)r)rrrrrrrrrHrrr}rrFrrrrhr@rXr?r@rryryrr|rC,s %    )ryr:cCs(t|to&t|ddo&|tk o&|tjk S)aZReturn True if the given type is a Protocol. Example:: >>> from typing_extensions import Protocol, is_protocol >>> class P(Protocol): ... def a(self) -> str: ... ... b: int >>> is_protocol(P) True >>> is_protocol(int) False r"F)rrrr=rrryryr|r7s  cCs6t|st|dt|dr*t|jStt|S)aReturn the set of members defined in a Protocol. Example:: >>> from typing_extensions import Protocol, get_protocol_members >>> class P(Protocol): ... def a(self) -> str: ... ... b: int >>> get_protocol_members(P) frozenset({'a', 'b'}) Raise a TypeError for arguments that are not Protocols. z is not a Protocolr )r7rrrr rrryryr|r4s   c@sLeZdZdZeddddZedddZedd d Ze e d d d Z dS)r+afDefine the documentation of a type annotation using ``Annotated``, to be used in class attributes, function and method parameters, return values, and variables. The value should be a positional-only string literal to allow static tools like editors and documentation generators to use it. This complements docstrings. The string value passed is available in the attribute ``documentation``. Example:: >>> from typing_extensions import Annotated, Doc >>> def hi(to: Annotated[str, Doc("Who to say hi to")]) -> None: ... N) documentationr:cCs ||_dSrr)r{rryryr|rsz Doc.__init__r9cCsd|jdS)NzDoc()rrzryryr|r}sz Doc.__repr__cCs t|jSr)rrrzryryr|rsz Doc.__hash__)rr:cCst|tstS|j|jkSr)rr+rrrryryr|rs z Doc.__eq__) rrrrrrr}r<rrrrryryryr|r+s  CapsuleTypeCAPIrc@seZdZdZdZdZdS)r/rrrtN)rrrVALUE FORWARDREFSTRINGryryryr|r/:s)rglocalseval_strrcs:t|}|r|tjk rtdt|trt|dd}|r`t|dr`|dd}t|tj rdd}nd}d}t|dd}|rt j |d} | rt| dd}t t |} |} nt|tjrt|dd}|j}d} d} nXt|rt|dd}t|dd}d} |} n.t|dr|j}d}} } nt|d|dkr6iSt|t sPt|d |sZiS|s|tjkr~d d |DSt |S| dk rt| d r| j} qt| tjr| j} qqƐqt| dr| j}dkr|dkr| pit|d f} rdd | DBfdd |D} | S)aCompute the annotations dict for an object. obj may be a callable, class, or module. Passing in an object of any other type raises TypeError. Returns a dict. get_annotations() returns a new dict every time it's called; calling it twice on the same object will return two different but equivalent dicts. This is a backport of `inspect.get_annotations`, which has been in the standard library since Python 3.10. See the standard library documentation for more: https://docs.python.org/3/library/inspect.html#inspect.get_annotations This backport adds the *format* argument introduced by PEP 649. The three formats supported are: * VALUE: the annotations are returned as-is. This is the default and it is compatible with the behavior on previous Python versions. * FORWARDREF: return annotations as-is if possible, but replace any undefined names with ForwardRef objects. The implementation proposed by PEP 649 relies on language changes that cannot be backported; the typing-extensions implementation simply returns the same result as VALUE. * STRING: return annotations as strings, in a format close to the original source. Again, this behavior cannot be replicated directly in a backport. As an approximation, typing-extensions retrieves the annotations under VALUE semantics and then stringifies them. The purpose of this backport is to allow users who would like to use FORWARDREF or STRING semantics once PEP 649 is implemented, but who also want to support earlier Python versions, to simply write: typing_extensions.get_annotations(obj, format=Format.FORWARDREF) z8eval_str=True is only supported with format=Format.VALUErNrr rrz% is not a module, class, or callable.z+.__annotations__ is neither a dict nor NonecSs*i|]"\}}|t|tr|nt|qSry)rrrrrrrcryryr|r|sz#get_annotations..rrcSsi|] }|j|qSryr)rrryryr|r|scs,i|]$\}}|t|ts|n t|qSry)rrevalrrgrryr|r|s)r/rrrrrrrrGetSetDescriptorTypermodulesrvarsrrrGr rrrrr partialrr)rrgrrrZobj_dictannZ obj_globals module_namerlZ obj_localsunwraprZ return_valueryrr|r0Cs%                      ownerrgrrc CsP|jr |jSt|dddk rNz |jj}Wntk r<YnXd|_||_|S|dkrbt|dd}|dkrt|dddk rttj|j ddd}|dkrt|dd}|dkrt |t rt|dd}|rtj|d}|rt|dd}n2t |t j rt|dd}nt|rt|dd}|dkr*i}|dkrRi}t |t rR|t||dkrr|dk rrt|dd}|dk rt|}t|}|D]8}|j} tr|jr| |kr||| <|| dq|j} | r.t| s.| |kr|| }n2| |kr|| }ntt| r$tt| St| n|j} t| ||}d|_||_|S) N__cell__TZ __owner____forward_module__rrrr)__forward_evaluated____forward_value__rr cell_contentsrrrrrrrrrrGrrrr_FORWARD_REF_HAS_CLASSrwr__forward_arg__ isidentifierkeyword iskeywordrbuiltins NameError__forward_code__r) forward_refrrgrrrcrrlr param_namer&coderyryr|_eval_with_owners                    rrlrcCslttdrptjdks6dtjddkr2dkrHnntj|||d}qdtjjkrdtj||d }qt|}n&|dkrtdSt|t rt|S|}t t f}|s|t f7}|r|t f7}t|tjrt||krt|d d|ttttttfkr|S|r|t t fkr|St|ttjfs2|t t fkrDtd |d dt|tkrht|d |d d|S)zG A lax Python 3.11+ like version of typing._type_check rr#)rtrrNrtrrrrvrzPlain z Got z.100r1)rrrrFrrVrCrrrrYr=rrrr2rrrrIrHr rBr8r)rcrrrlrtype_invalid_generic_formsryryr|_lax_type_checksV           r)rrgrrr_recursive_guardc Cs|tjkr|jS|j|kr|Szt|||||d}Wn(tk r\|tjkrV|YSYnXd}tsp|j } n|j} t |||j| d} t | t rt | dddk rd}t | ||||||dStjdkr|r|rt|ni}|D]} | j|kr| || j<qtjd krt| ||Stjdkr8tj| ||||jhBd Stjd kr`tj| |||||jhBd Stj| |||||jhB||d S) aEvaluate a forward reference as a type hint. This is similar to calling the ForwardRef.evaluate() method, but unlike that method, evaluate_forward_ref() also: * Recursively evaluates forward references nested within the type hint. * Rejects certain objects that are not valid type hints. * Replaces type hints that evaluate to None with types.NoneType. * Supports the *FORWARDREF* and *STRING* formats. *forward_ref* must be an instance of ForwardRef. *owner*, if given, should be the object that holds the annotations that the forward reference derived from, such as a module, class object, or function. It is used to infer the namespaces to use for looking up names. *globals* and *locals* can also be explicitly given to provide the global and local namespaces. *type_params* is a tuple of type parameters that are in scope when evaluating the forward reference. This parameter must be provided (though it may be an empty tuple) if *owner* is not given and the forward reference does not already have an owner set. *format* specifies the format of the annotation and is a member of the annotationlib.Format enum. rz*Forward references must evaluate to types.)rrrTN)rgrrrrr)rtrDr)recursive_guardr)rrr)r/rrrrrr__forward_is_argument__rwrrrVrr,rrFrrrr) rrrgrrrrrcrrrtvarryryr|r,Ps              )r)rt)NNF)NN)N)N)ry)T(rrr=collections.abcrenumr r5rrrr{rrr__all__ZPEP_560rZ GenericMetarFZ_PEP_696_IMPLEMENTEDrVrCrrxrrrIr rrrrrrrrr8rrr.r6r9rrrrrrrr;r-r( defaultdictrrrr rrrrrrrrrrArGrrrrXrrrrrrrgrrr)rEXCLUDED_ATTRIBUTESrrrr=r!r$r'r(r}r3rYr@r?r#r!r rr"rr$r`Z_NEEDS_SINGLETONMETArarMrdrNrjZ_PEP_728_IMPLEMENTEDrror8 signaturerrrrnrrrr'r5rrrr%rr2r1r ImportErrorrrrBrrrrrr rrrrrr"r%rr&rr)rEr0rFr4rDr5_Finalrr rHrKrLrCrJrErHrrrGrIrVrr r>rdr&r)rnrorRr<rnr*rorrrrrrrrr _prohibitedrrrrrrABCregister memoryview bytearrayrRr3r:rCrrrr7r4rWrr+Z _CapsuleType_socketZ_CAPIrrr0__kwdefaults__Z_PEP_649_OR_749_IMPLEMENTEDIntEnumr/rr,rrrOrPrQrSrTrUrZr[r\r]r^r_r`rarbrcrdrerfrhrirjrkrlrmrprqrrrsryryryr|s8                   (  2      d  5      { g     5 : '=    '   1f   z    /. )(  +         *      >N   "V  %    7 " 0 8  F B       <   "           ~ Y6u