o znh@s$dZddlmZddlZddlZddlZddlZddlZddlZddl Z ddl Z ddl Z ddl m Z ddl mZddl mZd d ZGd d d eZd dZddZddZddZddZddZddZGdddeZddZddd Zd!d"Zdd$d%Zdd'd(Zdd)d*Z d+d,Z!d-d.Z"dd0d1Z#Gd2d3d3eZ$d4d5Z%d6d7Z&   8 dd9d:Z'd;d<Z(dd=d>Z)Gd?d@d@eZ*dAdBZ+GdCdDdDeZ,GdEdFdFeZ-ddGdHZ.GdIdJdJeZ/dKdLZ0dMdNZ1dOdPZ2ddQdRZ3dSdTZ4dUdVZ5ddWdXZ6dYdZZ7d[d\Z8Gd]d^d^e9Z:Gd_d`d`eZ;GdadbdbeZdee>_?GdfdedeeZ@daAdgdhZBdidjZCddldmZDGdndodoejEZFdpdqZGdrdsZHdtduZIeJdvZKeJdwZLeLeKfdxdyZMeNdZOdzd{ZPGd|d}d}eNZQd~dZRddZSddZTddZUddZVddZWdS)zRoutines to help with the creation, loading and introspection of modules, classes, hierarchies, attributes, functions, and methods. update_wrapperN) _collections)compat)exccCs*tjr|d}t}|||S)Nzutf-8)rpy3kencodehashlibmd5update hexdigest)xmrF/usr/local/lib/python3.10/dist-packages/sqlalchemy/util/langhelpers.pymd5_hexs   rc@s.eZdZdZdZd ddZddZdd Zd S) safe_reraiseaKReraise 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() ) warn_only _exc_infoFcC ||_dSN)r)selfrrrr__init__8 zsafe_reraise.__init__cCst|_dSr)sysexc_inforrrrr __enter__;zsafe_reraise.__enter__cCs|dur|j\}}}d|_|jst|||dSdStjs4|jr4|jdr4td|jd|jdfd|_t|||dS)NrzfAn exception has occurred during handling of a previous exception. The previous exception is: %s %s r)rrrreraiser warn)rtype_value tracebackexc_type exc_valueexc_tbrrr__exit__>s zsafe_reraise.__exit__NF)__name__ __module__ __qualname____doc__ __slots__rrr)rrrrr$s   rcCsdddtd|jDS)N css|]}|VqdSr)lower).0nrrr Ss z(clsname_as_plain_name..z ([A-Z][a-z]+))joinrefindallr+)clsrrrclsname_as_plain_nameRs  r9cCs>g}|j|j|jfD]}t|dr|}||q t|S)zrdecode a slice object as sent to __getitem__. takes into account the 2.5 __index__() method, basically. __index__)startstopstephasattrr:appendtuple)slcretrrrr decode_sliceXs   rCc 'slt|}|D],tftfddtd}|D]}||vr,|||VnqtdqdS)Ncs t|Sr)str)ibaserrks z!_unique_symbols..iz&exhausted namespace for symbol base %s)set itertoolschainritertools_imaprangeadd NameError)usedbasespoolsymrrFr_unique_symbolsfs   rTccs2|r||d@}||V||N}|sdSdS)z6Call the given function given each nonzero bit from n.rNr)fnr3brrrmap_bitsvs   rWcfdd}t|S)z'A signature-matching decorator factory.cst|st|stdt|}t|d|dd|jf}t|dd\}}t ||d}| t |dd |j|d <d |}t ||||i|j}t |d |j|_||_t||S) Nznot a decoratable functionrrtargetrU)rZrUFgroupednamezDdef %(name)s(%(args)s): return %(target)s(%(fn)s, %(apply_kw)s) im_func)inspect isfunctionismethod Exceptionrinspect_getfullargspecr@r+rTdictr format_argspec_plus_exec_code_in_envgetattr __defaults__ __wrapped__r)rUspecnames targ_namefn_namemetadatacode decoratedrZrrdecorates$     zdecorator..decorater)rZrrrrqr decorators  rscCst||||Sr)exec)roenvrmrrrrfs rfc Cst|tr|j}|}d|j|f}n|}}d|}|dd}t|}|dd=t|dd}||d<d |}|td } t || | |} |j | _ d | dd d| _ tj s^t|d rd||j_ | S||_ | S)zProduce a wrapping function for the given cls or classmethod. Rationale here is so that the __init__ method of the class can serve as documentation for the function. zConstruct a new :class:`.%s` object. This constructor is mirrored as a public API function; see :func:`~%s` for a full usage and argument description.zJThis function is mirrored; see :func:`~%s` for a description of arguments..rFr[r]z5def %(name)s(%(args)s): return cls(%(apply_kw)s) )r8symbol sqlalchemyr__func__) isinstancetyperr+splitrrcrerxrtr.rsplitr,py2kr>rz) rZlocationrU callable_doc location_namerjrnrorurprrrpublic_factorys>      rc@.eZdZd ddZddZddZdd ZdS) PluginLoaderNcCs||_i|_||_dSr)groupimplsauto_fn)rrrrrrrs zPluginLoader.__init__cCs|jdSr)rclearrrrrrr zPluginLoader.clearcCs||jvr |j|S|jr||}|r||j|<|Szddl}Wn ty,Ynw||j|D] }|j|j|<|Std|j|f)NrzCan't load plugin: %s:%s) rr pkg_resources ImportErroriter_entry_pointsrloadrNoSuchModuleError)rr]loaderrimplrrrrs$         zPluginLoader.loadcsfdd}||j|<dS)Ncs6t}dddD]}t||}qt|S)Nrvr)rimport_r}rg)modtoken modulepathobjnamerrrs   z#PluginLoader.register..load)r)rr]rrrrrrregisterszPluginLoader.registerr)r+r,r-rrrrrrrrrs   rcCshztj}Wntyt|}|dt|dfYSw|j}|j}t|j d|t|j |@fS)Nrr) r_CO_VARKEYWORDSAttributeErrorrrcbool__code__ co_argcountlist co_varnamesco_flags)rUco_varkeywordsrjconargsrrr_inspect_func_argss     rcCs|du}|r t}|jdd}|ot|tjot|jtj}|r2t|\}}| ||s2|s2dS|r6|rE|j D] }t ||durDnq9| 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 ! NrFr) rI__dict__getr{types FunctionTyperCodeTyperr __bases__get_cls_kwargsdiscard)r8_settoplevelctrhas_initrkhas_kwcrrrrs*      rcCst|dS)zReturn the set of legal kwargs for the given `func`. Uses getargspec so is safe to call for methods, functions, etc. r)rrcfuncrrrget_func_kwargs<srFc Cs0t|r td|t|r4|r/|r/t|}t|jdd|j|j |j |j |j |j St|St|rb|r\|s@|jr\t|j}t|jdd|j|j |j |j |j |j St|jSt|rot|j|ddSt|drzt|jSt|drt|jrt|j|dStd |td |) 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)no_self_is_initrz__call__)rzCan't inspect callable: %s)r_ isbuiltin TypeErrorr`rrc FullArgSpecargsvarargsvarkwdefaults kwonlyargskwonlydefaults annotationsra__self__rzisclassget_callable_argspecrr>r)rUrrrjrrrrGsN              rTc Cs0t|r t|}n|}tj|}|dr|dd}n |dr(d|d}nd}t|d|d|dd|d}d}|drI|t|d7}|drU|t|d7}|d|d}|rh|d|d}nd}tj||d|d|d d d } |rt|||| d St|dd ||dd | dd d S)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. Example:: >>> format_argspec_plus(lambda self, a, b, c=3, **d: 123) {'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)'} rrz%s[0]NrrYrcSsd|S)N=r)rrrrrHsz%format_argspec_plus..) formatvalue)rself_arg apply_posapply_kwrw)rcallablercinspect_formatargspeclenrd) rUr\rjrrr num_defaults name_argsdefaulted_valsrrrrre}sR     recCsV|tjur |r dp d}nzt||dWSty"|rdpd}Ynwtd|||dS)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)rr[z(self, *args, **kwargs)zself, *args, **kwargs)rrrr)objectrrerrd)methodr\rrrrformat_argspec_inits  rcCsJzt|WSty$|tjurdgdddfYSdgdddfYSw)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) rNrkwargs)rrcrrr)rrrrgetargspec_inits   rcCst|tjr |js |jS|S)zSAdjust the incoming callable such that a 'self' argument is not required. )r{r MethodTyperrz) func_or_clsrrrunbound_method_to_callablesrrc s(|durg}nt|}tg}t}d}t|D]k\}}zt|j} Wn ty1Yqw| j r:t | j p;d} |dkr_| j rF| j }| rT| | j d| n| | j ddn|fdd| j d| D| r|ddt| j | d| j Dqg} | fdd|D|durt|r| d dt|D|D]+\} } | |vrqzt| }|ur|| kr| d | |fWqtyYqw|r |D]'\} } zt| }|ur|| kr| d | |fWqtyYqwd jjd | fS) z}Produce a __repr__() based on direct association of the __init__() specification vs. same-named attributes present. Nrrcsg|]}|fqSrrr2arg)missingrr %z generic_repr..cSsg|]\}}||fqSrr)r2rdefaultrrrr*sc3s |] }tt|dVqdSr)reprrgrobjrrr43szgeneric_repr..cSsg|]}t|qSrr)r2valrrrr6rz%s=%rz%s(%s), )rto_listr OrderedDict enumeraterrcrrrrrextendrr zipr>rgitemsr?rb __class__r+r5)r additional_kw to_inspect omit_kwargpos_argskw_argsvargsrEinsprj default_lenoutputrdefvalrr)rrr generic_reprst      rc@s6eZdZdZdZddZddZd dd Zd d Zd S)portable_instancemethodz_Turn an instancemethod into a (parent, name) pair to produce a serializable callable. )rZr]r __weakref__cCs|j|j|jdS)NrZr]rrrrrr __getstate__Vsz$portable_instancemethod.__getstate__cCs&|d|_|d|_|dd|_dS)NrZr]rr)rZr]rr)rstaterrr __setstate__]s  z$portable_instancemethod.__setstate__rcCs|j|_|j|_||_dSr)rrZr+r]r)rmethrrrrrbs z portable_instancemethod.__init__cOs$||jt|j|j|i|Sr)r rrgrZr])rrkwrrrrgs z portable_instancemethod.__call__Nr) r+r,r-r.r/rrrrrrrrrNs  rcstjr t|tjr tS|ht|j}|r||}tjr/t|tjr$qfdd|jD}n fdd|jD}|D] }| | |q;tj rW|j dksUt |dsVqn |j dksat |dsbqfdd|DD] }| | |qm|stS) aReturn 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. Old-style classes are discarded and hierarchies rooted on them will not be descended. c3s(|]}|vrt|tjs|VqdSr)r{r ClassTyper2_hierrrr4sz"class_hierarchy..c3s|] }|vr|VqdSrrrrrrr4builtins__subclasses__ __builtin__csg|]}|vr|qSrrrrrrrsz#class_hierarchy..)rrr{rrr__mro__poprr?rNr r,r>r)r8processrrQrVsrrrclass_hierarchyls<         rccsBt|}|D]}|jD]}||jvr||j|fVnq qdS)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)dirr r)r8keyskeyrrrriterate_attributess  r self.proxyc s$|r|}ndur dfddt|D}|D]v}zt||}t|ds(Wqt|d|}Wn ty8Yqwzt|} t| d} t| ddd} Wn ty_d } d } Ynwd t} |durm||ipni} t | | z|j | |_ Wn tyYnwt || |qdS) z9Automates delegation of __specials__ for a proxying type.N)r/__del____getattribute__ __metaclass__rrcs6g|]}|dr|drt|s|vr|qS)__) startswithendswithr>r2rinto_clsskiprrrsz0monkeypatch_proxied_specials..rr^rrz(self, *args, **kw)z (*args, **kw)z?def %(method)s%(fn_args)s: return %(name)s.%(method)s%(d_args)s) rrgr>rrrcrrlocalsexec_rhsetattr)rfrom_clsronlyr] from_instancedundersrrUrjfn_argsd_argspyrurrrmonkeypatch_proxied_specialssJ          r(cCst|d|t|d|uS)z;Return True if the two methods are the same implementation.rz)rg)meth1meth2rrrmethods_equivalents r+c Csj|s|stdt|trt||r|St|pddt|D}tt|}tj}t|tr2|}n |s;t}tj}nt|}||||rI|St|t sc|tjurUdpVd}td||d |fGdd d t }|rsd |j |_ t} t |D](\} } | |vrtd | t| std | | ft|| t| | | qz|| |r|Std d || )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)r)rrrrrrsz as_interface..zany ofzall ofz%r does not implement %s: %src@seZdZdZdS)z(as_interface..AnonymousInterfacezA callable-holding shell.N)r+r,r-r.rrrrAnonymousInterface4sr, Anonymousz%r: unknown in this interfacez%r=%r is not callablez,dictionary does not contain required keys %s)rr{r|rIroperatorgegt intersectionrdr5rr+dictlike_iteritemsrrr  staticmethodrN) rr8methodsrequired interface implementedcomplies qualifierr,foundrrrrr as_interfacesP!         r;c@s6eZdZdZd ddZddZddZed d ZdS) memoized_propertyz2A read-only @property that is only evaluated once.NcCs||_|p|j|_|j|_dSr)fgetr.r+)rr=rrrrrOs  zmemoized_property.__init__cCs&|dur|S|||j|j<}|Sr)r=rr+)rrr8resultrrr__get__Tszmemoized_property.__get__cCst||jdSr)r<resetr+)rrrrr_resetZszmemoized_property._resetcCs|j|ddSr)rr )r8rr]rrrr@]szmemoized_property.resetr) r+r,r-r.rr?rA classmethodr@rrrrr<Ls r<crX)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. csB|g|Ri|fdd}j|_j|_||jj<S)NcSrrarr>rrmemonz6memoized_instancemethod..oneshot..memo)r+r.r)rrrrGrUrFroneshotks   z(memoized_instancemethod..oneshotr)rUrJrrIrmemoized_instancemethodbs rKc@s2eZdZdZd ddZddZddZd d Zd S) !group_expirable_memoized_propertyz?A family of @memoized_properties that can be expired in tandem.rcCsg|_|r |j|dSdSr) attributesr)rrMrrrr|sz*group_expirable_memoized_property.__init__cCs"|j}|jD]}||dqdS)z.Expire all memoized properties for *instance*.N)rrMr )rinstancestash attributerrrexpire_instances z1group_expirable_memoized_property.expire_instancecC|j|jt|Sr)rMr?r+r<rrUrrrrz*group_expirable_memoized_property.__call__cCrRr)rMr?r+rKrSrrrrrTz(group_expirable_memoized_property.methodNr)r+r,r-r.rrQrrrrrrrLys   rLc@s$eZdZdZdZddZddZdS) 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__. rcCst|r)r)rrrrr_fallback_getattrzMemoizedSlots._fallback_getattrcsdr ttdr td}t||Stdr.oneshot..memo)r+r.r )rrrGrUrrrFrrJs   z*MemoizedSlots.__getattr__..oneshot)rrr>rgr r.rV)rrr$rJrrYr __getattr__s    zMemoizedSlots.__getattr__N)r+r,r-r.r/rVrZrrrrrUs  rUcsfdd}|S)Ncsnd}td|ddtt|dg}t||d}t||j|r5t |dr5|j |j|S)Nrvrrw__all__) r}rrr5globalsrrgr r+r>r[r?)rtokensr add_to_all modulenamerrrrs  z dependency_for..decorater)r`r_rrrr^rdependency_fors rac@sFeZdZdZddZddZeddZeZ iZ Gdd d e Z d S) dependenciesaApply imported dependencies as arguments to a function. E.g.:: @util.dependencies( "sqlalchemy.sql.widget", "sqlalchemy.engine.default" ); def some_func(self, widget, default, arg1, arg2, **kw): # ... Rationale is so that the impact of a dependency cycle can be associated directly with the few functions that cause the cycle, and not pollute the module-level namespace. c GsDg|_|D]}|d}|jtd|dd|dqdS)Nrvrrw) import_depsr}r?rb _importlaterr5)rdepsdepr]rrrrs zdependencies.__init__c Cs|j}t|}t|d}|ddv}tt|D]}d||d||r'dnd<qt|dd}|D] }||r:dnd=q3||ddd<t|dd} d| d|d d } t| t} t |d |j | _ t | |S) Nr)rr8zimport_deps[%r]rFr[z!lambda %(args)s: fn(%(apply_kw)s)rr)rrr^) rcrrcrrMrreevalrrgrhr) rrUrcrj spec_zerohasselfrE inner_specimpname outer_specrorprrrrs$       zdependencies.__call__cCs(ttjD] }|j|r|qdSr)rrb _unresolved _full_pathr_resolve)r8pathrrrr resolve_alls  zdependencies.resolve_allc@sNeZdZeZiZddZddZeddZ e ddZ d d Z d d Z d S)zdependencies._importlatercCs8|d|}|tjvrtj|St|tj|<}|SNrv)rb_by_keyr__new__)r8rpaddtlrimprrrrt s   z!dependencies._importlater.__new__cCs||_||_tj|dSr)_il_path _il_addtlrbrmrN)rrprurrrrsz"dependencies._importlater.__init__cCs|jd|jSrr)rwrxrrrrrnsz$dependencies._importlater._full_pathcCs,|tjvrtd|j|jft|j|jS)Nz.bool_or_valuer)rrrrr bool_or_strHs rcCs|dur|St|S)zCoerce to integer.N)int)r$rrrasintWsrcCsx|dur|}||vr6t|trt|||s:||dur8|tur,|r,t||||<dS|||||<dSdSdSdS)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)r{r|rr)rrr# flexi_booldestrrrcoerce_kw_type_s   rcs4t|}|fdd||D||i|S)zInstantiate cls using the __dict__ of obj as constructor arguments. Uses inspect to match the named arguments of ``cls``. c3s(|]}|jvr|j|fVqdSr)r)r2krrrr4{sz#constructor_copy..)rr difference)rr8rrrkrrrconstructor_copyss rcs&tjtdfdd}|S)z%Return a threadsafe counter function.rcs&z tWSwr)acquirenextreleasercounterlockrr_nextszcounter.._next)r threadingLockrJcount)rrrrrs  rcCst|dr|jdurt|jtrtS|jSt|trtpt}||tr%tS||tr,tS||tr3tSt|dr:tSt|drAtSt|drHtS|S)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__Nr?rNrI)r>r issubclassrIr{r|rrd)specimenrisarrrduck_type_collections(        rcCsXt||r|St|tr td|ddd|Dt|ftd||t|f)Nz8Argument '%s' is expected to be one of type %s, got '%s'z or css|]}d|VqdS)z'%s'Nr)r2rErrrr4sz"assert_arg_type..z6Argument '%s' is expected to be of type '%s', got '%s')r{r@r ArgumentErrorr5r|)rargtyper]rrrassert_arg_types   rcstjrtdrtSntdrStdr#tStdtdddur7tdtdrFfdd }|Std rXtfd d  DStd) z?Return a (key, value) iterator for almost any dict-like object.r iteritems __getitem__rNzObject '%r' is not dict-likeiterkeysc3s"D] }||fVqdSr)r)rdictlikegetterrriterators z$dictlike_iteritems..iteratorrc3s|] }||fVqdSrr)r2r)rrrr4rz%dictlike_iteritems..) rr r>rrriterrgrr)rrrrrr2s"         r2c(eZdZdZfddZddZZS) 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. cs*tt|j|g|Ri||j|_dSr)superrrr.)rr=rrrrrrs zclassproperty.__init__cCs ||Sr)r=)descrr8rrrr?rzclassproperty.__get__)r+r,r-r.rr? __classcell__rrrrrs rc@seZdZddZddZdS)hybridpropertycCrrrrrrrrrrzhybridproperty.__init__cCs*|dur||}|jj|_|S||Sr)rr.)rrNownerclsvalrrrr?s    zhybridproperty.__get__N)r+r,r-rr?rrrrrs rc@s eZdZdZddZddZdS) hybridmethodz/Decorate a function as cls- or instance- level.cCrrrrrrrrrzhybridmethod.__init__cCs&|dur |j||jS|j||Sr)rr?r)rrNrrrrr?szhybridmethod.__get__N)r+r,r-r.rr?rrrrrs rc@r) _symbolNcCs@t|tjsJ|durt|}tt|}||_|r||_|S)zConstruct a new named symbol.N) r{rrhashrrtrr]r.)rr]r canonicalvrrrrts z_symbol.__new__cCst|jdt|ffS)Nr)rxr]rrrrr __reduce__sz_symbol.__reduce__cCst|Srrrrrr__str__rWz_symbol.__str__cCs d|jS)Nz symbol(%r))r]rrrr__repr__rz_symbol.__repr__NN)r+r,r-rtrrrrrrrr s    rrxc@s8eZdZdZiZejZdddZ e d ddZ dS) rxaA 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. The optional ``doc`` argument assigns to ``__doc__``. This is strictly so that Sphinx autoattr picks up the docstring we want (it doesn't appear to pick up the in-module docstring if the datamember is in a different module - autoattribute also blows up completely). If Sphinx fixes/improves this then we would no longer need ``doc`` here. NcCsR|jz|j|}|durt||||j|<}|WtjStjwr)_lockrsymbolsrrrxr)r8r]rrrSrrrrt?s  zsymbol.__new__FcCsf|D]\}}||ur|S|r||jkr|S||vr#|Sq|dur*dStd||f)aGiven a user parameter, parse the parameter into a chosen symbol. 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 symbol object to list of possible entries. :param name: name of the argument. Used in an :class:`.ArgumentError` that is raised if the parameter doesn't match any available argument. :param resolve_symbol_names: include the name of each symbol as a valid entry. NzInvalid value for '%s': %r)rr]rr)r8rchoicesr]resolve_symbol_namesrSchoicerrrparse_user_argumentIszsymbol.parse_user_argumentrr*) r+r,r-r.rrrrrrtrBrrrrrrx&s   cCst|_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)rNrrrset_creation_orderps rcOs>z||i|WStytdtddYdSw)zXexecutes the given function, catches all exceptions and converts to a warning. z%s('%s') ignoredrrN)rbr"rr)rrrrrrwarn_exception}s  rcCs<zt||krd|d|WS|WSty|YSw)Nz%s...r)rr)r$len_rrrellipses_strings  rcs0eZdZdZfddZddZddZZS)_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, cs@||d|}tt|||}td|t||f|_|S)Nz6 (this warning may be suppressed after %d occurrences)z%s_%d)rrrtr_hash)r8r$numr interpolatedrrrrrts z_hash_limit_string.__new__cCs|jSr)rrrrr__hash__sz_hash_limit_string.__hash__cCst|t|kSr)r)rotherrrr__eq__sz_hash_limit_string.__eq__)r+r,r-r.rtrrrrrrrrs  rcCstj|tjdddS)zdIssue a warning. If msg is a string, :class:`.exc.SAWarning` is used as the category. r stacklevelN)warningsr"r SAWarning)msgrrrr"sr"cCs&|rt|d|}tj|tjdddS)z\Issue a warning with a parameterized string, limiting the number of registrations. rrN)rrr"rr)rrrrr warn_limiteds rcsgfdd}|S)zNDecorate the given function to be a no-op after it is called exactly once.cs>}r}z||i|WSrd|dS)Nr)r insert)rr strong_fnonce_fnrUonceretry_on_exceptionrrgos zonly_once..gor)rUrrrrr only_onces rz%sqlalchemy/([a-z_]+/){0,2}[a-z_]+\.pyzunit(?:2|test2?/)cCsd}t|d}||kr"|||r"|d7}||kr"|||s||kr<|||r<|d8}||kr<|||s-|||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)tbexclude_prefixexclude_suffixr;endrrrchop_tracebacks rcCs$d|}t}t|||dS)Nz&def set(obj, value): obj.%s = valuerI)rcopyrt)attrnamerorurrr attrsetters  rcr)EnsureKWArgTypezYApply translation of functions to accept \**kw arguments if they don't already. c sr|j}|r-|D]%}t||}|r,||}t|}|js,||||<} t||| qtt | |||dSr) ensure_kwargr6matchrrcr _wrap_w_kwr rrr) r8clsnamerQclsdictfn_regrrrUrjwrappedrrrrs   zEnsureKWArgType.__init__csfdd}t|S)Ncs|Srr)rrrIrrwraprWz(EnsureKWArgType._wrap_w_kw..wrapr)rrUrrrIrr s  zEnsureKWArgType._wrap_w_kw)r+r,r-r.rrrrrrrrs  rcCsht|dr t||S|}|jj|_t|dr|j|_t|jdr+|jjr+|jj|_|S|jr2|j|_|S)zAugment functools.update_wrapper() to work with objects with a ``__call__()`` method. :param fn: object with __call__ method r+r,r.)r>rrr+r,rr.)wrapperrU_frrr wrap_callables     rcCsd|vr |dSd}gg}d}t|}||kr`||}|dkrC|dkr>||dkr>||ddkr>|dd|d7}n|dN}n|dkrQ|dkrQ|gn|d||d7}||ksdd|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'] "rvrrrwcSsg|]}d|qS))r5)r2rrrrrUsz'quoted_token_parser..)r}rr?)r$rr>idxlvcharrrrquoted_token_parser,s& $   rcstfdd}|S)Ncs:|jdur|jp d}|rt|fddD}||_|S)Nrcsi|]}|qSrr)r2paramrrr ^sz8add_parameter_text..decorate..)r.inject_param_text)rUrparamsrrrrr[s z$add_parameter_text..decorate)rr)rrrrrrradd_parameter_textXs rcCsJ|dd}t|dkr|S|\}}|ds |dt|St|S)N rr0)r}rrtextwrapdedent)r split_text firstline remainingrrr_dedent_docstringes    rcCst|pd}|d}t|d}|dr|ddddt|D}|dd|t|t|d}|d||||d}d|S)NrrrcSsg|] \}}|s|qSr)r)r2rlinerrrrxsz)inject_docstring_text..r) rr}r r rrminrr5)doctext injecttextposlines injectlinesblanks inject_posrrrinject_docstring_textqs     rc Cs2|}g}d}|r|d}|durKtd|}|rJ|d}||vrJdt|dd}|rDtd|d} | rDdt| d}|||}nB|drd|d|||dd}n)| sz|||||dd}n| d r||||dq|||s d |S) Nrz(\s+):param (?:\\\*\*?)?(.+?):rr0rz(\s+)\Sz:param rz::) splitlinesr r6rrrlstriprr?rstriprr5) r inject_paramsdoclinesr to_injectrrrindentm2rrrrsH              &rr)FF)T)rNr)NNrN)NNNr*)TN)r)Xr. functoolsrr r_rJr.r6rr rrrrrrrrrr9rCrTrWrsrfrrrrrrrerrrrrrrr(r+r;r<rKrLrUrarbrrrrrrrrr2r|rrrrrr+rxrrrr text_typerr"rrcompile_SQLA_RE _UNITTEST_RErr|NoneTyperrrrrrrrrrrrs    . 0* + 6 S H3 ? V (u   !  G     ,