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   i/var/www/html/cobodadashboardai.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   Zmd5_not_for_securityupdater   r;   	hexdigest)r<   mr1   r1   r2   md5_hexW   s    

rA   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]]rC   Noner,   c                 C  s   t  | _d S r-   )sysexc_inforC   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-   )rC   with_traceback)rI   rK   rL   rM   exc_type	exc_valueexc_tbr1   r1   r2   __exit__   s    zsafe_reraise.__exit__N)__name__
__module____qualname____doc__	__slots__r3   rJ   rR   r1   r1   r1   r2   rB   ^   s
   

rB   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__)rX   seenstackr1   r1   r2   walk_subclasses   s    
r`   )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)ra   r1   r1   r2   string_or_unprintable   s    

rc   z	Type[Any]Optional[str])rX   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))rS   joinrefindall)rX   re   namer1   r1   r2   clsname_as_plain_name   s    
rp   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__rS   r8   )rs   rt   Zcurrent_clsmethod_nameZcurrent_methodr1   r1   r2   method_is_overridden   s    

rw   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hasattrrz   appendtuple)ry   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>   rk   z!_unique_symbols.<locals>.<lambda>i  z&exhausted namespace for symbol base %s)rY   	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])fnri   r,   c                 c  s*   |r&|| d @ }| |V  ||N }q dS )z6Call the given function given each nonzero bit from n.r   Nr1   )r   ri   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groupedro   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)
rS   __func__)r.   
isfunctionismethodrb   r   inspect_getfullargspec!_update_argspec_defaults_into_envr   r   rS   r   dictr>   format_argspec_plusiscoroutinefunctionreprrF   modulesrT   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   rT   r   listr   r   FullArgSpec)r   r   Znew_defaultsr   argro   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   )rI   r   r   r1   r1   r2   __init__^  s    zPluginLoader.__init__c                 C  s   | j   d S r-   )r   clearrH   r1   r1   r2   r   e  s    zPluginLoader.clearr   )ro   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   Zimportlib_metadata_getr   ro   loadr   ZNoSuchModuleError)rI   ro   loaderimplr1   r1   r2   r   h  s    



zPluginLoader.loadrD   )ro   
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   )rI   ro   r   r   r   r1   r   r2   register{  s    zPluginLoader.register)N)rS   rT   rU   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   rr   __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])rX   r   r   r,   c                C  s   d S r-   r1   rX   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   rI   )rY   r6   r7   r4   r   r   r   r   r   r>   	TypeError	__bases__r   discard)	rX   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  rk   z%format_argspec_plus.<locals>.<lambda>)formatvaluec                 S  s   dt |  S r   r   r   r1   r1   r2   r   |  rk   )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)rI   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   )rX   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)

    rI   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   rh   r   )missingr1   r2   
<listcomp>  rk   z generic_repr.<locals>.<listcomp>c                 S  s   g | ]\}}||fqS r1   r1   )rh   r   defaultr1   r1   r2   r    s   c                 3  s   | ]}t t |d V  qd S r-   )r   r8   r  r0   r1   r2   rj   "  rk   zgeneric_repr.<locals>.<genexpr>c                 S  s   g | ]}t |qS r1   r   )rh   valr1   r1   r2   r  %  rk   z%s=%rz%s(%s), )r   to_listr  OrderedDict	enumerater   r   r   r   r   r  r   r\   r   r>   zipr~   r8   itemsr   rb   ru   rS   rl   )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   ro   r  __weakref__c                 C  s   | j | j| jdS )Nr   ro   r  r)  rH   r1   r1   r2   __getstate__E  s    z$portable_instancemethod.__getstate__c                 C  s&   |d | _ |d | _|dd| _d S )Nr   ro   r  r1   )r   ro   r7   r  )rI   stater1   r1   r2   __setstate__L  s    

z$portable_instancemethod.__setstate__r1   c                 C  s   |j | _|j| _|| _d S r-   )r   r   rS   ro   r  )rI   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   ro   )rI   r   kwr1   r1   r2   r   V  s    z portable_instancemethod.__call__N)r1   )	rS   rT   rU   rV   rW   r*  r,  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   rh   _Zhierr1   r2   rj   j  rk   z"class_hierarchy.<locals>.<genexpr>r   r]   c                   s   g | ]}| vr|qS r1   r1   r/  r1  r1   r2   r  s  s   z#class_hierarchy.<locals>.<listcomp>)r   __mro__rZ   r   r   r[   rT   r~   
issubclassr5   r]   )rX   processr   r   r   sr1   r1  r2   class_hierarchy[  s$    




	
r6  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)dirr2  r6   )rX   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)rW   __del____getattribute____metaclass__r*  r,  c                   s6   g | ].}| d r|d rt |s|vr|qS )r   )
startswithendswithr~   rh   r@   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)r7  r8   r~   r   r   r   r   r   r   r  r   localsr   r   setattr)rC  Zfrom_clsrD  onlyro   Zfrom_instanceZdundersr  Zmaybe_fnr   r   Zfn_argsZd_argspyr   r1   rB  r2   monkeypatch_proxied_specials  sF    






rI  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    rJ  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 )r0  )r?  rA  r1   r1   r2   r    rk   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rS   rT   rU   rV   r1   r1   r1   r2   AnonymousInterface  s   rL  Z	Anonymousz%r: unknown in this interfacez%r=%r is not callablez,dictionary does not contain required keys %sN)r   r4   r5   rY   r7  operatorgegtintersectionr   rl   rS   dictlike_iteritemsr  rF  staticmethodr[   )r+   rX   r  requiredZ	interfaceZimplementedZcompliesZ	qualifierrL  foundr  r   r1   r1   r2   as_interface  sP    !



rU  _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]fgetrd   rV   r;   rS   NrX  docc                 C  s   || _ |p|j| _|j| _d S r-   rX  rV   rS   rI   rX  rZ  r1   r1   r2   r   D  s    zgeneric_fn_descriptor.__init__rV  rD   r   rI   r+   rX   r,   c                 C  s   d S r-   r1   rI   r+   rX   r1   r1   r2   __get__I  s    zgeneric_fn_descriptor.__get__r  r!   r+   rX   r,   c                 C  s   d S r-   r1   r^  r1   r1   r2   r_  L  s    zUnion[_GFD, _T_co]c                 C  s
   t  d S r-   NotImplementedErrorr^  r1   r1   r2   r_  O  s    instancerL   r,   c                 C  s   d S r-   r1   rI   rd  rL   r1   r1   r2   __set__T  rk   zgeneric_fn_descriptor.__set__rd  r,   c                 C  s   d S r-   r1   )rI   rd  r1   r1   r2   
__delete__V  rk   z generic_fn_descriptor.__delete__r*   c                 C  s
   t  d S r-   ra  rI   r+   r1   r1   r2   _resetX  s    zgeneric_fn_descriptor._reset)r+   ro   r,   c                 C  s
   t  d S r-   ra  rX   r+   ro   r1   r1   r2   reset[  s    zgeneric_fn_descriptor.reset)N)rS   rT   rU   rV   r3   r   r   r_  r   rf  rh  rj  classmethodrl  r1   r1   r1   r2   rW  5  s    

rW  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-   rX  r^  r1   r1   r2   r_  k  s    z_non_memoized_property.__get__N)rS   rT   rU   rV   r   r_  r1   r1   r1   r2   rn  `  s   rn  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-   )rX  r6   rS   rI   r+   rX   resultr1   r1   r2   r_  v  s    z_memoized_property.__get__c                 C  s   t || j d S r-   )rp  rl  rS   ri  r1   r1   r2   rj  |  s    z_memoized_property._resetc                 C  s   |j |d  d S r-   )r6   rZ   rk  r1   r1   r2   rl    s    z_memoized_property.resetN)	rS   rT   rU   rV   r   r_  rj  rm  rl  r1   r1   r1   r2   rp  q  s   rp  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   ar.  rr  r1   r2   memo  s    z6memoized_instancemethod.<locals>.oneshot.<locals>.memo)rS   rV   r6   rI   r   r.  rv  r   ru  r2   oneshot  s    z(memoized_instancemethod.<locals>.oneshotr   )r   ry  r1   rx  r2   memoized_instancemethod  s    	rz  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_keysrD   rE   c                 C  s   | j D ]}| j|d  qd S r-   )r|  r6   rZ   rI   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   )r9  rL   r,   c                 C  s   || j |< |  j|hO  _d S r-   )r6   r|  )rI   r9  rL   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]rX  rd   rV   r;   rS   NrY  c                 C  s   || _ |p|j| _|j| _d S r-   r[  r\  r1   r1   r2   r     s    z'HasMemoized.memoized_attribute.__init__r&   rD   r   r]  c                 C  s   d S r-   r1   r^  r1   r1   r2   r_    s    z&HasMemoized.memoized_attribute.__get__r    r`  c                 C  s   d S r-   r1   r^  r1   r1   r2   r_    s    c                 C  s8   |d u r| S |  | |j| j< }| j| jhO  _|S r-   )rX  r6   rS   r|  rq  r1   r1   r2   r_    s
    )N)rS   rT   rU   rV   r3   r   r   r_  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   )rI   r   r.  r,   c                   sT   | g|R i |  fdd}j |_ j|_|| jj < |  jj hO  _ S )Nc                    s    S r-   r1   rs  ru  r1   r2   rv    s    zBHasMemoized.memoized_instancemethod.<locals>.oneshot.<locals>.memo)rS   rV   r6   r|  rw  rx  ru  r2   ry    s    z4HasMemoized.memoized_instancemethod.<locals>.oneshotr   )rX   r   ry  r1   rx  r2   rz    s    z#HasMemoized.memoized_instancemethodN)rS   rT   rU   rV   r   rW   	frozensetr|  r3   r~  r  r  memoized_propertyr    r  rm  rz  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   )rI   r9  r1   r1   r2   _fallback_getattr  s    zMemoizedSlots._fallback_getattrr;   r   )r9  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   rs  ru  r1   r2   rv  )  s    z8MemoizedSlots.__getattr__.<locals>.oneshot.<locals>.memo)rS   rV   rF  )r   r.  rv  r   r9  rI   ru  r2   ry  &  s    z*MemoizedSlots.__getattr__.<locals>.oneshot)r?  r   r~   ru   r8   rF  rV   r  )rI   r9  rL   ry  r1   r  r2   __getattr__  s    
zMemoizedSlots.__getattr__N)rS   rT   rU   rV   rW   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offri   f0FzString is not true/false: %r)r4   r;   striprg   
ValueErrorrr   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])rL   r,   c                 C  s   | du r| S t | S )zCoerce to integer.N)r   )rL   r1   r1   r2   asintS  s    r  zOptional[Dict[str, Any]]rD   )r.  r9  rK   
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   rr   r  )r.  r9  rK   r  r  r1   r1   r2   coerce_kw_type[  s    
r  r`  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   rh   kr0   r1   r2   rj   {  s   z"constructor_key.<locals>.<genexpr>)r   r   )r+   rX   r   r1   r0   r2   constructor_keyu  s    r  )r+   rX   r   r.  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   rj     s   z#constructor_copy.<locals>.<genexpr>)r   r>   
difference)r+   rX   r   r.  r   r1   r0   r2   constructor_copy  s
    r  zCallable[[], int]rE   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[   rY   )r~   r  r3  rY   r4   r5   r   r   )r  r  Zisar1   r1   r2   duck_type_collection  s(    






r  z'Union[Tuple[Type[Any], ...], Type[Any]])r   argtypero   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   )rh   rt  r1   r1   r2   rj     rk   z"assert_arg_type.<locals>.<genexpr>z6Argument '%s' is expected to be of type '%s', got '%s')r4   r   r   ArgumentErrorrl   r5   )r   r  ro   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  )r9  dictlikegetterr1   r2   iterator  s    z$dictlike_iteritems.<locals>.iteratorr8  c                 3  s   | ]}| |fV  qd S r-   r1   )rh   r9  )r  r1   r2   rj     rk   z%dictlike_iteritems.<locals>.<genexpr>)r~   r   r$  r8   r   iterr8  )r  r  r1   r  r2   rQ    s    


rQ  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]rX  r   )rX  r   r.  c                   s&   t  j|g|R i | |j| _d S r-   )superr   rV   )rI   rX  r   r.  ru   r1   r2   r     s    zclassproperty.__init__NzOptional[type]r`  c                 C  s
   |  |S r-   ro  r^  r1   r1   r2   r_    s    zclassproperty.__get__)N)rS   rT   rU   rV   r3   r   r_  __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rI   r   r1   r1   r2   r     s    zhybridproperty.__init__r   r    rd  ownerr,   c                 C  s$   |d u r|  |}|S | |S d S r-   r  r   rI   rd  r  Zclsvalr1   r1   r2   r_    s    
zhybridproperty.__get__rq   zhybridproperty[_T]r   c                 C  s
   || _ | S r-   r  r  r1   r1   r2   
classlevel
  s    zhybridproperty.classlevelN)rS   rT   rU   r   r_  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   r_    s    
zrw_hybridproperty.__get__rD   rc  c                 C  s   | j d usJ |  || d S r-   r  re  r1   r1   r2   rf    s    zrw_hybridproperty.__set__rq   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)rS   rT   rU   r   r_  rf  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  r_  ru   r   )rI   rd  r  r1   r1   r2   r_  0  s    zhybridmethod.__get__rq   zhybridmethod[_T]r   c                 C  s
   || _ | S r-   r  r  r1   r1   r2   r  6  s    zhybridmethod.classlevelN)rS   rT   rU   rV   r   r_  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;   ro   zDict[str, symbol]symbolsNrd   r  )ro   rZ  	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  ro   rV   r   )rX   ro   rZ  r  r   r1   r1   r2   r  O  s$    zsymbol.__new__c                 C  s   t | jdt| ffS )Nr<   )r  ro   r   rH   r1   r1   r2   
__reduce__m  s    zsymbol.__reduce__c                 C  s   t | S r-   r  rH   r1   r1   r2   __str__p  s    zsymbol.__str__c                 C  s   d| j dS )Nzsymbol()ro   rH   r1   r1   r2   __repr__s  s    zsymbol.__repr__)NN)rS   rT   rU   rV   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   rD   )	classnamer   dict_r.  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  r0  z#Expected integer values for IntFlagc                 S  s   i | ]}|j |qS r1   r  )rh   r   r1   r1   r2   
<dictcomp>  rk   z)_IntFlagMeta.__init__.<locals>.<dictcomp>)Z_itemsr$  rm   matchr4   r   r  r?  r   rF  r   r   Zimmutabledict__members__)	rX   r  r   r  r.  r$  r  vr   r1   r1   r2   r   x  s    



z_IntFlagMeta.__init__zIterator[symbol]rE   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/99304ra  rH   r1   r1   r2   __iter__  s    z_IntFlagMeta.__iter__N)rS   rT   rU   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.

    NrK  r1   r1   r1   r2   r    s   r  )	metaclass)IntFlag_EzDict[_E, List[Any]]zOptional[_E])r   choicesro   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$  ro   r   r  )r   r  ro   r  Z
enum_valuechoicer1   r1   r2   parse_user_argument_for_enum  s    
r  rg  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)rd  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)rb   warnrF   rG   )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   )rL   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])rL   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  )rX   rL   r  r   ZinterpolatedrI   r  r1   r2   r    s    z_hash_limit_string.__new__rE   c                 C  s   | j S r-   )r  rH   r1   r1   r2   __hash__  s    z_hash_limit_string.__hash__r   rr   )otherr,   c                 C  s   t | t |kS r-   )r  )rI   r  r1   r1   r2   __eq__  s    z_hash_limit_string.__eq__)	rS   rT   rU   rV   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   rx  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   FrS   r   Tz (r  r   )r   )rF   	_getframer  rm   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   r.  r,   c                    sD    }r@  }z|| i |W S    r8d|  Y n0 d S )Nr   )rZ   insert)r   r.  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 = valuerY   )rE  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   rD   rE   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  rh   ro   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__)rX   	remainingr  r1   r2   r    s    
zTypingOnly.__init_subclass__)rS   rT   rU   rV   rW   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_kwargrD   rE   c                   sf   | j }| j}|rX|D ]B}t||}|r|| }t|}|js| |}t| || qt	 
  d S r-   )r  r6   rm   r  r   r   r   
_wrap_w_kwrF  r  r  )rX   Zfn_regZclsdictr9  r@   r   r   wrappedr  r1   r2   r    s    

zEnsureKWArg.__init_subclass__rq   r   c                   s    dddd fdd}t | S )Nr   r	  c                    s    |  S r-   r1   )r   r.  rx  r1   r2   wrap  s    z$EnsureKWArg._wrap_w_kw.<locals>.wrapr   )rX   r   r"  r1   rx  r2   r     s    zEnsureKWArg._wrap_w_kw)	rS   rT   rU   rV   r3   r  rm  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

    rS   rT   rV   N)r~   r   ru   rS   rT   r   rV   )wrapperr   Z_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   )rl   )rh   r   r1   r1   r2   r  1  rk   z'quoted_token_parser.<locals>.<listcomp>)r   r  r   )rL   r+  rr  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   )rh   paramr  r1   r2   r  :  rk   z8add_parameter_text.<locals>.decorate.<locals>.<dictcomp>)rV   inject_param_text)r   rZ  r*  r  r1   r2   r   7  s
    z$add_parameter_text.<locals>.decorate)r   r   )r*  r  r   r1   r-  r2   add_parameter_text4  s    
r.  c                 C  sN   |  dd}t|dkr| S |\}}|ds@|d t| S t| S d S )N
r   rf   )r   r  r?  textwrapdedent)r  Z
split_text	firstliner  r1   r1   r2   _dedent_docstringA  s    
r3  )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   r/  r   r   c                 S  s   g | ]\}}|  s|qS r1   )r  )rh   r  liner1   r1   r2   r  X  rk   z)inject_docstring_text.<locals>.<listcomp>)
r3  r   r  r   r0  r1  r
  r"  minrl   )r4  r5  r6  doctextlinesZinjectlinesZblanksZ
inject_posr1   r1   r2   inject_docstring_textM  s    

r;  z(\s+):param (.+?):zDict[str, str])r9  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   *rf   r   z(\s+)\Sr   r/  z::)collectionsdeque
splitlinespopleft
_param_regr  r   lstripr  rm   r\   rstripr@  r   rl   )
r9  r<  Zdoclinesr:  Z	to_injectr7  r@   r+  indentm2r1   r1   r2   r,  d  s6    

r,  )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    rk   z$repr_tuple_names.<locals>.<listcomp>r  z%s, ..., %s)r  rl   )r   flagresr1   r1   r2   repr_tuple_names  s    (
rJ  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    rL  c                   @  s   e Zd Ze ZdS )_MissingN)rS   rT   rU   enumautoMissingr1   r1   r1   r2   rM    s   rM  )N)FF)T)T)r1   r1   r1   r1   )r1   Nr1   )NNr;  N)NNN)TN)N)F)r  )N)Nr   )F)rV   
__future__r   r>  rN  	functoolsr   r.   r   rM  rm   rF   r0  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   Z_has_cyr   r   r   r    r!   r#   r%   r&   r'   r(   Zpy310r/   rA   rB   r`   rc   rp   rw   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r	  r  r  r  r&  r'  r6  r:  rI  rJ  rU  rV  rW  rn  rp  r  Znon_memoized_propertypropertyZro_memoized_propertyZro_non_memoized_propertyrz  r{  Z!HasMemoized_ro_memoized_attributer  r  r  r  r  r  r  r  r  r  r  rQ  r  r  r  r  r   r  r5   r  r  r  ZFastIntFlagEnumr  r  r  r  r  r  r;   r  r  r  r  r3   r  compiler  r  r  Z_SQLA_REZ_UNITTEST_REr  ZNoneTyper  r  r  r  r$  r)  r.  r3  r;  rB  r,  rJ  rL  rM  rP  Z	MissingOrr1   r1   r1   r2   <module>	   sl  ;	G(59u%     N&   
CV+M. #<"
"


  3 ),+