a
    ~gt                  
   @  s  U d Z ddlmZ ddlZddlZddlmZ ddlZddlZddl	Z	ddl
Z
ddlZddlZddlZddlZddlmZ ddlmZ ddlmZ ddlmZ dd	lmZ dd
lmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlm Z  ddlm!Z! ddlm"Z" ddlm#Z# ddl$Z$ddl%m&Z& ddl%m'Z' ddl(m)Z) ddlm*Z* ddl%m+Z+ e"d Z,e"d!d"d#Z-e"d$ed%ef d&Z.e"d'd(d&Z/e"d)d*d&Z0e"d+d,d&Z1e"d-d.d&Z2e'j3rd/d0d1d2d3Z4nd/d0d1d4d3Z4d/d5d6d7d8Z5G d9d: d:Z6d;d<d=d>d?Z7d/d5d@dAdBZ8d6dCdDd5dEdFdGZ9dHdIdJdKdLdMZ:dNdOdPdQdRZ;dSd5dTdUdVdWZ<dXdYdZd[d\d]Z=e"d^dId&Z>dId_d`dadbZ?dcdd Z@dedfd5dIdgdhdiZAe"djZBe"dkZCG dldm dmZDdndo ZEedd%dpdqdrdsdtdudvdwZFeddxdpdqdrdJdrdudydwZFddxdpdqdrdJdrdudzdwZFdId{d|d}d~ZGd7dIdJdJddddZHd8ddJddddZId9ddZJd:dCd5d5dSdSdSdSddddZKdd ZLdd ZMd;d/dddSd5dddZNG dd dZOdd ZPdd ZQd<ddZRdd ZSd=ddZTe"ddd&ZUG dd dee- ZVG dd deVe- ZWG dd deVe- ZXe!reVZYeVZZe[Z\e[Z]neX ZYZ\eW ZZZ]d$d$dddZ^G dd dZ_e!re[Z`ne_jaZ`G dd dZbd/dJd1ddZcd5ddddZdd/ddddZed>dfd5dCdJdddddZfd/dCdOdÜddńZgd d;d/d/d dƜddȄZhddʜdd̄Zid?d/dddΜddЄZjd/dd5d/dҜddԄZkddք ZlG dd؄ de[ZmG ddڄ dee, ZnG dd܄ dee, ZoG ddބ dee, ZpG dd deqZrG dd desZtG dd detdZue!rBddlmvZv evZwneuZwe"dejxd&Zyd@d/dd5dJddddZzda{d/ddddZ|dId/d/d/dddZ}dAddZ~G dd deZdBd5dDddddZd5dddddZi Zded < d5dddddZe
dZdCdddYdd	d
dZddJddddZe
dZe
dZeefd{ddd{dddZesdZdd Ze
dZG dd dZG dd dZdd Zd d! Zd/d5dd"d#d$Zd5d5dd%d&ZdDd5dYd5d'd(d)Ze
d*Zd5d+d5d,d-d.Zd{dDd/d0d1ZdDd2d3ZG d4d5 d5ejxZejZe#e,e*ej f ZdS (E  zRoutines to help with the creation, loading and introspection of
modules, classes, hierarchies, attributes, functions, and methods.

    )annotationsNupdate_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_MPzmemoized_property[Any]_MAz#HasMemoized.memoized_attribute[Any]_HPzhybridproperty[Any]_HMzhybridmethod[Any]r   Mapping[str, Any]objreturnc                 C  s
   t | S N)inspectget_annotationsr+    r1   `/var/www/html/emsaiapi.evdpl.com/venv/lib/python3.9/site-packages/sqlalchemy/util/langhelpers.pyr/   A   s    r/   c                 C  sB   t | tr| jdd }nt| dd }|d u r4tjS td|S d S )N__annotations__r)   )
isinstancetype__dict__getgetattrr   
EMPTY_DICTr   )r+   annr1   r1   r2   r/   F   s    
str)xr,   c                 C  s*   |  d} t }||  tt| S )Nzutf-8)encoder   md5_not_for_securityupdater   r;   	hexdigest)r<   mr1   r1   r2   md5_hexW   s    

rB   c                   @  s@   e Zd ZU dZdZded< ddddZd	d
dddddZdS )safe_reraisea  Reraise 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_infozdUnion[None, Tuple[Type[BaseException], BaseException, types.TracebackType], Tuple[None, None, None]]rD   Noner,   c                 C  s   t  | _d S r-   )sysexc_inforD   selfr1   r1   r2   	__enter__   s    zsafe_reraise.__enter__zOptional[Type[BaseException]]zOptional[BaseException]zOptional[types.TracebackType]r   )type_value	tracebackr,   c                 C  s`   | j d usJ |d u r@| j \}}}|d us.J d | _ ||nd | _ |d usRJ ||d S r-   )rD   with_traceback)rJ   rL   rM   rN   exc_type	exc_valueexc_tbr1   r1   r2   __exit__   s    zsafe_reraise.__exit__N)__name__
__module____qualname____doc__	__slots__r3   rK   rS   r1   r1   r1   r2   rC   ^   s
   

rC   zType[_T]zIterator[Type[_T]])clsr,   c                 c  sH   t  }| g}|rD| } | |v r$qn
||  ||   | V  qd S r-   )setpopaddextend__subclasses__)rY   seenstackr1   r1   r2   walk_subclasses   s    
ra   )elementr,   c                 C  s8   t | tr| S z
t| W S  ty2   d|   Y S 0 d S )Nzunprintable element %r)r4   r;   	Exception)rb   r1   r1   r2   string_or_unprintable   s    

rd   z	Type[Any]Optional[str])rY   use_namer,   c                 C  s&   |p| j }ddd td|D S )N c                 s  s   | ]}|  V  qd S r-   )lower).0nr1   r1   r2   	<genexpr>       z(clsname_as_plain_name.<locals>.<genexpr>z([A-Z][a-z]+|SQL))rT   joinrefindall)rY   rf   namer1   r1   r2   clsname_as_plain_name   s    
rq   zUnion[Type[Any], object]Callable[..., Any]bool)instance_or_clsagainst_methodr,   c                 C  s.   t | ts| j}n| }|j}t||}||kS )z1Return True if the two class methods don't match.)r4   r5   	__class__rT   r8   )rt   ru   Zcurrent_clsmethod_nameZcurrent_methodr1   r1   r2   method_is_overridden   s    

rx   slicezTuple[Any, ...])slcr,   c                 C  s>   g }| j | j| jfD ] }t|dr*| }|| qt|S )zrdecode a slice object as sent to __getitem__.

    takes into account the 2.5 __index__() method, basically.

    	__index__)startstopstephasattrr{   appendtuple)rz   retr<   r1   r1   r2   decode_slice   s    
r   zSequence[str]zIterator[str])usedbasesr,   c                 '  sh   t | }|D ]V t ft fddtd}|D ] }||vr4|| |V   qq4td  qd S )Nc                   s    t |  S r-   r;   )ibaser1   r2   <lambda>   rl   z!_unique_symbols.<locals>.<lambda>i  z&exhausted namespace for symbol base %s)rZ   	itertoolschainmapranger\   	NameError)r   r   Zused_setpoolsymr1   r   r2   _unique_symbols   s    
r   zCallable[[int], Any]intzIterator[Any])fnrj   r,   c                 c  s*   |r&|| d @ }| |V  ||N }q dS )z6Call the given function given each nonzero bit from n.r   Nr1   )r   rj   br1   r1   r2   map_bits   s    
r   _FnzCallable[[_Fn], _Fn])targetr,   c                   s   ddd fdd}t | S )z'A signature-matching decorator factory.r   r   r,   c           
        sN  t | st | stdt| }i }t||}ttd|d td|dd  | j	f }t
|dd\}}t||d}|t|d	d
 | j	|d< t | rd|d< d|d< nd|d< d|d< dt|d v rd| }nd| }tj| j }|t| || || d| ji ttjt||| j	}	t| d| j|	_| |	_t|	| S )Nznot a decoratable functionzTuple[str, ...]r   r      r   r   )r   r   Fgroupedrp   zasync prefixzawait 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.   
isfunctionismethodrc   r   inspect_getfullargspec!_update_argspec_defaults_into_envr   r   rT   r   dictr?   format_argspec_plusiscoroutinefunctionreprrG   modulesrU   varstypesFunctionType_exec_code_in_envr8   __defaults____wrapped__r   )
r   specenvnamesZ	targ_namefn_namemetadatacodemodZ	decoratedr   r1   r2   decorate   sN    





	zdecorator.<locals>.decorater   )r   r   r1   r   r2   	decorator   s    Ar   c                 C  s|   | j rtg }d}| j D ]@}t|jdvrJd| }|||< || |d7 }q|| qt| }t||d< tj| S | S dS )zCgiven a FullArgSpec, convert defaults to be symbol names in an env.r   )builtins__builtin__zx%dr   r   N)defaultsr5   rU   r   listr   r   FullArgSpec)r   r   new_defaultsr   argrp   elemr1   r1   r2   r   =  s    



r   zUnion[str, types.CodeType]Dict[str, Any])r   r   r   r,   c                 C  s   t | | || S r-   )exec)r   r   r   r1   r1   r2   r   R  s    
r   _PF_TEc                   @  sJ   e Zd ZddddddZdd Zdd	d
ddZdddddddZdS )PluginLoaderNr;   zOptional[Callable[..., Any]])groupauto_fnc                 C  s   || _ i | _|| _d S r-   )r   implsr   )rJ   r   r   r1   r1   r2   __init__^  s    zPluginLoader.__init__c                 C  s   | j   d S r-   )r   clearrI   r1   r1   r2   r   e  s    zPluginLoader.clearr   )rp   r,   c                 C  s   || j v r| j |  S | jr:| |}|r:|| j |< | S t| jD ]&}|j|krF|j| j |< |   S qFtd| j|f d S )NzCan't load plugin: %s:%s)	r   r   r   importlib_metadata_getr   rp   loadr   NoSuchModuleError)rJ   rp   loaderimplr1   r1   r2   r   h  s    



zPluginLoader.loadrE   )rp   
modulepathobjnamer,   c                   s    fdd}|| j |< d S )Nc                    s4   t  }  ddd  D ]}t| |} qt| S )N.r   )
__import__splitr8   )r   tokenr   r   r1   r2   r   |  s    z#PluginLoader.register.<locals>.load)r   )rJ   rp   r   r   r   r1   r   r2   register{  s    zPluginLoader.register)N)rT   rU   rV   r   r   r   r   r1   r1   r1   r2   r   ]  s
    r   c                 C  sl   z
t j}W n0 ty:   t| }|d t|d f Y S 0 | j}|j}t|j	d | t|j
|@ fS d S )Nr   r   )r.   CO_VARKEYWORDSAttributeErrorr   r   rs   __code__co_argcountr   co_varnamesco_flags)r   Zco_varkeywordsr   conargsr1   r1   r2   _inspect_func_args  s    

r   )_setraiseerrr5   zOptional[Set[str]]zLiteral[True]zSet[str])rY   r   r   r,   c                C  s   d S r-   r1   rY   r   r   r1   r1   r2   get_cls_kwargs  s    r   Fc                C  s   d S r-   r1   r   r1   r1   r2   r     s    c          	      C  s   |du }|rt  }|dusJ | jdd}|oHt|tjoHt|jtj}|rt|\}}|	| |s|s|rt
d|  dqdS nd}|r|r| jD ]}t||ddu r qq|d |S )ae  Return 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 !

    Nr   Fz
given cls z  doesn't have an __init__ method)r   rJ   )rZ   r6   r7   r4   r   r   r   r   r   r?   	TypeError	__bases__r   discard)	rY   r   r   toplevelZctrZhas_initr   Zhas_kwcr1   r1   r2   r     s4    




z	List[str]funcr,   c                 C  s   t | d S )zReturn the set of legal kwargs for the given `func`.

    Uses getargspec so is safe to call for methods, functions,
    etc.

    r   )r   r   r   r1   r1   r2   get_func_kwargs  s    r   zcompat.FullArgSpec)r   no_self_is_initr,   c              	   C  sD  t | rtd|  n&t | rn|rb|rbt| }t|jdd |j|j	|j
|j|j|jS t| S nt | r|r|s| jrt| j}t|jdd |j|j	|j
|j|j|jS t| jS ntt | rt| j|ddS t| d rt| jS t| dr4t | jr&t| j|dS td	|  ntd	|  dS )
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.

    zCan't inspect builtin: %sr   NT)r   r   r   __call__)r   zCan't inspect callable: %s)r.   	isbuiltinr   r   r   r   r   argsvarargsvarkwr   
kwonlyargskwonlydefaultsr   r   __self__r   isclassget_callable_argspecr   r   r   )r   r   r   r   r1   r1   r2   r     sN    






r   z-Union[Callable[..., Any], compat.FullArgSpec]zDict[str, Optional[str]])r   r   r,   c              	   C  s  t | rt| }n| }tj| }t|d |d |d d|d }|d r|d d }t|d dd |d |d d|d }n"|d rd|d  }|}nd}|}d}|d r|tttt |d 7 }|d r|t|d 7 }|d |d  }|r|d| d }	nd}	tj||d |d |	d	d
 d}
|d rdtj|dd |d |d |	dd
 d}n|
}|rt||||
||dS t|||dd |
dd |dd |dd dS dS )a  Returns 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)'}

    r   r   r   N   z%s[0]r   r1   c                 S  s   dt |  S N=r   r<   r1   r1   r2   r   s  rl   z%format_argspec_plus.<locals>.<lambda>)formatvaluec                 S  s   dt |  S r   r   r   r1   r1   r2   r   |  rl   )grouped_argsself_arg	apply_posapply_kwapply_pos_proxiedapply_kw_proxied)	callabler   r   inspect_formatargspeclenr   r   r   r   )r   r   r   r   r  r  r  num_defaultsZ	name_argsZdefaulted_valsr  r  r1   r1   r2   r      sv    $
"

	



r   c                 C  sz   | t ju r(d}|rdnd}|r"dnd}n>zt| |dW S  tyd   d}|rP|nd}|r\dnd	}Y n0 td|||||d
S )a$  format_argspec_plus with considerations for typical __init__ methods

    Wraps format_argspec_plus with error handling strategies for typical
    __init__ cases:

    .. sourcecode:: text

      object.__init__ -> (self)
      other unreflectable (usually C) -> (self, *args, **kwargs)

    z(self)rJ   z()r   r   z(self, *args, **kwargs)zself, *args, **kwargsz(*args, **kwargs)z*args, **kwargs)r  r   r  r  r  r  )objectr   r   r   r   )methodr   r   r   Zproxiedr1   r1   r2   format_argspec_init  s$    
r  r1   zCallable[[_T], _T])
target_clstarget_cls_sphinx_nameproxy_cls_sphinx_nameclassmethodsmethods
attributesuse_intermediate_variabler,   c                 C  s   dd }|S )aS  A 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.

    c                 S  s   | S r-   r1   )rY   r1   r1   r2   r     s    z&create_proxy_methods.<locals>.decorater1   )r  r  r  r  r  r  r  r   r1   r1   r2   create_proxy_methods  s    r  c                 C  sR   zt | W S  tyL   | tju r6dgdddf Y S dgdddf Y S Y n0 dS )a  inspect.getargspec with considerations for typical __init__ methods

    Wraps inspect.getargspec with error handling for typical __init__ cases:

    .. sourcecode:: text

      object.__init__ -> (self)
      other unreflectable (usually C) -> (self, *args, **kwargs)

    rJ   Nr   kwargs)r   r   r   r  r   )r  r1   r1   r2   getargspec_init  s    
r  c                 C  s    t | tjr| js| jS | S dS )zSAdjust the incoming callable such that a 'self' argument is not
    required.

    N)r4   r   
MethodTyper   r   )Zfunc_or_clsr1   r1   r2   unbound_method_to_callable  s    r  zSequence[Tuple[str, Any]]z%Optional[Union[object, List[object]]])r+   additional_kw
to_inspect
omit_kwargr,   c              	     sP  |du rg}n
t |}t  g }t  }d}t|D ]\}}zt|j}	W n tyf   Y q8Y q80 |	j	rxt
|	j	nd}
|dkr|	jr|	j}|
r||	jd|
   q||	jdd  n$| fdd|	jd|
  D  |
r8|	j	sJ |dd t|	j|
 d |	j	D  q8g }|fdd|D  |durjt|rj|d	d t|D  | D ]d\}}||v rqrz6t| }| ur||kr|d
||f  W n ty   Y n0 qr|r:|D ]V\}}z6t| }| ur||kr|d
||f  W n ty4   Y n0 qdjjd|f S )z}Produce a __repr__() based on direct association of the __init__()
    specification vs. same-named attributes present.

    Nr   r   c                   s   g | ]}| fqS r1   r1   ri   r   )missingr1   r2   
<listcomp>  rl   z generic_repr.<locals>.<listcomp>c                 S  s   g | ]\}}||fqS r1   r1   )ri   r   defaultr1   r1   r2   r    s   c                 3  s   | ]}t t |d V  qd S r-   )r   r8   r  r0   r1   r2   rk   "  rl   zgeneric_repr.<locals>.<genexpr>c                 S  s   g | ]}t |qS r1   r   )ri   valr1   r1   r2   r  %  rl   z%s=%rz%s(%s), )r   to_listr  OrderedDict	enumerater   r   r   r   r   r	  r   r]   r   r?   zipr   r8   itemsr   rc   rv   rT   rm   )r+   r  r  r  Zpos_argsZkw_argsZvargsr   Zinspr   Zdefault_lenoutputr   Zdefvalr"  r1   )r  r+   r2   generic_repr  sj    






r*  c                   @  s6   e Zd ZdZdZdd Zdd Zddd	Zd
d ZdS )portable_instancemethodz_Turn an instancemethod into a (parent, name) pair
    to produce a serializable callable.

    )r   rp   r  __weakref__c                 C  s   | j | j| jdS )Nr   rp   r  r-  rI   r1   r1   r2   __getstate__E  s    z$portable_instancemethod.__getstate__c                 C  s&   |d | _ |d | _|dd| _d S )Nr   rp   r  r1   )r   rp   r7   r  )rJ   stater1   r1   r2   __setstate__L  s    

z$portable_instancemethod.__setstate__r1   c                 C  s   |j | _|j| _|| _d S r-   )r   r   rT   rp   r  )rJ   methr  r1   r1   r2   r   Q  s    z portable_instancemethod.__init__c                 O  s$   | | j t| j| j|i |S r-   )r?   r  r8   r   rp   )rJ   r   kwr1   r1   r2   r   V  s    z portable_instancemethod.__call__N)r1   )	rT   rU   rV   rW   rX   r.  r0  r   r   r1   r1   r1   r2   r+  =  s   
r+  c                   s   | h t | j}|r| } fdd|jD }|D ]}||  | q4|jdkst|dsdq fddt|t	s|
 n|
|D D ]}||  | qqt  S )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.

    c                 3  s   | ]}| vr|V  qd S r-   r1   ri   _Zhierr1   r2   rk   j  rl   z"class_hierarchy.<locals>.<genexpr>r   r^   c                   s   g | ]}| vr|qS r1   r1   r3  r5  r1   r2   r  s  s   z#class_hierarchy.<locals>.<listcomp>)r   __mro__r[   r   r   r\   rU   r   
issubclassr5   r^   )rY   processr   r   r   sr1   r5  r2   class_hierarchy[  s$    




	
r:  c                 c  s@   t | }|D ].}| jD ]"}||jv r||j| fV   qqqdS )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)dirr6  r6   )rY   keyskeyr   r1   r1   r2   iterate_attributes  s    

r>  
self.proxyc              	     s4  |r
|}n$du rd fddt |D }|D ]}z4t||}t|dsPW q2t|d|}ttj|}	W n ty   Y q2Y n0 z2t|	}
t	|
d }t	|
d dd }W n t
y   d	}d
}Y n0 dt  }|dur||ipi }t|| z|	j|| _W n ty   Y n0 t |||  q2dS )z9Automates delegation of __specials__ for a proxying type.N)rX   __del____getattribute____metaclass__r.  r0  c                   s6   g | ].}| d r|d rt |s|vr|qS )r   )
startswithendswithr   ri   rA   into_clsskipr1   r2   r    s   


z0monkeypatch_proxied_specials.<locals>.<listcomp>r   r   r   r   z(self, *args, **kw)z(*args, **kw)z?def %(method)s%(fn_args)s: return %(name)s.%(method)s%(d_args)s)r;  r8   r   r   r   r   r   r   r   r  r   localsr   r   setattr)rG  Zfrom_clsrH  onlyrp   Zfrom_instanceZdundersr  Zmaybe_fnr   r   Zfn_argsZd_argspyr   r1   rF  r2   monkeypatch_proxied_specials  sF    






rM  c                 C  s   t | d| t |d|u S )z;Return True if the two methods are the same implementation.r   )r8   )Zmeth1Zmeth2r1   r1   r2   methods_equivalent  s    rN  c                 C  sp  |s|st dt|tr(t| |r(| S t|p>dd t|D }tt| }tj}t|trd|}n|svt }tj}nt|}||||r| S t| t	s|tju rdpd}t d| |d
|f G dd	 d	}|rd
|j |_t }	t| D ]R\}
}|
|vrt d|
 t|s*t d|
|f t||
t| |	|
 q||	|rV|S t dd
||	  dS )a  Ensure 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 requiredc                 S  s   g | ]}| d s|qS )r4  )rC  rE  r1   r1   r2   r    rl   z as_interface.<locals>.<listcomp>zany ofzall ofz%r does not implement %s: %sr#  c                   @  s   e Zd ZdZdS )z(as_interface.<locals>.AnonymousInterfacezA callable-holding shell.NrT   rU   rV   rW   r1   r1   r1   r2   AnonymousInterface  s   rP  Z	Anonymousz%r: unknown in this interfacez%r=%r is not callablez,dictionary does not contain required keys %sN)r   r4   r5   rZ   r;  operatorgegtintersectionr   rm   rT   dictlike_iteritemsr  rJ  staticmethodr\   )r+   rY   r  requiredZ	interfaceZimplementedZcompliesZ	qualifierrP  foundr  r   r1   r1   r2   as_interface  sP    !



rY  _GFDzgeneric_fn_descriptor[Any]c                   @  s   e Zd ZU dZded< ded< ded< d$ddd	d
dZedddddddZeddddddZdddddddZerddddddZ	dddddZ
ddddd Zedddd!d"d#ZdS )%generic_fn_descriptorag  Descriptor 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.

    zCallable[..., _T_co]fgetre   rW   r;   rT   Nr\  docc                 C  s   || _ |p|j| _|j| _d S r-   r\  rW   rT   rJ   r\  r^  r1   r1   r2   r   D  s    zgeneric_fn_descriptor.__init__rZ  rE   r   rJ   r+   rY   r,   c                 C  s   d S r-   r1   rJ   r+   rY   r1   r1   r2   __get__I  s    zgeneric_fn_descriptor.__get__r  r!   r+   rY   r,   c                 C  s   d S r-   r1   rb  r1   r1   r2   rc  L  s    zUnion[_GFD, _T_co]c                 C  s
   t  d S r-   NotImplementedErrorrb  r1   r1   r2   rc  O  s    instancerM   r,   c                 C  s   d S r-   r1   rJ   rh  rM   r1   r1   r2   __set__T  rl   zgeneric_fn_descriptor.__set__rh  r,   c                 C  s   d S r-   r1   )rJ   rh  r1   r1   r2   
__delete__V  rl   z generic_fn_descriptor.__delete__r*   c                 C  s
   t  d S r-   re  rJ   r+   r1   r1   r2   _resetX  s    zgeneric_fn_descriptor._reset)r+   rp   r,   c                 C  s
   t  d S r-   re  rY   r+   rp   r1   r1   r2   reset[  s    zgeneric_fn_descriptor.reset)N)rT   rU   rV   rW   r3   r   r   rc  r   rj  rl  rn  classmethodrp  r1   r1   r1   r2   r[  5  s    

r[  c                   @  s   e Zd ZdZesdd ZdS )_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.

    c                 C  s   |d u r| S |  |S r-   r\  rb  r1   r1   r2   rc  k  s    z_non_memoized_property.__get__N)rT   rU   rV   rW   r   rc  r1   r1   r1   r2   rr  `  s   rr  c                   @  s0   e Zd ZdZesdd Zdd Zedd ZdS )	_memoized_propertyz2A read-only @property that is only evaluated once.c                 C  s&   |d u r| S |  | |j| j< }|S r-   )r\  r6   rT   rJ   r+   rY   resultr1   r1   r2   rc  v  s    z_memoized_property.__get__c                 C  s   t || j d S r-   )rt  rp  rT   rm  r1   r1   r2   rn  |  s    z_memoized_property._resetc                 C  s   |j |d  d S r-   )r6   r[   ro  r1   r1   r2   rp    s    z_memoized_property.resetN)	rT   rU   rV   rW   r   rc  rn  rq  rp  r1   r1   r1   r2   rt  q  s   rt  r   c                   s    fdd}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.

    c                   sB   | g|R i |  fdd}j |_ j|_|| jj <  S )Nc                    s    S r-   r1   ar2  rv  r1   r2   memo  s    z6memoized_instancemethod.<locals>.oneshot.<locals>.memo)rT   rW   r6   rJ   r   r2  rz  r   ry  r2   oneshot  s    z(memoized_instancemethod.<locals>.oneshotr   )r   r}  r1   r|  r2   memoized_instancemethod  s    	r~  c                   @  s~   e Zd ZU dZesdZe Zded< ddddZ	ddd	d
Z
ddddddZG dd dee ZedddddZdS )HasMemoizedzA mixin class that maintains the names of memoized elements in a
    collection for easy cache clearing, generative, etc.

    r1   zFrozenSet[str]_memoized_keysrE   rF   c                 C  s   | j D ]}| j|d  qd S r-   )r  r6   r[   rJ   r   r1   r1   r2   _reset_memoizations  s    
zHasMemoized._reset_memoizationsc                 C  s   | j D ]}|| jvsJ qd S r-   )r  r6   r  r1   r1   r2   _assert_no_memoizations  s    
z#HasMemoized._assert_no_memoizationsr;   r   )r=  rM   r,   c                 C  s   || j |< |  j|hO  _d S r-   )r6   r  )rJ   r=  rM   r1   r1   r2   _set_memoized_attribute  s    
z#HasMemoized._set_memoized_attributec                   @  sr   e Zd ZU dZded< ded< ded< dddd	d
dZedddddddZeddddddZdd ZdS )zHasMemoized.memoized_attributezTA read-only @property that is only evaluated once.

        :meta private:

        Callable[..., _T]r\  re   rW   r;   rT   Nr]  c                 C  s   || _ |p|j| _|j| _d S r-   r_  r`  r1   r1   r2   r     s    z'HasMemoized.memoized_attribute.__init__r&   rE   r   ra  c                 C  s   d S r-   r1   rb  r1   r1   r2   rc    s    z&HasMemoized.memoized_attribute.__get__r    rd  c                 C  s   d S r-   r1   rb  r1   r1   r2   rc    s    c                 C  s8   |d u r| S |  | |j| j< }| j| jhO  _|S r-   )r\  r6   rT   r  ru  r1   r1   r2   rc    s
    )N)rT   rU   rV   rW   r3   r   r   rc  r1   r1   r1   r2   memoized_attribute  s   
r  r#   r   c                   s"   ddddd fdd}t | S )zMDecorate a method memoize its return value.

        :meta private:

        r   )rJ   r   r2  r,   c                   sT   | g|R i |  fdd}j |_ j|_|| jj < |  jj hO  _ S )Nc                    s    S r-   r1   rw  ry  r1   r2   rz    s    zBHasMemoized.memoized_instancemethod.<locals>.oneshot.<locals>.memo)rT   rW   r6   r  r{  r|  ry  r2   r}    s    z4HasMemoized.memoized_instancemethod.<locals>.oneshotr   )rY   r   r}  r1   r|  r2   r~    s    z#HasMemoized.memoized_instancemethodN)rT   rU   rV   rW   r   rX   	frozensetr  r3   r  r  r  memoized_propertyr    r  rq  r~  r1   r1   r1   r2   r    s   
r  c                   @  s,   e Zd ZdZdZdd Zddddd	Zd
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__.

    r1   c                 C  s   t |d S r-   )r   )rJ   r=  r1   r1   r2   _fallback_getattr  s    zMemoizedSlots._fallback_getattrr;   r   )r=  r,   c                   s    ds drtn|tjd rRtd  }t| |S tjd rtd   fdd} j|_|S S d S )NZ_memoized_attr_Z_memoized_method_c                    s:   | i |  fdd}j |_ j|_t|  S )Nc                    s    S r-   r1   rw  ry  r1   r2   rz  )  s    z8MemoizedSlots.__getattr__.<locals>.oneshot.<locals>.memo)rT   rW   rJ  )r   r2  rz  r   r=  rJ   ry  r2   r}  &  s    z*MemoizedSlots.__getattr__.<locals>.oneshot)rC  r   r   rv   r8   rJ  rW   r  )rJ   r=  rM   r}  r1   r  r2   __getattr__  s    
zMemoizedSlots.__getattr__N)rT   rU   rV   rW   rX   r  r  r1   r1   r1   r2   r  
  s   r  c                 C  sB   t | tr:|   } | dv r"dS | dv r.dS td|  t| S )N)trueyesonyt1T)falsenooffrj   f0FzString is not true/false: %r)r4   r;   striprh   
ValueErrorrs   r0   r1   r1   r2   asbool8  s    
r  z!Callable[[str], Union[str, bool]])textr,   c                    s   ddd fdd}|S )zqReturn a callable that will evaluate a string as
    boolean, or one of a set of "alternate" string values.

    r;   zUnion[str, bool]r*   c                   s   |  v r| S t | S d S r-   )r  r0   r  r1   r2   bool_or_valueJ  s    z"bool_or_str.<locals>.bool_or_valuer1   )r  r  r1   r  r2   bool_or_strD  s    r  Optional[int])rM   r,   c                 C  s   | du r| S t | S )zCoerce to integer.N)r   )rM   r1   r1   r2   asintS  s    r  zOptional[Dict[str, Any]]rE   )r2  r=  rL   
flexi_booldestr,   c                 C  sj   |du r| }|| v rft |tr,t | | |sf| | durf|tu rV|rVt| | ||< n|| | ||< dS )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)r4   r5   rs   r  )r2  r=  rL   r  r  r1   r1   r2   coerce_kw_type[  s    
r  rd  c                   s$   t |}|ft fdd|D  S )zbProduce a tuple structure that is cacheable using the __dict__ of
    obj to retrieve values

    c                 3  s&   | ]}| j v r| j | fV  qd S r-   r6   ri   kr0   r1   r2   rk   {  s   z"constructor_key.<locals>.<genexpr>)r   r   )r+   rY   r   r1   r0   r2   constructor_keyu  s    r  )r+   rY   r   r2  r,   c                   s4   t |}| fdd||D  ||i |S )zInstantiate cls using the __dict__ of obj as constructor arguments.

    Uses inspect to match the named arguments of ``cls``.

    c                 3  s&   | ]}| j v r| j | fV  qd S r-   r  r  r0   r1   r2   rk     s   z#constructor_copy.<locals>.<genexpr>)r   r?   
difference)r+   rY   r   r2  r   r1   r0   r2   constructor_copy  s
    r  zCallable[[], int]rF   c                    s$   t  td  fdd} | S )z%Return a threadsafe counter function.r   c                     s0    t  W  d    S 1 s"0    Y  d S r-   )nextr1   counterlockr1   r2   _next  s    zcounter.<locals>._next)	threadingLockr   count)r  r1   r  r2   r    s    
r  zOptional[Type[Any]])specimenr   r,   c                 C  s   t | dr*| jdur$t| jtr$tS | jS t| tr8tnt}|| trJtS || trXtS || trftS t | drttS t | drtS t | drtS |S d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   r\   rZ   )r   r  r7  rZ   r4   r5   r   r   )r  r   Zisar1   r1   r2   duck_type_collection  s(    






r  z'Union[Tuple[Type[Any], ...], Type[Any]])r   argtyperp   r,   c                 C  s^   t | |r| S t |trBtd|ddd |D t| f ntd||t| f d S )Nz8Argument '%s' is expected to be one of type %s, got '%s'z or c                 s  s   | ]}d | V  qdS )z'%s'Nr1   )ri   rx  r1   r1   r2   rk     rl   z"assert_arg_type.<locals>.<genexpr>z6Argument '%s' is expected to be of type '%s', got '%s')r4   r   r   ArgumentErrorrm   r5   )r   r  rp   r1   r1   r2   assert_arg_type  s    

r  c                   s   t  drt  S t dt dddu r>td  t  dr\ fdd}| S t  d	rtfd
d  D S td  dS )z?Return a (key, value) iterator for almost any dict-like object.r(  __getitem__r7   NzObject '%r' is not dict-likeiterkeysc                  3  s,      D ]} d usJ | | fV  qd S r-   )r  )r=  dictlikegetterr1   r2   iterator  s    z$dictlike_iteritems.<locals>.iteratorr<  c                 3  s   | ]}| |fV  qd S r-   r1   )ri   r=  )r  r1   r2   rk     rl   z%dictlike_iteritems.<locals>.<genexpr>)r   r   r(  r8   r   iterr<  )r  r  r1   r  r2   rU    s    


rU  c                      sH   e Zd ZU dZded< dddd fddZddd	dd
ddZ  ZS )classpropertyaA  A 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.

    zCallable[[Any], Any]r\  r   )r\  r   r2  c                   s&   t  j|g|R i | |j| _d S r-   )superr   rW   )rJ   r\  r   r2  rv   r1   r2   r     s    zclassproperty.__init__NzOptional[type]rd  c                 C  s
   |  |S r-   rs  rb  r1   r1   r2   rc    s    zclassproperty.__get__)N)rT   rU   rV   rW   r3   r   rc  __classcell__r1   r1   r  r2   r    s   

r  c                   @  s<   e Zd ZddddZdddddd	Zd
ddddZdS )hybridpropertyr  r   c                 C  s   || _ || _d S r-   )r   clslevelrJ   r   r1   r1   r2   r     s    zhybridproperty.__init__r   r    rh  ownerr,   c                 C  s$   |d u r|  |}|S | |S d S r-   r  r   rJ   rh  r  Zclsvalr1   r1   r2   rc    s    
zhybridproperty.__get__rr   zhybridproperty[_T]r   c                 C  s
   || _ | S r-   r  r  r1   r1   r2   
classlevel
  s    zhybridproperty.classlevelN)rT   rU   rV   r   rc  r  r1   r1   r1   r2   r    s   r  c                   @  s^   e Zd ZddddZdddddd	Zddd
dddZdddddZdddddZdS )rw_hybridpropertyr  r   c                 C  s   || _ || _d | _d S r-   )r   r  setfnr  r1   r1   r2   r     s    zrw_hybridproperty.__init__r   r    r  c                 C  s$   |d u r|  |}|S | |S d S r-   r  r  r1   r1   r2   rc    s    
zrw_hybridproperty.__get__rE   rg  c                 C  s   | j d usJ |  || d S r-   r  ri  r1   r1   r2   rj    s    zrw_hybridproperty.__set__rr   zrw_hybridproperty[_T]r   c                 C  s
   || _ | S r-   r  r  r1   r1   r2   setter   s    zrw_hybridproperty.setterc                 C  s
   || _ | S r-   r  r  r1   r1   r2   r  $  s    zrw_hybridproperty.classlevelN)rT   rU   rV   r   rc  rj  r  r  r1   r1   r1   r2   r    s
   r  c                   @  s@   e Zd ZdZddddZdddddd	Zd
ddddZdS )hybridmethodz/Decorate a function as cls- or instance- level.r  r   c                 C  s   | | _ | _|| _d S r-   )r   r   r  r  r1   r1   r2   r   ,  s    zhybridmethod.__init__r   r  c                 C  s*   |d u r| j ||jS | j||S d S r-   )r  rc  rv   r   )rJ   rh  r  r1   r1   r2   rc  0  s    zhybridmethod.__get__rr   zhybridmethod[_T]r   c                 C  s
   || _ | S r-   r  r  r1   r1   r2   r  6  s    zhybridmethod.classlevelN)rT   rU   rV   rW   r   rc  r  r1   r1   r1   r2   r  )  s   r  c                   @  s\   e Zd ZU dZded< i Zded< e Zddddd d	d
dZ	dd Z
dd Zdd ZdS )symbolaI  A constant symbol.

    >>> symbol("foo") is symbol("foo")
    True
    >>> symbol("foo")
    <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;   rp   zDict[str, symbol]symbolsNre   r  )rp   r^  	canonicalr,   c                 C  s   | j  | j|}|d u rbt|ts*J |d u r:t|}tt|}||_	|rV||_
|| j|< n |r||krtd|d| |W  d    S 1 s0    Y  d S )Nz#Can't replace canonical symbol for z with new int value )_lockr  r7   r4   r;   hashr   __new__r  rp   rW   r   )rY   rp   r^  r  r   r1   r1   r2   r  O  s$    zsymbol.__new__c                 C  s   t | jdt| ffS )Nr<   )r  rp   r   rI   r1   r1   r2   
__reduce__m  s    zsymbol.__reduce__c                 C  s   t | S r-   r!  rI   r1   r1   r2   __str__p  s    zsymbol.__str__c                 C  s   d| j dS )Nzsymbol()rp   rI   r1   r1   r2   __repr__s  s    zsymbol.__repr__)NN)rT   rU   rV   rW   r3   r  r  r  r  r  r  r  r  r1   r1   r1   r2   r  ;  s   
  r  c                   @  s0   e Zd ZddddddddZd	d
ddZdS )_IntFlagMetar;   zTuple[Type[Any], ...]r   r   rE   )	classnamer   dict_r2  r,   c           	      K  s   g  | _ }| D ]Z\}}td|r(qt|tr@t||d}n|dstdnqt	| || |
| qtdd |D | _d S )Nz^__.*__$)r  r4  z#Expected integer values for IntFlagc                 S  s   i | ]}|j |qS r1   r  )ri   r   r1   r1   r2   
<dictcomp>  rl   z)_IntFlagMeta.__init__.<locals>.<dictcomp>)Z_itemsr(  rn   matchr4   r   r  rC  r   rJ  r   r   immutabledict__members__)	rY   r  r   r  r2  r(  r  vr   r1   r1   r2   r   x  s    



z_IntFlagMeta.__init__zIterator[symbol]rF   c                 C  s   t dd S )Nziter not implemented to ensure compatibility with Python 3.11 IntFlag.  Please use __members__.  See https://github.com/python/cpython/issues/99304re  rI   r1   r1   r2   __iter__  s    z_IntFlagMeta.__iter__N)rT   rU   rV   r   r  r1   r1   r1   r2   r  w  s   r  c                   @  s   e Zd ZdZdS )_FastIntFlagzAn 'IntFlag' copycat that isn't slow when performing bitwise
    operations.

    the ``FastIntFlag`` class will return ``enum.IntFlag`` under TYPE_CHECKING
    and ``_FastIntFlag`` otherwise.

    NrO  r1   r1   r1   r2   r    s   r  )	metaclass)IntFlag_EzDict[_E, List[Any]]zOptional[_E])r   choicesrp   resolve_symbol_namesr,   c                 C  sn   |  D ]>\}}| |u r |  S |r6| |jkr6|  S | |v r|  S q| du rTdS td| d| dS )aO  Given 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.

    NzInvalid value for 'z': )r(  rp   r   r  )r   r  rp   r  Z
enum_valuechoicer1   r1   r2   parse_user_argument_for_enum  s    
r  rk  c                 C  s   t | _ t d7 a dS )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).

    r   N)_creation_order)rh  r1   r1   r2   set_creation_order  s    	r  )r   r   r  r,   c                 O  s@   z| |i |W S  t y:   tdt dd   Y n0 dS )zXexecutes the given function, catches all exceptions and converts to
    a warning.

    z%s('%s') ignoredr   r   N)rc   warnrG   rH   )r   r   r  r1   r1   r2   warn_exception  s    r     c                 C  sD   z(t | |kr d| d|  W S | W S W n ty>   |  Y S 0 d S )Nz%s...r   )r	  r   )rM   Zlen_r1   r1   r2   ellipses_string  s    
r  c                      sT   e Zd ZU dZded< dddd d fddZdd	d
dZdddddZ  ZS )_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])rM   numr   r,   c                   s<   || d|  }t  | |}td|t|| f |_|S )Nz6 (this warning may be suppressed after %d occurrences)z%s_%d)r  r  r  r  )rY   rM   r  r   ZinterpolatedrJ   r  r1   r2   r    s    z_hash_limit_string.__new__rF   c                 C  s   | j S r-   )r  rI   r1   r1   r2   __hash__  s    z_hash_limit_string.__hash__r   rs   )otherr,   c                 C  s   t | t |kS r-   )r  )rJ   r  r1   r1   r2   __eq__  s    z_hash_limit_string.__eq__)	rT   rU   rV   rW   r3   r  r  r  r  r1   r1   r  r2   r    s
   


r  )msgr   r,   c                 C  s(   |rt tj| |d nt | tj dS )zdIssue a warning.

    If msg is a string, :class:`.exc.SAWarning` is used as
    the category.

    )r   N)_warnings_warnr   	SAWarning)r  r   r1   r1   r2   r    s    r  r  )r  r   r,   c                 C  s    |rt | d|} t| tj dS )z\Issue a warning with a parameterized string, limiting the number
    of registrations.

    
   N)r  r  r   r  )r  r   r1   r1   r2   warn_limited   s    r  z)Dict[CodeType, Tuple[str, Type[Warning]]]_warning_tagszType[Warning]zCallable[[_F], _F])messagecategoryr,   c                   s    fdd}|S )Nc                   s    ft | j< | S r-   )r  r   r|  r  r   r1   r2   go0  s    z#tag_method_for_warnings.<locals>.gor1   )r   r  r  r1   r  r2   tag_method_for_warnings-  s    r  z&^(?:sqlalchemy\.(?!testing)|alembic\.)zUnion[str, Warning]zOptional[Type[Warning]])r   r  
stacklevelr,   c                 C  s   zt |}W n$ ty$   d}Y n   d}Y n0 d }}|d ur|sbtt|jddsbd}|jt	v rd}t	|j \}}|p|}|  d| d} |j
}|s|d7 }q<|r<|r<qq<|d urtj| ||d d	 ntj| |d d	 d S )
Nr   FrT   r   Tz (r  r   )r  )rG   	_getframer  rn   r  _not_sa_pattern	f_globalsr7   f_coder  f_backwarningsr  )r   r  r  frameZstacklevel_foundZwarning_tag_foundZ_suffixZ	_categoryr1   r1   r2   r  :  s2    


r  r  zCallable[..., Optional[_T]])r   retry_on_exceptionr,   c                   s$    gdddd fdd}|S )zNDecorate the given function to be a no-op after it is called exactly
    once.r   zOptional[_T]r   r2  r,   c                    sD    }r@  }z|| i |W S    r8d|  Y n0 d S )Nr   )r[   insert)r   r2  Z	strong_fnZonce_fnr   oncer  r1   r2   r  u  s    zonly_once.<locals>.gor1   )r   r  r  r1   r  r2   	only_oncem  s    r  z%sqlalchemy/([a-z_]+/){0,2}[a-z_]+\.pyzunit(?:2|test2?/)zre.Pattern[str])tbexclude_prefixexclude_suffixr,   c                 C  s`   d}t | d }||kr0|| | r0|d7 }q||krP|| | rP|d8 }q0| ||d  S )at  Chop 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``
    r   r   )r	  search)r  r  r  r|   endr1   r1   r2   chop_traceback  s    

r  c                 C  s$   d|  }t   }t|| |d S )Nz&def set(obj, value):    obj.%s = valuerZ   )rI  copyr   )attrnamer   r   r1   r1   r2   
attrsetter  s    

r  z^__.+__$c                      s*   e Zd ZdZdZdd fddZ  ZS )
TypingOnlyzA mixin class that marks a class as 'typing only', meaning it has
    absolutely no methods, attributes, or runtime functionality whatsoever.

    r1   rE   rF   c                   sB   t | jv r4dd | jD }|r4td|  d| dt   d S )Nc                 S  s   h | ]}t |s|qS r1   )_dundersr  ri   rp   r1   r1   r2   	<setcomp>  s   z/TypingOnly.__init_subclass__.<locals>.<setcomp>zClass z< directly inherits TypingOnly but has additional attributes r   )r  r   r6   AssertionErrorr  __init_subclass__)rY   	remainingr  r1   r2   r!    s    
zTypingOnly.__init_subclass__)rT   rU   rV   rW   rX   r!  r  r1   r1   r  r2   r    s   r  c                      sD   e Zd ZU dZded< dd fddZeddd	d
dZ  ZS )EnsureKWArga6  Apply 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_kwargrE   rF   c                   sf   | j }| j}|rX|D ]B}t||}|r|| }t|}|js| |}t| || qt	 
  d S r-   )r$  r6   rn   r  r   r   r   
_wrap_w_kwrJ  r  r!  )rY   Zfn_regZclsdictr=  rA   r   r   wrappedr  r1   r2   r!    s    

zEnsureKWArg.__init_subclass__rr   r   c                   s    dddd fdd}t | S )Nr   r  c                    s    |  S r-   r1   )r   r2  r|  r1   r2   wrap  s    z$EnsureKWArg._wrap_w_kw.<locals>.wrapr   )rY   r   r'  r1   r|  r2   r%    s    zEnsureKWArg._wrap_w_kw)	rT   rU   rV   rW   r3   r!  rq  r%  r  r1   r1   r  r2   r#    s
   
		r#  c                 C  sj   t |drt| |S | }|jj|_t |dr4|j|_t |jdrT|jjrT|jj|_n|jrb|j|_|S dS )zAugment functools.update_wrapper() to work with objects with
    a ``__call__()`` method.

    :param fn:
      object with __call__ method

    rT   rU   rW   N)r   r   rv   rT   rU   r   rW   )wrapperr   _fr1   r1   r2   wrap_callable  s    



r*  c                 C  s   d| vr|  dS d}g g}d}t| }||k r| | }|dkr|dkr|||d k r|| |d  dkr||d d |d7 }q|dN }n*|dkr|dkr|g  n|d | |d7 }q(dd |D S )a  Parse 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']

    "r   r   r   r  c                 S  s   g | ]}d  |qS )r   )rm   )ri   r   r1   r1   r2   r  1  rl   z'quoted_token_parser.<locals>.<listcomp>)r   r	  r   )rM   r/  rv  idxlvcharr1   r1   r2   quoted_token_parser  s$    
$


r/  )paramsr  r,   c                   s   t    fdd}|S )Nc                   s:   | j d ur| j pd}|r0t|fdd D }|| _ | S )Nr   c                   s   i | ]
}| qS r1   r1   )ri   paramr  r1   r2   r  :  rl   z8add_parameter_text.<locals>.decorate.<locals>.<dictcomp>)rW   inject_param_text)r   r^  r0  r  r1   r2   r   7  s
    z$add_parameter_text.<locals>.decorate)r   r$  )r0  r  r   r1   r3  r2   add_parameter_text4  s    
r4  c                 C  sN   |  dd}t|dkr| S |\}}|ds@|d t| S t| S d S )N
r   rg   )r   r	  rC  textwrapdedent)r  Z
split_text	firstliner"  r1   r1   r2   _dedent_docstringA  s    
r9  )given_doctext
injecttextposr,   c                 C  s   t | pd}|d}t|dkr,|d t|d}|d rP|dd dd t|D }|dd |t|t|d  }|d| | ||d   }d	|S )Nr   r5  r   r   c                 S  s   g | ]\}}|  s|qS r1   )r  )ri   r  liner1   r1   r2   r  X  rl   z)inject_docstring_text.<locals>.<listcomp>)
r9  r   r	  r   r6  r7  r  r&  minrm   )r:  r;  r<  doctextlinesZinjectlinesZblanksZ
inject_posr1   r1   r2   inject_docstring_textM  s    

rA  z(\s+):param (.+?):zDict[str, str])r?  inject_paramsr,   c           
      C  s  t |  }g }d }|r| }t|}|d u r|r|dd}||v rdt|d d }|rt	d|d }	|	rdt|	d }|||  }nV|r|
d|dg d }n<| s|
||dg d }n|dr|
|| g q|| qd|S )	Nr   *rg   r   z(\s+)\Sr   r5  z::)collectionsdeque
splitlinespopleft
_param_regr  r   lstripr	  rn   r]   rstriprD  r   rm   )
r?  rB  Zdoclinesr@  Z	to_injectr=  rA   r1  indentZm2r1   r1   r2   r2  d  s6    

r2  )r   r,   c                 C  s   t | dkrdS t | dk}|r,| dd n| dd | dd  } dd | D }|r`d|S d	d|dd |d f S dS )
zTrims a list of strings from the middle and return a string of up to
    four elements. Strings greater than 11 characters will be truncatedr   Nr   r   r  c                 S  s,   g | ]$}t |d kr$d|dd   n|qS )   z%s..N)r	  r  r1   r1   r2   r    rl   z$repr_tuple_names.<locals>.<listcomp>r#  z%s, ..., %s)r	  rm   )r   flagresr1   r1   r2   repr_tuple_names  s    (
rO  c                 C  s   t rdS | rtdndS d S )NTzDcython extensions were expected to be installed, but are not presentF)r   ImportError)Zraise_r1   r1   r2   has_compiled_ext  s    rQ  c                   @  s   e Zd Ze ZdS )_MissingN)rT   rU   rV   enumautoMissingr1   r1   r1   r2   rR    s   rR  )N)FF)T)T)r1   r1   r1   r1   )r1   Nr1   )NNr?  N)NNN)TN)N)F)r  )N)Nr   )F)rW   
__future__r   rD  rS  	functoolsr   r.   r   rQ  rn   rG   r6  r  r   r   typingr   r   r   r	   r
   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r   r   r   _has_cyr   r   r   r    r!   r#   r%   r&   r'   r(   py310r/   rB   rC   ra   rd   rq   rx   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r  r  r*  r+  r:  r>  rM  rN  rY  rZ  r[  rr  rt  r  non_memoized_propertypropertyro_memoized_propertyro_non_memoized_propertyr~  r  !HasMemoized_ro_memoized_attributer  r  r  r  r  r  r  r  r  r  r  rU  r  r  r  r  r   r  r5   r  r  r  FastIntFlagEnumr  r  r  r  r  r  r;   r  r  r  r  r3   r  compiler  r  r  Z_SQLA_REZ_UNITTEST_REr  NoneTyper  r  r  r#  r*  r/  r4  r9  rA  rH  r2  rO  rQ  rR  rU  Z	MissingOrr1   r1   r1   r2   <module>	   sl  ;	G(59u%     N&   
CV+M. #<"
"


  3 ),+