fL i]6UddlmZddlZddlZddlZddlZddlmZddlm Z m Z ddl m Z ddl mZddlmZddlmZdd lmZdd lmZmZmZmZmZmZdd lmZddlZdd lmZdd lm Z ddl!m"Z"ddl#m$Z$ddl%m&Z&ddl'm(Z(m)Z)erddl*m+Z+e,eee,edffZ-edZ.edZ/dZ0Gdde1e.e/fZ2ee-dfZ3erGddee.e/fZ4n GddeZ4edd Z5d!e6d<Gd"d#eZ7 d9d$Z8d:d;d%Z9ijujvZd=d*Z?d>d+Z@d?d,ZAd@d-ZBdAd.ZCed/d ZDd0e6d/<e dBd1ZEdCd2ZFdDd3ZG dEd4ZH dF dGd5ZIdHd6ZJdId7ZKdJd8ZLy)K) annotationsN)ChainMap)IteratorMapping)contextmanager) ContextVar)reduce) zip_longest) prepare_class) TYPE_CHECKING AnnotatedAny TypedDictTypeVarcast)WeakValueDictionary)typing_objects)is_union_origin) _typing_extra) get_type_ref)PydanticRecursiveRef) all_identicalis_model_class) BaseModel.KTVTdc0eZdZefdfd Zdfd ZxZS) LimitedDictc0||_t| yN) size_limitsuper__init__)selfr$ __class__s b/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/pydantic/_internal/_generics.pyr&zLimitedDict.__init__+s$ ct|||t||jkDrOt||jz |jdzz}t |j d|}|D]}||=yy)N )r% __setitem__lenr$listkeys)r'keyvalueexcess to_removekr(s r)r-zLimitedDict.__setitem__/st C' t9t &Y04??b3HHFTYY[)'62I G  'r*)r$intreturnNoner1rr2rr7r8)__name__ __module__ __qualname___LIMITED_DICT_SIZEr&r- __classcell__)r(s@r)r!r!*s);r*r!type[BaseModel]c eZdZy) DeepChainMapN)r:r;r<r*r)rArA>s r*rAc(eZdZdZddZddZddZy) rAzVariant of ChainMap that allows direct updates to inner scopes. Taken from https://docs.python.org/3/library/collections.html#collections.ChainMap, with some light modifications for this use case. cF|jD]}|jyr#)mapsclear)r'mappings r)rFzDeepChainMap.clearJs99   r*c0|jD]}|||< yr#)rE)r'r1r2rGs r)r-zDeepChainMap.__setitem__Ns99 %$  %r*cXd}|jD] }||vs||=d}|s t|y)NFT)rEKeyError)r'r1hitrGs r) __delitem__zDeepChainMap.__delitem__RsAC99 '> C sm#r*N)r7r8r9)r1rr7r8)r:r;r<__doc__rFr-rLrBr*r)rArACs   % $r*_GENERIC_TYPES_CACHE)defaultz$ContextVar[GenericTypesCache | None]c,eZdZUded<ded<ded<y)PydanticGenericMetadatatype[BaseModel] | Noneorigintuple[Any, ...]argsztuple[TypeVar, ...] parametersN)r:r;r<__annotations__rBr*r)rQrQcs "" ##r*rQcFd|ji}|f}t||\}}}|j|||||f|||ddd|} td\} } | rKd} |} tj | jj }| | ur|j| | } | dz } | | ur| S) aNDynamically create a submodel of a provided (generic) BaseModel. This is used when producing concrete parametrizations of generic models. This function only *creates* the new subclass; the schema/validators/serialization must be updated to reflect a concrete parametrization elsewhere. Args: model_name: The name of the newly created model. origin: The base class for the new model to inherit from. args: A tuple of generic metadata arguments. params: A tuple of generic metadata parameters. Returns: The created submodel. r;)rSrUrVF)__pydantic_generic_metadata__#__pydantic_reset_parent_namespace__)depthN_)r;r update_get_caller_frame_infosysmodules__dict__ setdefault) model_namerSrUparams namespacebasesmetanskwds created_model model_modulecalled_globallyobject_by_referencereference_namereference_module_globalss r)create_generic_submodelrqis$".v/@/@ AI IE":u5ND"d R    ' -2   M%;$C!L/"##&;;}/G/G#H#Q#Q !6":"E"EnVc"d  c !N"6 r*c tj|}|j }|j d|j|ufS#t$r}td|d}~wt$rYywxYw)aUsed inside a function to check whether it was called globally. Args: depth: The depth to get the frame. Returns: A tuple contains `module_name` and `called_globally`. Raises: RuntimeError: If the function is not called inside a function. z2This function must be used inside another functionN)NFr:)r` _getframe ValueError RuntimeErrorAttributeError f_globalsgetf_locals)r\previous_caller_framee frame_globalss r)r_r_sr # e 4 *33M   Z (*?*H*HM*Y YY XOPVWW sA A& A A&%A&z type[Any] DictValuesc#4Kt|tr|yt|r|jdEd{yt|tt fr|D]}t |Ed{yt|}|D]}t |Ed{y7\7/7 w)a7Recursively iterate through all subtypes and type args of `v` and yield any typevars that are found. This is inspired as an alternative to directly accessing the `__parameters__` attribute of a GenericAlias, since __parameters__ of (nested) generic BaseModel subclasses won't show up in that list. rVN) isinstancerrrYr}r/iter_contained_typevarsget_args)vvarrUargs r)rrs !W  22<@@@ A D) * 4C.s3 3 3 4{ 4C.s3 3 3 4 A 4 4s33BB.B$B%%B B BBBclt|dd}|r|jdStj|S)NrYrU)getattrrxtyping_extensionsrrpydantic_generic_metadatas r)rrs8@GKjlp@q (,,V44  % %a ((r*clt|dd}|r|jdStj|S)NrYrS)rrxr get_originrs r)rrs8@GKjlp@q (,,X66  ' ' **r*ct|}|yt|dsy|j}|j}t t ||S)zPackage a generic type's typevars and parametrization (if present) into a dictionary compatible with the `replace_types` function. Specifically, this works with standard typing generics and typing._GenericAlias. N__parameters__)rhasattr__args__rdictzip)clsrSrUrVs r)get_standard_typevars_maprsK_F ~ 6+ , LLD&,&;&;J J% &&r*cr|j}|d}|d}|siSttt||S)aePackage a generic BaseModel's typevars and concrete parametrization (if present) into a dictionary compatible with the `replace_types` function. Since BaseModel.__class_getitem__ does not produce a typing._GenericAlias, and the BaseModel generic info is stored in the __pydantic_generic_metadata__ attribute, we need special handling here. rSrU)rYrrr)rgeneric_metadatarSrUs r)get_model_typevars_maprsD88 h 'F F #D  +F3T: ;;r*cs|St|}t|}tj|r|^}}t |}t |g|S|rt fd|D}t||r|S|[t|tjrAt|tjs't|ddtt|j}|Jt|r+td|Drt f}t d|D}t"j$dk\r,|t&j(urt+t,j.|S|t1|dk(r|dS|S|sEt3|r:|j4d }|s|St fd |D}t||r|S||St|t6r)|Dcgc]}t |} }t|| r|S| Sj9||Scc}w) afReturn type with all occurrences of `type_map` keys recursively replaced with their values. Args: type_: The class or generic alias. type_map: Mapping from `TypeVar` instance to concrete types. Returns: A new type representing the basic structure of `type_` with all `typevar_map` keys recursively replaced. Example: ```python from typing import Union from pydantic._internal._generics import replace_types replace_types(tuple[str, Union[list[str], float]], {str: int}) #> tuple[int, Union[list[int], float]] ``` c36K|]}t|ywr# replace_types).0rtype_maps r) z replace_types..s"UC=h#?"UN_namec3FK|]}tj|ywr#)ris_anyrrs r)rz replace_types..,sL#>((-Ls!c3tK|]0}tj|stj|s|2ywr#)r is_noreturnis_neverrs r)rz replace_types..0s4'&2237>;R;RSV;W's68)r[r,rrrVc36K|]}t|ywr#r)rtrs r)rz replace_types..Ds"R!=H#="Rr)rrr is_annotatedrr tuplerrr typing_basertypingrranyrr` version_infotypes UnionTyper operatoror_r.rrYr/rx) type_r type_args origin_typeannotated_typerresolved_type_argsrVelement resolved_lists ` r)rrs*  IU#K"";/'0$&~x@.7;788""U9"UU $6 7L  #5-";";<{M,E,EFw-9 "&%++6K&&& ; 'L9KLL&)V"!&'-'"    w &;%//+I(,,(:; ;C8J4Kq4P-a0iiVhii >%088F L""Rz"RR %7 8L'((%INOgw9O O  .L <<u %%Ps>G5c |jd}t|}i}t}t|||D]\}}||urt d|dt|d|||urot t |} |j} | rt|j|||<h|td|Dz}t d|dt|d |t t |}|||<|S#t$rd} YtwxYw) aReturn a mapping between the parameters of a generic model and the provided arguments during parameterization. Raises: TypeError: If the number of arguments does not match the parameters (i.e. if providing too few or too many arguments). Example: ```python {test="skip" lint="skip"} class Model[T, U, V = int](BaseModel): ... map_generic_model_arguments(Model, (str, bytes)) #> {T: str, U: bytes, V: int} map_generic_model_arguments(Model, (str,)) #> TypeError: Too few arguments for ; actual 1, expected at least 2 map_generic_model_arguments(Model, (str, bytes, int, complex)) #> TypeError: Too many arguments for ; actual 4, expected 3 ``` Note: This function is analogous to the private `typing._check_generic_specialization` function. rV) fillvaluezToo many arguments for z ; actual z , expected Fc3XK|]"}t|dxr|j$yw) has_defaultN)rr)rps r)rz.map_generic_model_arguments..s&#fVWGA}$=$Q!--/$Q#fs(*zToo few arguments for z, expected at least ) rYr.objectr TypeErrorrrrrvr __default__sum) rrUrV expected_len typevars_map_missing parameterargumentparamrs r)map_generic_model_argumentsrVs(.22<@Jz?L')LxH*:txP+ 8  5cU)CI;kZfYghi i x ),E $#//1 '4E4E4E|&T U##f[e#f ff "8Ys4ykQefres tuu),E"*L )+, " $#  $s1C(( C65C6_generic_recursion_cachezContextVar[set[str] | None]c#xKtj}| t}tj|}nd} t||}||vrt |}|n&|j |d|j ||rtj|yy#|rtj|wwxYww)aThis contextmanager should be placed around the recursive calls used to build a generic type, and accept as arguments the generic origin type and the type arguments being passed to it. If the same origin and arguments are observed twice, it implies that a self-reference placeholder can be used while building the core schema, and will produce a schema_ref that will be valid in the final parent schema. N) args_override)type_ref)rrxsetrraddremovereset)rSrUpreviously_seen_type_refstokenr self_types r)generic_recursion_self_typers!9 < < > ($'E!(,,-FG 2d; 0 0,h?IO % ) )( 3  % , ,X 6  $ * *5 1 5 $ * *5 1 s9B:ABB:B77B:cbtj}|s tS|jSr#)rrxrcopy)visiteds r)recursively_defined_type_refsrs&&**,G u <<>r*ctj}|t}tj||jt ||S)aThe use of a two-stage cache lookup approach was necessary to have the highest performance possible for repeated calls to `__class_getitem__` on generic types (which may happen in tighter loops during runtime), while still ensuring that certain alternative parametrizations ultimately resolve to the same type. As a concrete example, this approach was necessary to make Model[List[T]][int] equal to Model[List[int]]. The approach could be modified to not use two different cache keys at different points, but the _early_cache_key is optimized to be as quick to compute as possible (for repeated-access speed), and the _late_cache_key is optimized to be as "correct" as possible, so that two types that will ultimately be the same after resolving the type arguments will always produce cache hits. If we wanted to move to only using a single cache key per type, we would either need to always use the slower/more computationally intensive logic associated with _late_cache_key, or would need to accept that Model[List[T]][int] is a different type than Model[List[T]][int]. Because we rely on subclass relationships during validation, I think it is worthwhile to ensure that types that are functionally equivalent are actually equal. )rNrxGenericTypesCacher_early_cache_key)parenttypevar_valuesgeneric_types_caches r)get_cached_generic_type_earlyrsJ"/224"/1  !45  " "#3FN#K LLr*ctj}|t}tj||jt |||}|t ||||||S)zkSee the docstring of `get_cached_generic_type_early` for more information about the two-stage cache lookup.)rNrxrr_late_cache_keyset_cached_generic_type)rrrSrUrcacheds r)get_cached_generic_type_laterse/224#/1  !45 $ $_VT>%R SF M Mr*ctj}|t}tj|||t ||<t |dk(r||t ||d<|r|r||t |||<yyy)zSee the docstring of `get_cached_generic_type_early` for more information about why items are cached with two different keys. Nrr)rNrxrrrr.r)rrrrSrUrs r)rrs/224#/1  !45DI(@A >aKP,V^A5FGH $MROFD.IJvr*ct|trtd|DStjt j |r t |Sy)aThis is intended to help differentiate between Union types with the same arguments in different order. Thanks to caching internal to the `typing` module, it is not possible to distinguish between List[Union[int, float]] and List[Union[float, int]] (and similarly for other "parent" origins besides List) because `typing` considers Union[int, float] to be equal to Union[float, int]. However, you _can_ distinguish between (top-level) Union[int, float] vs. Union[float, int]. Because we parse items as the first Union type that is successful, we get slightly more consistent behavior if we make an effort to distinguish the ordering of items in a union. It would be best if we could _always_ get the exact-correct order of items in the union, but that would require a change to the `typing` module itself. (See https://github.com/python/cpython/issues/86483 for reference.) c32K|]}t|ywr#_union_orderings_key)rr2s r)rz'_union_orderings_key..sMU)%0MsrB)rrris_unionrrr)rs r)rrsG.%(MnMMM  !2!=!=n!M N''r*c||t|fS)aThis is intended for minimal computational overhead during lookups of cached types. Note that this is overly simplistic, and it's possible that two different cls/typevar_values inputs would ultimately result in the same type being created in BaseModel.__class_getitem__. To handle this, we have a fallback _late_cache_key that is checked later if the _early_cache_key lookup fails, and should result in a cache hit _precisely_ when the inputs to __class_getitem__ would result in the same type. r)rrs r)rr s  4^ D DDr*ct|||fS)aThis is intended for use later in the process of creating a new type, when we have more information about the exact args that will be passed. If it turns out that a different set of inputs to __class_getitem__ resulted in the same inputs to the generic type creation process, we can still return the cached type, and update the cache with the _early_cache_key as well. r)rSrUrs r)rrs  / ==r*) rdstrrSr?rUrTrerTr7r?)r)r\r6r7ztuple[str | None, bool])rrr7zIterator[TypeVar])rrr7r)rrr7zdict[TypeVar, Any] | None)rr?r7dict[TypeVar, Any])rrrzMapping[TypeVar, Any] | Noner7r)rr?rUrTr7r)rSr?rUrTr7z%Iterator[PydanticRecursiveRef | None])r7zset[str])rr?rrr7rR) rr?rrrSr?rUrTr7rR)NN) rr?rrTrr?rSrRrUztuple[Any, ...] | Noner7r8)rrr7r)rr?rrr7GenericTypesCacheKey)rSr?rUrTrrr7r)M __future__rrr`rr collectionsrcollections.abcrr contextlibr contextvarsr functoolsr itertoolsr r r r rrrrweakrefrrtyping_inspectionrtyping_inspection.introspectionrr _core_utilsr _forward_refr_utilsrrmainrrrrrr=rr!rrArNrWrQrqr_valuesr(r}rrrrrrrrrrrrrrrrrBr*r)rs;" -%"!JJ',;%.1 S#uS#X67 T] T] $r2v,  ((<>O(OP xB' $x$:>HH^hl=m:m$i$ ,,,,4C,M\,,^Z, -- I-4&)+'"<$^&B2j9CC]gk8l5l2 2#22*22>M0   -0 :I Q`  (&*#' S S#S S # S ! S  S.* E >r*