U kfB @sUdZddlmZddlZddlZddlmZddlZddlZddl Z ddl Z ddl Z ddl Z ddl Z ddlZddlmZddlmZddlmZddlmZdd lmZdd lmZdd lmZdd lmZdd lmZddlmZddlmZddlmZddlmZddlmZddlmZddlmZddlm Z ddlm!Z!ddlm"Z"ddlm#Z#ddl$Z$ddl%m&Z&ddl%m'Z'ddl(m)Z)ddlm*Z*ddl%m+Z+e"d Z,e"d!d"d#Z-e"d$ed%efd&Z.e"d'd(d&Z/e"d)d*d&Z0e"d+d,d&Z1e"d-d.d&Z2e'j3rd/d0d1d2d3Z4nd/d0d1d4d3Z4d/d5d6d7d8Z5Gd9d:d:Z6d;dd?Z7d/d5d@dAdBZ8d6dCdDd5dEdFdGZ9dHdIdJdKdLdMZ:dNdOdPdQdRZ;dSd5dTdUdVdWZdId_d`dadbZ?dcddZ@dedfd5dIdgdhdiZAe"djZBe"dkZCGdldmdmZDdndoZEedd%dpdqdrdsdtdudvdwZFeddxdpdqdrdJdrdudydwZFddxdpdqdrdJdrdudzdwZFdId{d|d}d~ZGd7dIdJdJddddZHd8ddJddddZId9ddZJd:dCd5d5dSdSdSdSddddZKddZLddZMd;d/dddSd5dddZNGdddZOddZPddZQddfd5dCdJddddd„Zfd/dCdOdÜddńZgd d;d/d/d dƜddȄZhddʜdd̄Zid?d/dddΜddЄZjd/dd5d/dҜddԄZkddքZlGdd؄de[ZmGddڄdee,ZnGdd܄dee,ZoGddބdee,ZpGdddeqZrGdddesZtGdddetdZue!rBddlmvZvevZwneuZwe"dejxd&Zyd@d/dd5dJddddZzda{d/ddddZ|dId/d/d/dddZ}dAddZ~GdddeZdBd5dDddddZd5dddddZiZded<d5dddddZe dZdCdddYdd d d Zd dJd dddZe dZe dZeefd{ddd{dddZesdZddZe dZGdddZGdddZddZd d!Zd/d5dd"d#d$Zd5d5dd%d&ZdDd5dYd5d'd(d)Ze d*Zd5d+d5d,d-d.Zd{dDd/d0d1ZdDd2d3ZGd4d5d5ejxZejZe#e,e*ejfZdS(EzRoutines to help with the creation, loading and introspection of modules, classes, hierarchies, attributes, functions, and methods. ) annotationsNupdate_wrapper)CodeType)Any)Callable)cast)Dict) FrozenSet)Generic)Iterator)List)Mapping)NoReturn)Optional)overload)Sequence)Set)Tuple)Type) TYPE_CHECKING)TypeVar)Union) _collections)compat)HAS_CYEXTENSION)Literal)exc_T_T_coT) covariant_F.)bound_MPzmemoized_property[Any]_MAz#HasMemoized.memoized_attribute[Any]_HPzhybridproperty[Any]_HMzhybridmethod[Any]rMapping[str, Any]objreturncCs t|SN)inspectget_annotationsr+r1K/opt/hc_python/lib64/python3.8/site-packages/sqlalchemy/util/langhelpers.pyr/Asr/cCsBt|tr|jdd}n t|dd}|dkr4tjStd|SdS)N__annotations__r)) isinstancetype__dict__getgetattrr EMPTY_DICTr)r+annr1r1r2r/Fs   str)xr,cCs*|d}t}||tt|S)Nzutf-8)encoderZmd5_not_for_securityupdaterr; hexdigest)r<mr1r1r2md5_hexWs  rAc@s@eZdZUdZdZded<ddddZd d d d d ddZdS) safe_reraiseaReraise an exception after invoking some handler code. Stores the existing exception info before invoking so that it is maintained across a potential coroutine context switch. e.g.:: try: sess.commit() except: with safe_reraise(): sess.rollback() TODO: we should at some point evaluate current behaviors in this regard based on current greenlet, gevent/eventlet implementations in Python 3, and also see the degree to which our own asyncio (based on greenlet also) is impacted by this. .rollback() will cause IO / context switch to occur in all these scenarios; what happens to the exception context from an "except:" block if we don't explicitly store it? Original issue was #2703. ) _exc_infozfUnion[None, Tuple[Type[BaseException], BaseException, types.TracebackType], Tuple[(None, None, None)]]rCNoner,cCst|_dSr-)sysexc_inforCselfr1r1r2 __enter__szsafe_reraise.__enter__zOptional[Type[BaseException]]zOptional[BaseException]zOptional[types.TracebackType]r)type_value tracebackr,cCs`|jdk st|dkr@|j\}}}|dk s.td|_||nd|_|dk sRt||dSr-)rCAssertionErrorwith_traceback)rIrKrLrMexc_type exc_valueexc_tbr1r1r2__exit__s    zsafe_reraise.__exit__N)__name__ __module__ __qualname____doc__ __slots__r3rJrSr1r1r1r2rB^s  rBzType[_T]zIterator[Type[_T]])clsr,ccsHt}|g}|rD|}||kr$q n |||||Vq dSr-)setpopaddextend__subclasses__)rYseenstackr1r1r2walk_subclassess ra)elementr,cCs:t|tr|Sz t|WStk r4d|YSXdS)Nzunprintable element %r)r4r; Exception)rbr1r1r2string_or_unprintables   rdz Type[Any] Optional[str])rYuse_namer,cCs&|p|j}dddtd|DS)N css|]}|VqdSr-)lower).0nr1r1r2 sz(clsname_as_plain_name..z([A-Z][a-z]+|SQL))rTjoinrefindall)rYrfnamer1r1r2clsname_as_plain_names rpzUnion[Type[Any], object]Callable[..., Any]bool)instance_or_clsagainst_methodr,cCs.t|ts|j}n|}|j}t||}||kS)z1Return True if the two class methods don't match.)r4r5 __class__rTr8)rsrtZ current_cls method_nameZcurrent_methodr1r1r2method_is_overriddens   rwslicezTuple[Any, ...])slcr,cCs>g}|j|j|jfD] }t|dr*|}||qt|S)zrdecode a slice object as sent to __getitem__. takes into account the 2.5 __index__() method, basically. __index__)startstopstephasattrrzappendtuple)ryretr<r1r1r2 decode_slices   rz Sequence[str]z Iterator[str])usedbasesr,c'sht|}|D]Vtftfddtd}|D] }||kr4|||Vq q4tdq dS)Ncs t|Sr-r;)ibaser1r2z!_unique_symbols..iz&exhausted namespace for symbol base %s)rZ itertoolschainmapranger\ NameError)rrZused_setpoolsymr1rr2_unique_symbolss rzCallable[[int], Any]intz Iterator[Any])fnrjr,ccs*|r&||d@}||V||N}qdS)z6Call the given function given each nonzero bit from n.rNr1)rrjbr1r1r2map_bitss r_FnzCallable[[_Fn], _Fn])targetr,csdddfdd }t|S)z'A signature-matching decorator factory.rrr,c sNt|st|stdt|}i}t||}ttd|dtd|dd|j f}t |dd\}}t ||d}| t |d d |j |d <t|rd |d <d|d<nd|d <d|d<dt|dkrd|}nd|}tj|j}| t|| |||d|jittjt|||j } t|d|j| _|| _t| |S)Nznot a decoratable functionzTuple[str, ...]rrrr)rrFgroupedrozasync prefixzawait Z target_prefix__zf%(prefix)sdef %(name)s%(grouped_args)s: return %(target_prefix)s%(target)s(%(fn)s, %(apply_pos)s) ze%(prefix)sdef %(name)s%(grouped_args)s: return %(target_prefix)s%(target)s(%(fn)s, %(apply_kw)s) rT__func__)r. isfunctionismethodrcrinspect_getfullargspec!_update_argspec_defaults_into_envrrrTrdictr>format_argspec_plusiscoroutinefunctionreprrFmodulesrUvarstypes FunctionType_exec_code_in_envr8 __defaults__ __wrapped__r) rspecenvnamesZ targ_namefn_namemetadatacodemodZ decoratedrr1r2decoratesN          zdecorator..decorater)rrr1rr2 decoratorsArcCs||jrtg}d}|jD]@}t|jdkrJd|}|||<|||d7}q||qt|}t||d<tj|S|SdS)zCgiven a FullArgSpec, convert defaults to be symbol names in an env.r)builtins __builtin__zx%drrN)defaultsr5rUrlistrr FullArgSpec)rrZ new_defaultsrargroelemr1r1r2r=s      rzUnion[str, types.CodeType]Dict[str, Any])rrrr,cCst||||Sr-)exec)rrrr1r1r2rRs r_PF_TEc@sJeZdZddddddZddZdd d d d Zdddd dddZdS) PluginLoaderNr;zOptional[Callable[..., Any]])groupauto_fncCs||_i|_||_dSr-)rimplsr)rIrrr1r1r2__init__^szPluginLoader.__init__cCs|jdSr-)rclearrHr1r1r2reszPluginLoader.clearr)ror,cCs||jkr|j|S|jr:||}|r:||j|<|St|jD]&}|j|krF|j|j|<|SqFtd|j|fdS)NzCan't load plugin: %s:%s) rrrZimportlib_metadata_getrroloadrZNoSuchModuleError)rIroloaderimplr1r1r2rhs       zPluginLoader.loadrD)ro modulepathobjnamer,csfdd}||j|<dS)Ncs4t}dddD]}t||}qt|S)N.r) __import__splitr8)rtokenrrr1r2r|s z#PluginLoader.register..load)r)rIrorrrr1rr2register{szPluginLoader.register)N)rTrUrVrrrrr1r1r1r2r]s rcCsnz tj}Wn2tk r<t|}|dt|dfYSX|j}|j}t|j d|t|j |@fSdS)Nrr) r.CO_VARKEYWORDSAttributeErrorrrrr__code__ co_argcountr co_varnamesco_flags)rZco_varkeywordsrconargsr1r1r2_inspect_func_argss   r)_setraiseerrr5zOptional[Set[str]]z Literal[True]zSet[str])rYrrr,cCsdSr-r1rYrrr1r1r2get_cls_kwargssrFcCsdSr-r1rr1r1r2rsc Cs|dk}|rt}|dk st|jdd}|oHt|tjoHt|jtj}|rt |\}}| ||s|s|rt d|dqdSnd}|r|r|j D]}t ||ddkrqq|d|S)aeReturn the full set of inherited kwargs for the given `cls`. Probes a class's __init__ method, collecting all named arguments. If the __init__ defines a \**kwargs catch-all, then the constructor is presumed to pass along unrecognized keywords to its base classes, and the collection process is repeated recursively on each of the bases. Uses a subset of inspect.getfullargspec() to cut down on method overhead, as this is used within the Core typing system to create copies of type objects which is a performance-sensitive operation. No anonymous tuple arguments please ! NrFz given cls z doesn't have an __init__ method)rrI)rZrNr6r7r4rrrrrr> TypeError __bases__rdiscard) rYrrtoplevelZctrZhas_initrZhas_kwcr1r1r2rs4        z List[str]funcr,cCst|dS)zReturn the set of legal kwargs for the given `func`. Uses getargspec so is safe to call for methods, functions, etc. r)rrrr1r1r2get_func_kwargssrzcompat.FullArgSpec)rno_self_is_initr,c CsDt|rtd|n&t|rn|rb|rbt|}t|jdd|j|j |j |j |j |j St|Snt|r|r|s|jrt|j}t|jdd|j|j |j |j |j |j St|jSntt|rt|j|ddSt|drt|jSt|dr4t|jr&t|j|dStd |n td |dS) zReturn the argument signature for any callable. All pure-Python callables are accepted, including functions, methods, classes, objects with __call__; builtins and other edge cases like functools.partial() objects raise a TypeError. zCan't inspect builtin: %srNT)rrr__call__)rzCan't inspect callable: %s)r. isbuiltinrrrrrargsvarargsvarkwr kwonlyargskwonlydefaultsrr__self__risclassget_callable_argspecrr~r)rrrrr1r1r2rsR             rz-Union[Callable[..., Any], compat.FullArgSpec]zDict[str, Optional[str]])rrr,c Cst|rt|}n|}tj|}t|d|d|dd|d}|dr|dd}t|ddd|d|dd|d}n"|drd|d}|}nd}|}d}|dr|tttt|d7}|dr|t|d7}|d|d}|r |d|d} nd} tj||d|d| d d d } |drdtj|dd|d|d| d d d } n| } |rt|||| || d St|||dd| dd|dd| ddd SdS)aReturns a dictionary of formatted, introspected function arguments. A enhanced variant of inspect.formatargspec to support code generation. fn An inspectable callable or tuple of inspect getargspec() results. grouped Defaults to True; include (parens, around, argument) lists Returns: args Full inspect.formatargspec for fn self_arg The name of the first positional argument, varargs[0], or None if the function defines no positional arguments. apply_pos args, re-written in calling rather than receiving syntax. Arguments are passed positionally. apply_kw Like apply_pos, except keyword-ish args are passed as keywords. apply_pos_proxied Like apply_pos but omits the self/cls argument Example:: >>> format_argspec_plus(lambda self, a, b, c=3, **d: 123) {'grouped_args': '(self, a, b, c=3, **d)', 'self_arg': 'self', 'apply_kw': '(self, a, b, c=c, **d)', 'apply_pos': '(self, a, b, c, **d)'} rrrNz%s[0]rr1cSs dt|SN=rr<r1r1r2rsrz%format_argspec_plus..) formatvaluecSs dt|Srrrr1r1r2r|r) grouped_argsself_arg apply_posapply_kwapply_pos_proxiedapply_kw_proxied) callablerrinspect_formatargspeclenrrrr) rrrrrrr num_defaultsZ name_argsZdefaulted_valsrrr1r1r2r s$           rcCs||tjkr(d}|rdnd}|r"dnd}n@zt||dWStk rfd}|rR|nd}|r^dnd }YnXtd|||||d S) a format_argspec_plus with considerations for typical __init__ methods Wraps format_argspec_plus with error handling strategies for typical __init__ cases:: object.__init__ -> (self) other unreflectable (usually C) -> (self, *args, **kwargs) z(self)rIz()rrz(self, *args, **kwargs)zself, *args, **kwargsz(*args, **kwargs)z*args, **kwargs)rrrrrr)objectrrrr)methodrrrZproxiedr1r1r2format_argspec_inits$   r r1zCallable[[_T], _T]) target_clstarget_cls_sphinx_nameproxy_cls_sphinx_name classmethodsmethods attributesuse_intermediate_variabler,cCs dd}|S)aSA class decorator indicating attributes should refer to a proxy class. This decorator is now a "marker" that does nothing at runtime. Instead, it is consumed by the tools/generate_proxy_methods.py script to statically generate proxy methods and attributes that are fully recognized by typing tools such as mypy. cSs|Sr-r1)rYr1r1r2rsz&create_proxy_methods..decorater1)r r r rrrrrr1r1r2create_proxy_methodssrcCsTz t|WStk rN|tjkr8dgdddfYSdgdddfYSYnXdS)zinspect.getargspec with considerations for typical __init__ methods Wraps inspect.getargspec with error handling for typical __init__ cases:: object.__init__ -> (self) other unreflectable (usually C) -> (self, *args, **kwargs) rINrkwargs)rrrrr)r r1r1r2getargspec_inits   rcCs t|tjr|js|jS|SdS)zSAdjust the incoming callable such that a 'self' argument is not required. N)r4r MethodTyperr)Z func_or_clsr1r1r2unbound_method_to_callablesrzSequence[Tuple[str, Any]]z%Optional[Union[object, List[object]]])r+ additional_kw to_inspect omit_kwargr,c sV|dkrg}n t|}tg}t}d}t|D]\}}zt|j} Wntk rhYq8Yq8X| j rzt | j nd} |dkr| j r| j }| r| | j d| q| | j ddn$|fdd| j d| D| r8| j st|ddt| j | d| j Dq8g} | fdd|D|dk rlt|rl| d dt|D|D]f\} } | |krqtz6t| }|k r|| kr| d | |fWntk rYnXqt|r@|D]X\} } z6t| }|k r"|| kr"| d | |fWntk r:YnXqd jjd | fS) z}Produce a __repr__() based on direct association of the __init__() specification vs. same-named attributes present. Nrrcsg|] }|fqSr1r1rir)missingr1r2 sz generic_repr..cSsg|]\}}||fqSr1r1)rirdefaultr1r1r2rsc3s|]}tt|dVqdSr-)rr8rr0r1r2rkszgeneric_repr..cSsg|] }t|qSr1r)rivalr1r1r2r!sz%s=%rz%s(%s), )rto_listr OrderedDict enumeraterrrrrrrr]rr>rNzipr~r8itemsrrcrurTrl)r+rrrZpos_argsZkw_argsZvargsrZinsprZ default_lenoutputrZdefvalrr1)rr+r2 generic_reprsl          r'c@s6eZdZdZdZddZddZd dd Zd d Zd S)portable_instancemethodz_Turn an instancemethod into a (parent, name) pair to produce a serializable callable. )rror __weakref__cCs|j|j|jdS)Nrrorr*rHr1r1r2 __getstate__Asz$portable_instancemethod.__getstate__cCs&|d|_|d|_|dd|_dS)Nrrorr1)rror7r)rIstater1r1r2 __setstate__Hs  z$portable_instancemethod.__setstate__r1cCs|j|_|j|_||_dSr-)rrrTror)rImethrr1r1r2rMsz portable_instancemethod.__init__cOs ||jt|j|j||Sr-)r>rr8rro)rIrkwr1r1r2rRs z portable_instancemethod.__call__N)r1) rTrUrVrWrXr+r-rrr1r1r1r2r(9s  r(cs|ht|j}|r|}fdd|jD}|D]}|||q4|jdkst|dsdqfddt|t s| n| |DD]}|||qqtS)a'Return an unordered sequence of all classes related to cls. Traverses diamond hierarchies. Fibs slightly: subclasses of builtin types are not returned. Thus class_hierarchy(class A(object)) returns (A, object), not A plus every class systemwide that derives from object. c3s|]}|kr|VqdSr-r1ri_Zhierr1r2rkfsz"class_hierarchy..rr^csg|]}|kr|qSr1r1r0r2r1r2rosz#class_hierarchy..) r__mro__r[rrr\rUr~ issubclassr5r^)rYprocessrrrsr1r2r2class_hierarchyWs$       r7ccs@t|}|D].}|jD]"}||jkr||j|fVq qq dS)ziterate all the keys and attributes associated with a class, without using getattr(). Does not use getattr() so that class-sensitive descriptors (i.e. property.__get__()) are not called. N)dirr3r6)rYkeyskeyrr1r1r2iterate_attributes}s   r; self.proxyc s<|r |}n$dkrdfddt|D}|D]}z4t||}t|dsRWq2t|d|}ttj|} Wntk rYq2YnXz2t| } t | d} t | ddd} Wnt k rd } d } YnXd t } |dk r||ipi}t | |z| j ||_ Wntk r$YnXt|||q2dS) z9Automates delegation of __specials__ for a proxying type.N)rX__del____getattribute__Z __metaclass__r+r-cs6g|].}|dr|drt|s|kr|qS)r) startswithendswithr~rir@into_clsskipr1r2rs    z0monkeypatch_proxied_specials..rrrrz(self, *args, **kw)z (*args, **kw)z?def %(method)s%(fn_args)s: return %(name)s.%(method)s%(d_args)s)r8r8r~rrrrrrrrlocalsrrsetattr)rCZfrom_clsrDonlyroZ from_instanceZdundersr Zmaybe_fnrrZfn_argsZd_argspyrr1rBr2monkeypatch_proxied_specialssF          rIcCst|d|t|d|kS)z;Return True if the two methods are the same implementation.r)r8)Zmeth1Zmeth2r1r1r2methods_equivalents  rJc Csp|s|stdt|tr(t||r(|St|p>ddt|D}tt|}tj}t|trd|}n|svt}tj}nt|}||||r|St|t s|tjkrdpd}td||d |fGdd d }|rd |j |_ t} t |D]R\} } | |krtd | t | s*td | | ft|| t| | | q|| |rV|Std d || dS)aEnsure basic interface compliance for an instance or dict of callables. Checks that ``obj`` implements public methods of ``cls`` or has members listed in ``methods``. If ``required`` is not supplied, implementing at least one interface method is sufficient. Methods present on ``obj`` that are not in the interface are ignored. If ``obj`` is a dict and ``dict`` does not meet the interface requirements, the keys of the dictionary are inspected. Keys present in ``obj`` that are not in the interface will raise TypeErrors. Raises TypeError if ``obj`` does not meet the interface criteria. In all passing cases, an object with callable members is returned. In the simple case, ``obj`` is returned as-is; if dict processing kicks in then an anonymous class is returned. obj A type, instance, or dictionary of callables. cls Optional, a type. All public methods of cls are considered the interface. An ``obj`` instance of cls will always pass, ignoring ``required``.. methods Optional, a sequence of method names to consider as the interface. required Optional, a sequence of mandatory implementations. If omitted, an ``obj`` that provides at least one interface method is considered sufficient. As a convenience, required may be a type, in which case all public methods of the type are required. z2a class or collection of method names are requiredcSsg|]}|ds|qS)r1)r?rAr1r1r2rs z as_interface..zany ofzall ofz%r does not implement %s: %sr c@seZdZdZdS)z(as_interface..AnonymousInterfacezA callable-holding shell.NrTrUrVrWr1r1r1r2AnonymousInterfacesrLZ Anonymousz%r: unknown in this interfacez%r=%r is not callablez,dictionary does not contain required keys %sN)rr4r5rZr8operatorgegt intersectionrrlrTdictlike_iteritemsrrF staticmethodr\) r+rYrrequiredZ interfaceZ implementedZcompliesZ qualifierrLfoundr rr1r1r2 as_interfacesP!          rU_GFDzgeneric_fn_descriptor[Any]c@seZdZUdZded<ded<ded<d$ddd d d Zed d dd dddZeddddddZd ddddddZerddd dddZ dd dddZ dd ddd Z e ddd d!d"d#Z dS)%generic_fn_descriptoragDescriptor which proxies a function when the attribute is not present in dict This superclass is organized in a particular way with "memoized" and "non-memoized" implementation classes that are hidden from type checkers, as Mypy seems to not be able to handle seeing multiple kinds of descriptor classes used for the same attribute. zCallable[..., _T_co]fgetrerWr;rTNrXdoccCs||_|p|j|_|j|_dSr-rXrWrTrIrXrZr1r1r2r@s zgeneric_fn_descriptor.__init__rVrDrrIr+rYr,cCsdSr-r1rIr+rYr1r1r2__get__Eszgeneric_fn_descriptor.__get__rr!r+rYr,cCsdSr-r1r^r1r1r2r_HszUnion[_GFD, _T_co]cCs tdSr-NotImplementedErrorr^r1r1r2r_KsinstancerLr,cCsdSr-r1rIrdrLr1r1r2__set__Przgeneric_fn_descriptor.__set__rdr,cCsdSr-r1)rIrdr1r1r2 __delete__Rrz generic_fn_descriptor.__delete__r*cCs tdSr-rarIr+r1r1r2_resetTszgeneric_fn_descriptor._reset)r+ror,cCs tdSr-rarYr+ror1r1r2resetWszgeneric_fn_descriptor.reset)N)rTrUrVrWr3rrr_rrfrhrj classmethodrlr1r1r1r2rW1s  rWc@seZdZdZesddZdS)_non_memoized_propertyza plain descriptor that proxies a function. primary rationale is to provide a plain attribute that's compatible with memoized_property which is also recognized as equivalent by mypy. cCs|dkr |S||Sr-rXr^r1r1r2r_gsz_non_memoized_property.__get__N)rTrUrVrWrr_r1r1r1r2rn\srnc@s0eZdZdZesddZddZeddZdS) _memoized_propertyz2A read-only @property that is only evaluated once.cCs&|dkr |S|||j|j<}|Sr-)rXr6rTrIr+rYresultr1r1r2r_rsz_memoized_property.__get__cCst||jdSr-)rprlrTrir1r1r2rjxsz_memoized_property._resetcCs|j|ddSr-)r6r[rkr1r1r2rl{sz_memoized_property.resetN) rTrUrVrWrr_rjrmrlr1r1r1r2rpms rprcsfdd}t|S)zDecorate a method memoize its return value. Best applied to no-arg methods: memoization is not sensitive to argument values, and will always return the same value even when called with different arguments. cs<|f||fdd}j|_j|_||jj<S)NcsSr-r1ar/rrr1r2memosz6memoized_instancemethod..oneshot..memo)rTrWr6rIrr/rvrrur2oneshots   z(memoized_instancemethod..oneshotr)rryr1rxr2memoized_instancemethods rzc@s~eZdZUdZesdZeZded<ddddZ ddd d Z d d dd ddZ Gddde e ZedddddZdS) HasMemoizedzA mixin class that maintains the names of memoized elements in a collection for easy cache clearing, generative, etc. r1zFrozenSet[str]_memoized_keysrDrEcCs|jD]}|j|dqdSr-)r|r6r[rIrr1r1r2_reset_memoizationss zHasMemoized._reset_memoizationscCs|jD]}||jkstqdSr-)r|r6rNr}r1r1r2_assert_no_memoizationss z#HasMemoized._assert_no_memoizationsr;r)r:rLr,cCs||j|<|j|hO_dSr-)r6r|)rIr:rLr1r1r2_set_memoized_attributes z#HasMemoized._set_memoized_attributec@sreZdZUdZded<ded<ded<dddd d d Zed d dd dddZeddddddZddZdS)zHasMemoized.memoized_attributezTA read-only @property that is only evaluated once. :meta private: Callable[..., _T]rXrerWr;rTNrYcCs||_|p|j|_|j|_dSr-r[r\r1r1r2rs z'HasMemoized.memoized_attribute.__init__r&rDrr]cCsdSr-r1r^r1r1r2r_sz&HasMemoized.memoized_attribute.__get__r r`cCsdSr-r1r^r1r1r2r_scCs8|dkr |S|||j|j<}|j|jhO_|Sr-)rXr6rTr|rqr1r1r2r_s )N)rTrUrVrWr3rrr_r1r1r1r2memoized_attributes rr#rcs"dddddfdd }t|S)zMDecorate a method memoize its return value. :meta private: r)rIrr/r,csN|f||fdd}j|_j|_||jj<|jjhO_S)NcsSr-r1rsrur1r2rvszBHasMemoized.memoized_instancemethod..oneshot..memo)rTrWr6r|rwrxrur2rys  z4HasMemoized.memoized_instancemethod..oneshotr)rYrryr1rxr2rzs z#HasMemoized.memoized_instancemethodN)rTrUrVrWrrX frozensetr|r3r~rrmemoized_propertyr rrmrzr1r1r1r2r{s r{c@s,eZdZdZdZddZddddd Zd S) MemoizedSlotszApply memoized items to an object using a __getattr__ scheme. This allows the functionality of memoized_property and memoized_instancemethod to be available to a class using __slots__. r1cCs t|dSr-)r)rIr:r1r1r2_fallback_getattrszMemoizedSlots._fallback_getattrr;r)r:r,csdsdrtn|tjdrRtd}t||Stjdrtdfdd}j|_|SSdS)NZ_memoized_attr_Z_memoized_method_cs6||fdd}j|_j|_t|S)NcsSr-r1rsrur1r2rv%sz8MemoizedSlots.__getattr__..oneshot..memo)rTrWrF)rr/rvrr:rIrur2ry"s    z*MemoizedSlots.__getattr__..oneshot)r?rr~rur8rFrWr)rIr:rLryr1rr2 __getattr__s   zMemoizedSlots.__getattr__N)rTrUrVrWrXrrr1r1r1r2rsrcCsBt|tr:|}|dkr"dS|dkr.dStd|t|S)N)trueyesonyt1T)falsenooffrjf0FzString is not true/false: %r)r4r;striprh ValueErrorrrr0r1r1r2asbool4s   rz!Callable[[str], Union[str, bool]])textr,csdddfdd }|S)zqReturn a callable that will evaluate a string as boolean, or one of a set of "alternate" string values. r;zUnion[str, bool]r*cs|kr |St|SdSr-)rr0rr1r2 bool_or_valueFsz"bool_or_str..bool_or_valuer1)rrr1rr2 bool_or_str@sr Optional[int])rLr,cCs|dkr |St|S)zCoerce to integer.N)r)rLr1r1r2asintOsrzOptional[Dict[str, Any]]rD)r/r:rK flexi_booldestr,cCsj|dkr |}||krft|tr,t|||sf||dk rf|tkrV|rVt||||<n|||||<dS)zIf 'key' is present in dict 'kw', coerce its value to type 'type\_' if necessary. If 'flexi_bool' is True, the string '0' is considered false when coercing to boolean. N)r4r5rrr)r/r:rKrrr1r1r2coerce_kw_typeWs    rr`cs$t|}|ftfdd|DS)zbProduce a tuple structure that is cacheable using the __dict__ of obj to retrieve values c3s&|]}|jkr|j|fVqdSr-r6rikr0r1r2rkws z"constructor_key..)rr)r+rYrr1r0r2constructor_keyqsr)r+rYrr/r,cs0t|}|fdd||D|||S)zInstantiate cls using the __dict__ of obj as constructor arguments. Uses inspect to match the named arguments of ``cls``. c3s&|]}|jkr|j|fVqdSr-rrr0r1r2rks z#constructor_copy..)rr> difference)r+rYrr/rr1r0r2constructor_copy|s rzCallable[[], int]rEcs$ttdfdd}|S)z%Return a threadsafe counter function.rc s$tW5QRSQRXdSr-)nextr1counterlockr1r2_nextszcounter.._next) threadingLockrcount)rr1rr2rs rzOptional[Type[Any]])specimenrr,cCst|dr*|jdk r$t|jtr$tS|jSt|tr8tnt}||trJtS||trXtS||trftSt|drttSt|drtSt|drtS|SdS)zGiven an instance or class, guess if it is or is acting as one of the basic collection types: list, set and dict. If the __emulates__ property is present, return that preferentially. __emulates__Nrr\rZ)r~rr4rZr4r5rr)rrZisar1r1r2duck_type_collections*        rz'Union[Tuple[Type[Any], ...], Type[Any]])rargtyperor,cCs^t||r|St|trBtd|ddd|Dt|fntd||t|fdS)Nz8Argument '%s' is expected to be one of type %s, got '%s'z or css|]}d|VqdS)z'%s'Nr1)rirtr1r1r2rksz"assert_arg_type..z6Argument '%s' is expected to be of type '%s', got '%s')r4rr ArgumentErrorrlr5)rrror1r1r2assert_arg_types   rcstdrtStdtdddkr>tdtdr\fdd}|Std rtfd d DStddS) z?Return a (key, value) iterator for almost any dict-like object.r% __getitem__r7NzObject '%r' is not dict-likeiterkeysc3s,D]}dk st||fVqdSr-)rrN)r:dictlikegetterr1r2iterators  z$dictlike_iteritems..iteratorr9c3s|]}||fVqdSr-r1)rir:)rr1r2rksz%dictlike_iteritems..)r~rr%r8riterr9)rrr1rr2rQs     rQcsHeZdZUdZded<ddddfdd Zd dd dd d d ZZS) classpropertyaAA decorator that behaves like @property except that operates on classes rather than instances. The decorator is currently special when using the declarative module, but note that the :class:`~.sqlalchemy.ext.declarative.declared_attr` decorator should be used for this purpose with declarative. zCallable[[Any], Any]rXr)rXrr/cs tj|f|||j|_dSr-)superrrW)rIrXrr/rur1r2rszclassproperty.__init__NzOptional[type]r`cCs ||Sr-ror^r1r1r2r_szclassproperty.__get__)N)rTrUrVrWr3rr_ __classcell__r1r1rr2rs  rc@s<eZdZddddZdddddd Zd d d d dZdS)hybridpropertyrrcCs||_||_dSr-)rclslevelrIrr1r1r2rszhybridproperty.__init__rr rdownerr,cCs$|dkr||}|S||SdSr-rrrIrdrZclsvalr1r1r2r_s zhybridproperty.__get__rqzhybridproperty[_T]rcCs ||_|Sr-rrr1r1r2 classlevelszhybridproperty.classlevelN)rTrUrVrr_rr1r1r1r2rsrc@s^eZdZddddZdddddd Zddd d d d ZdddddZdddddZdS)rw_hybridpropertyrrcCs||_||_d|_dSr-)rrsetfnrr1r1r2r szrw_hybridproperty.__init__rr rcCs$|dkr||}|S||SdSr-rrr1r1r2r_s zrw_hybridproperty.__get__rDrccCs|jdk st|||dSr-)rrNrer1r1r2rfszrw_hybridproperty.__set__rqzrw_hybridproperty[_T]rcCs ||_|Sr-)rrr1r1r2setterszrw_hybridproperty.settercCs ||_|Sr-rrr1r1r2r szrw_hybridproperty.classlevelN)rTrUrVrr_rfrrr1r1r1r2r s rc@s@eZdZdZddddZdddddd Zd d d d dZdS) hybridmethodz/Decorate a function as cls- or instance- level.rrcCs||_|_||_dSr-)rrrrr1r1r2r(s zhybridmethod.__init__rrcCs*|dkr|j||jS|j||SdSr-)rr_rur)rIrdrr1r1r2r_,szhybridmethod.__get__rqzhybridmethod[_T]rcCs ||_|Sr-rrr1r1r2r2szhybridmethod.classlevelN)rTrUrVrWrr_rr1r1r1r2r%src@s\eZdZUdZded<iZded<eZdddddd d d Z d d Z ddZ ddZ dS)symbolaIA constant symbol. >>> symbol('foo') is symbol('foo') True >>> symbol('foo') A slight refinement of the MAGICCOOKIE=object() pattern. The primary advantage of symbol() is its repr(). They are also singletons. Repeated calls of symbol('name') will all return the same instance. r;rozDict[str, symbol]symbolsNrer)rorZ canonicalr,c Cs|j|j|}|dkrbt|ts*t|dkr:t|}tt |}||_ |rV||_ ||j|<n |r||krt d|d||W5QRSQRXdS)Nz#Can't replace canonical symbol for z with new int value ) _lockrr7r4r;rNhashr__new__rrorWr)rYrorZrrr1r1r2rKs     zsymbol.__new__cCst|jdt|ffS)Nr<)rrorrHr1r1r2 __reduce__iszsymbol.__reduce__cCst|Sr-rrHr1r1r2__str__lszsymbol.__str__cCsd|jdS)Nzsymbol()rorHr1r1r2__repr__oszsymbol.__repr__)NN) rTrUrVrWr3rrrrrrrrr1r1r1r2r7s  rc@s0eZdZddddddddZd d d d Zd S) _IntFlagMetar;zTuple[Type[Any], ...]rrrD) classnamerdict_r/r,c Ksg|_}|D]Z\}}td|r(qt|tr@t||d}n|dstdnqt |||| |qt dd|D|_ dS)Nz^__.*__$)rr1z#Expected integer values for IntFlagcSsi|] }|j|qSr1r)rirr1r1r2 sz)_IntFlagMeta.__init__..)Z_itemsr%rmmatchr4rrr?rrFrrZ immutabledict __members__) rYrrrr/r%rvrr1r1r2rts        z_IntFlagMeta.__init__zIterator[symbol]rEcCs tddS)Nziter not implemented to ensure compatibility with Python 3.11 IntFlag. Please use __members__. See https://github.com/python/cpython/issues/99304rarHr1r1r2__iter__sz_IntFlagMeta.__iter__N)rTrUrVrrr1r1r1r2rssrc@seZdZdZdS) _FastIntFlagzAn 'IntFlag' copycat that isn't slow when performing bitwise operations. the ``FastIntFlag`` class will return ``enum.IntFlag`` under TYPE_CHECKING and ``_FastIntFlag`` otherwise. NrKr1r1r1r2rsr) metaclass)IntFlag_EzDict[_E, List[Any]]z Optional[_E])rchoicesroresolve_symbol_namesr,cCsn|D]>\}}||kr |S|r6||jkr6|S||kr|Sq|dkrTdStd|d|dS)aOGiven a user parameter, parse the parameter into a chosen value from a list of choice objects, typically Enum values. The user argument can be a string name that matches the name of a symbol, or the symbol object itself, or any number of alternate choices such as True/False/ None etc. :param arg: the user argument. :param choices: dictionary of enum values to lists of possible entries for each. :param name: name of the argument. Used in an :class:`.ArgumentError` that is raised if the parameter doesn't match any available argument. NzInvalid value for 'z': )r%rorr)rrrorZ enum_valuechoicer1r1r2parse_user_argument_for_enums rrgcCst|_td7adS)zAssign a '_creation_order' sequence to the given instance. This allows multiple instances to be sorted in order of creation (typically within a single thread; the counter is not particularly threadsafe). rN)_creation_order)rdr1r1r2set_creation_orders r)rrrr,cOs>z |||WStk r8tdtddYnXdS)zXexecutes the given function, catches all exceptions and converts to a warning. z%s('%s') ignoredrrN)rcwarnrFrG)rrrr1r1r2warn_exceptions rcCsFz(t||kr d|d|WS|WSWntk r@|YSXdS)Nz%s...r)rr)rLZlen_r1r1r2ellipses_strings   rcsTeZdZUdZded<dddddfdd Zdd d d Zd d dddZZS)_hash_limit_stringa/A string subclass that can only be hashed on a maximum amount of unique values. This is used for warnings so that we can send out parameterized warnings without the __warningregistry__ of the module, or the non-overridable "once" registry within warnings.py, overloading memory, r_hashr; Sequence[Any])rLnumrr,cs<||d|}t||}td|t||f|_|S)Nz6 (this warning may be suppressed after %d occurrences)z%s_%d)rrrr)rYrLrrZ interpolatedrIrr1r2rs z_hash_limit_string.__new__rEcCs|jSr-)rrHr1r1r2__hash__sz_hash_limit_string.__hash__rrr)otherr,cCst|t|kSr-)r)rIrr1r1r2__eq__ sz_hash_limit_string.__eq__) rTrUrVrWr3rrrrr1r1rr2rs   r)msgrr,cCs(|rttj||dn t|tjdS)zdIssue a warning. If msg is a string, :class:`.exc.SAWarning` is used as the category. )rN)_warnings_warnr SAWarning)rrr1r1r2rsrr)rrr,cCs |rt|d|}t|tjdS)z\Issue a warning with a parameterized string, limiting the number of registrations. N)rrrr)rrr1r1r2 warn_limiteds rz)Dict[CodeType, Tuple[str, Type[Warning]]] _warning_tagsz Type[Warning]zCallable[[_F], _F])messagecategoryr,csfdd}|S)Ncsft|j<|Sr-)rrrxrrr1r2go,sz#tag_method_for_warnings..gor1)rrrr1rr2tag_method_for_warnings)srz&^(?:sqlalchemy\.(?!testing)|alembic\.)zUnion[str, Warning]zOptional[Type[Warning]])rr stacklevelr,cCszt|}Wn&tk r&d}Ynd}YnXd}}|dk r|sdtt|jddsdd}|jt krd}t |j\}}|p|}|d|d}|j }|s|d7}q>|r>|r>qq>|dk rt j |||dd nt j ||dd dS) NrFrTrTz (rr)r) rF _getframerrmr_not_sa_pattern f_globalsr7f_coderf_backwarningsr)rrrframeZstacklevel_foundZwarning_tag_found_suffixZ _categoryr1r1r2r6s4    rrzCallable[..., Optional[_T]])rretry_on_exceptionr,cs$gddddfdd }|S)zNDecorate the given function to be a no-op after it is called exactly once.rz Optional[_T]rr/r,cs@}r<}z |||WSr4d|YnXdS)Nr)r[insert)rr/Z strong_fnZonce_fnroncerr1r2rqs  zonly_once..gor1)rrrr1r r2 only_onceisr z%sqlalchemy/([a-z_]+/){0,2}[a-z_]+\.pyzunit(?:2|test2?/)zre.Pattern[str])tbexclude_prefixexclude_suffixr,cCs`d}t|d}||kr0|||r0|d7}q||krP|||rP|d8}q0|||dS)atChop extraneous lines off beginning and end of a traceback. :param tb: a list of traceback lines as returned by ``traceback.format_stack()`` :param exclude_prefix: a regular expression object matching lines to skip at beginning of ``tb`` :param exclude_suffix: a regular expression object matching lines to skip at end of ``tb`` rr)rsearch)rrrr{endr1r1r2chop_tracebacks   rcCs$d|}t}t|||dS)Nz&def set(obj, value): obj.%s = valuerZ)rEcopyr)attrnamerrr1r1r2 attrsetters  rz^__.+__$cs*eZdZdZdZddfdd ZZS) TypingOnlyzA mixin class that marks a class as 'typing only', meaning it has absolutely no methods, attributes, or runtime functionality whatsoever. r1rDrEcsBt|jkr4dd|jD}|r4td|d|dtdS)NcSsh|]}t|s|qSr1)_dundersrriror1r1r2 s z/TypingOnly.__init_subclass__..zClass z< directly inherits TypingOnly but has additional attributes r)rrr6rNr__init_subclass__)rY remainingrr1r2rs zTypingOnly.__init_subclass__)rTrUrVrWrXrrr1r1rr2rsrcsDeZdZUdZded<ddfdd Zeddd d d ZZS) EnsureKWArga6Apply translation of functions to accept \**kw arguments if they don't already. Used to ensure cross-compatibility with third party legacy code, for things like compiler visit methods that need to accept ``**kw`` arguments, but may have been copied from old code that didn't accept them. r; ensure_kwargrDrEcsf|j}|j}|rX|D]B}t||}|r||}t|}|js||}t|||qt dSr-) rr6rmrrrr _wrap_w_kwrFrr)rYZfn_regZclsdictr:r@rrwrappedrr1r2rs   zEnsureKWArg.__init_subclass__rqrcs ddddfdd }t|S)Nrr cs|Sr-r1)rr/rxr1r2wrapsz$EnsureKWArg._wrap_w_kw..wrapr)rYrr!r1rxr2rszEnsureKWArg._wrap_w_kw) rTrUrVrWr3rrmrrr1r1rr2rs   rcCsjt|drt||S|}|jj|_t|dr4|j|_t|jdrT|jjrT|jj|_n|jrb|j|_|SdS)zAugment functools.update_wrapper() to work with objects with a ``__call__()`` method. :param fn: object with __call__ method rTrUrWN)r~rrurTrUrrW)wrapperr_fr1r1r2 wrap_callables     r$cCsd|kr|dSd}gg}d}t|}||kr||}|dkr|dkr|||dkr|||ddkr||dd|d7}q|dN}n*|dkr|dkr|gn|d||d7}q(dd|DS)aParse a dotted identifier with accommodation for quoted names. Includes support for SQL-style double quotes as a literal character. E.g.:: >>> quoted_token_parser("name") ["name"] >>> quoted_token_parser("schema.name") ["schema", "name"] >>> quoted_token_parser('"Schema"."Name"') ['Schema', 'Name'] >>> quoted_token_parser('"Schema"."Name""Foo"') ['Schema', 'Name""Foo'] "rrrrcSsg|]}d|qS)r)rl)rirr1r1r2r-sz'quoted_token_parser..)rrr)rLr,rridxlvcharr1r1r2quoted_token_parsers$ $    r))paramsrr,cstfdd}|S)Ncs:|jdk r|jpd}|r0t|fddD}||_|S)Nrcsi|] }|qSr1r1)riparamrr1r2r6sz8add_parameter_text..decorate..)rWinject_param_text)rrZr*rr1r2r3s z$add_parameter_text..decorate)rr!)r*rrr1r-r2add_parameter_text0s r.cCsN|dd}t|dkr|S|\}}|ds@|dt|St|SdS)N rrg)rrr?textwrapdedent)rZ split_text firstlinerr1r1r2_dedent_docstring=s   r3) given_doctext injecttextposr,cCst|pd}|d}t|dkr,|dt|d}|drP|ddddt|D}|dd|t|t|d}|d||||d}d |S)Nrr/rrcSsg|]\}}|s|qSr1)r)rirliner1r1r2rTsz)inject_docstring_text..) r3rrrr0r1r r#minrl)r4r5r6doctextlinesZ injectlinesZblanksZ inject_posr1r1r2inject_docstring_textIs      r;z(\s+):param (.+?):zDict[str, str])r9 inject_paramsr,c Cs t|}g}d}|r|}t|}|dkr|r|dd}||krdt|dd}|rt d|d} | rdt| d}|||}nV|r| d|dgd}n<| s| ||dgd}n| dr| ||gq| |qd|S) Nr*rgrz(\s+)\Srr/z::) collectionsdeque splitlinespopleft _param_regrrlstriprrmr]rstripr@rrl) r9r<Zdoclinesr:Z to_injectr7r@r+indentm2r1r1r2r,`s6   r,)rr,cCst|dkrdSt|dk}|r,|ddn|dd|dd}dd|D}|r`d|Sd d|dd|dfSdS) zTrims a list of strings from the middle and return a string of up to four elements. Strings greater than 11 characters will be truncatedrNrrrcSs,g|]$}t|dkr$d|ddn|qS) z%s..N)rrr1r1r2rsz$repr_tuple_names..r z %s, ..., %s)rrl)rflagresr1r1r2repr_tuple_namess  ( rJcCstrdS|rtdndSdS)NTzDcython extensions were expected to be installed, but are not presentF)r ImportError)Zraise_r1r1r2has_compiled_extsrLc@seZdZeZdS)_MissingN)rTrUrVenumautoMissingr1r1r1r2rMsrM)N)FF)T)T)r1r1r1r1)r1Nr1)NNr<N)NNN)TN)N)F)r)N)Nr)F)rW __future__rr>rN functoolsrr.rrMrmrFr0rrrtypingrrrr r r r r rrrrrrrrrrrrrrrZ_has_cyrrrr r!r#r%r&r'r(Zpy310r/rArBrardrprwrrrrrrrrrrrrrrrr rrrr'r(r7r;rIrJrUrVrWrnrprZnon_memoized_propertypropertyZro_memoized_propertyZro_non_memoized_propertyrzr{Z!HasMemoized_ro_memoized_attributerrrrrrrrrrrrQrrrrrrr5rrrZ FastIntFlagEnumrrrrrrr;rrrrr3rcompilerrr Z_SQLA_REZ _UNITTEST_RErZNoneTyperrrrr$r)r.r3r;rBr,rJrLrMrPZ MissingOrr1r1r1r2 sr                                ;  G(5 9u #N& C V +M.   #<"  "      3     )  ,   +