U
    dC                  	   @  st  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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&Z0e#d)d*d&Z1e#d+d,d&Z2e#d-d.d&Z3e(j4rd/d0d1d2d3Z5nd/d0d1d4d3Z5d/d5d6d7d8Z6G d9d: d:Z7d;d<d=d>d?Z8d/d5d@dAdBZ9dCd5d=dDdEZ:dFdGdHdIdJdKZ;dLdMdNdOdPZ<dQd5dRdSdTdUZ=dVdWdXdYdZd[Z>e#d\dGd&Z?dGd]d^d_d`Z@dadb ZAdcddd5dGdedfdgZBe#dhZCe#diZDG djdk dkZEdldm ZFedd%dndodpdqdrdsdtduZGeddvdndodpdHdpdsdwduZGddvdndodpdHdpdsdxduZGdGdydzd{d|ZHd2dGdHdHd}d~ddZId3ddHddddZJd4ddZKd5dCd5d5dQdQdQddddZLdd ZMdd ZNd6d/dddQd5dddZOG dd dZPdd ZQdd ZRd7ddZSdd ZTd8ddZUe#ddd&ZVG dd dee. ZWG dd deWe. ZXG dd deWe. ZYe"reWZZeWZ[e\Z]e\Z^neY ZZZ]eX Z[Z^d$d$dddZ_G dd dZ`e"re\Zane`jbZaG dd dZcd/dHd1ddZdd5ddddZed/ddddZfd9ddd5dCdHdddddZgd/dCdMdddÄZhd d;d/d/d dĜddƄZiddȜddʄZjd:d/ddd̜dd΄Zkd/dd5d/dМdd҄ZlddԄ ZmG ddք de\ZnG dd؄ dee- ZoG ddڄ dee- ZpG dd܄ dee- ZqG ddބ derZsG dd detZuG dd deudZve"rBddlmwZw ewZxnevZxe#dejyd&Zzd;d/dd5dHddddZ{da|d/ddddZ}dGd/d/d/dddZ~d<ddZG dd deZd=d5dddddZd5dddddZi Zded< d5d ddddZedZd>dddWddd	d
ZddHddddZedZedZeefdydddydddZetdZdd ZG dd dZG dd dZdd Zdd Zd/d5dd d!d"Zd5d5dd#d$Zdd5dWd5d%d&d'Zed(Zd5d)d5d*d+d,Zdydd-d.d/Zd?d0d1ZdS (@  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   ?/tmp/pip-unpacked-wheel-wbr0uges/sqlalchemy/util/langhelpers.pyr/   B   s    r/   c                 C  sB   t | tr| jdd }nt| dd }|d kr4tjS td|S d S )N__annotations__r)   )
isinstancetype__dict__getgetattrr   
EMPTY_DICTr   )r+   annr1   r1   r2   r/   G   s    
str)xr,   c                 C  s$   |  d} t }||  | S )Nzutf-8)encodehashlibmd5update	hexdigest)r<   mr1   r1   r2   md5_hexX   s    

rC   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_infozfUnion[None, Tuple[Type[BaseException], BaseException, types.TracebackType], Tuple[(None, None, None)]]rE   Noner,   c                 C  s   t  | _d S r-   )sysexc_inforE   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 k	st|d kr@| j \}}}|d k	s.td | _ ||nd | _ |d k	sRt||d S r-   )rE   AssertionErrorwith_traceback)rK   rM   rN   rO   exc_type	exc_valueexc_tbr1   r1   r2   __exit__   s    zsafe_reraise.__exit__N)__name__
__module____qualname____doc__	__slots__r3   rL   rU   r1   r1   r1   r2   rD   _   s
   

rD   zType[_T]zIterator[Type[_T]])clsr,   c                 c  sH   t  }| g}|rD| } | |kr$qn
||  ||   | V  qd S r-   )setpopaddextend__subclasses__)r[   seenstackr1   r1   r2   walk_subclasses   s    
rc   )elementr,   c                 C  s:   t | tr| S z
t| W S  tk
r4   d|   Y S X d S )Nzunprintable element %r)r4   r;   	Exception)rd   r1   r1   r2   string_or_unprintable   s    

rf   z	Type[Any]c                 C  s   d dd td| jD S )N c                 s  s   | ]}|  V  qd S r-   )lower).0nr1   r1   r2   	<genexpr>   s    z(clsname_as_plain_name.<locals>.<genexpr>z([A-Z][a-z]+|SQL))joinrefindallrV   r[   r1   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__rV   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 ] }||kr4|| |V   qq4td  qd S )Nc                   s    t |  S r-   r;   )ibaser1   r2   <lambda>       z!_unique_symbols.<locals>.<lambda>i  z&exhausted namespace for symbol base %s)r\   	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           	        s  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< dt|d krd| }nd| }|| || d| ji ttjt||| j	}t| d| j|_| |_ttt|| S )Nznot a decoratable functionzTuple[str, ...]r   r      r   r   )r   r   Fgroupedname__zKdef %(name)s%(grouped_args)s:
    return %(target)s(%(fn)s, %(apply_pos)s)
zJdef %(name)s%(grouped_args)s:
    return %(target)s(%(fn)s, %(apply_kw)s)
rV   __func__)r.   
isfunctionismethodre   r   inspect_getfullargspec!_update_argspec_defaults_into_envr   r   rV   r   dictr@   format_argspec_plusreprrW   typesFunctionType_exec_code_in_envr8   __defaults____wrapped__r   r   )	r   specenvnamesZ	targ_namefn_namemetadatacodeZ	decoratedr   r1   r2   decorate   s@    



	zdecorator.<locals>.decorater   )r   r   r1   r   r2   	decorator   s    7r   c                 C  s|   | j rtg }d}| j D ]@}t|jdk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   rW   r   listr   r   FullArgSpec)r   r   Znew_defaultsr   argr   elemr1   r1   r2   r   3  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   H  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   )rK   r   r   r1   r1   r2   __init__T  s    zPluginLoader.__init__c                 C  s   | j   d S r-   )r   clearrJ   r1   r1   r2   r   [  s    zPluginLoader.clearr   )r   r,   c                 C  s   || j k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   r   loadr   ZNoSuchModuleError)rK   r   loaderimplr1   r1   r2   r   ^  s    



zPluginLoader.loadrF   )r   
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   )modtokenr   r   r1   r2   r   r  s    z#PluginLoader.register.<locals>.load)r   )rK   r   r   r   r   r1   r   r2   registerq  s    zPluginLoader.register)N)rV   rW   rX   r   r   r   r   r1   r1   r1   r2   r   S  s
    r   c                 C  sn   z
t j}W n2 tk
r<   t| }|d t|d f Y S X | 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])r[   r   r   r,   c                C  s   d S r-   r1   r[   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k}|rt  }|dk	st| 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k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   rK   )r\   rP   r6   r7   r4   r   r   r   r   r   r@   	TypeError	__bases__r   discard)	r[   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     sX    






   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   m  r   z%format_argspec_plus.<locals>.<lambda>)formatvaluec                 S  s   dt |  S r   r   r   r1   r1   r2   r   v  r   )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     s    $
        

	



r   c                 C  s|   | t jkr(d}|rdnd}|r"dnd}n@zt| |dW S  tk
rf   d}|rR|nd}|r^dnd	}Y nX 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::

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

    z(self)rK   z() 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
attributesr,   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   ro   r1   r1   r2   r     s    z&create_proxy_methods.<locals>.decorater1   )r  r	  r
  r  r  r  r   r1   r1   r2   create_proxy_methods  s    r  c                 C  sT   zt | W S  tk
rN   | tjkr8dgdddf Y S dgdddf Y S Y nX dS )zinspect.getargspec with considerations for typical __init__ methods

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

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

    rK   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              	     sV  |dkrg}n
t |}t  g }t  }d}t|D ]\}}zt|j}	W n tk
rh   Y q8Y q8X |	j	rzt
|	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	st|dd t|	j|
 d |	j	D  q8g }|fdd|D  |dk	rlt|rl|d	d t|D  | D ]f\}}||krqtz6t| }| k	r||kr|d
||f  W n tk
r   Y nX qt|r@|D ]X\}}z6t| }| k	r"||kr"|d
||f  W n tk
r:   Y nX 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>  s     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     s     zgeneric_repr.<locals>.<genexpr>c                 S  s   g | ]}t |qS r1   r   )ri   valr1   r1   r2   r    s     z%s=%rz%s(%s), )r   to_listr  OrderedDict	enumerater   r   r   r   r   r  r   r_   r   r@   rP   zipr~   r8   itemsr   re   ru   rV   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  sl    



 


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   r   r  __weakref__c                 C  s   | j | j| jdS )Nr   r   r  r&  rJ   r1   r1   r2   __getstate__:  s    z$portable_instancemethod.__getstate__c                 C  s&   |d | _ |d | _|dd| _d S )Nr   r   r  r1   )r   r   r7   r  )rK   stater1   r1   r2   __setstate__A  s    

z$portable_instancemethod.__setstate__r1   c                 C  s   |j | _|j| _|| _d S r-   )r   r   rV   r   r  )rK   methr  r1   r1   r2   r   F  s    z portable_instancemethod.__init__c                 O  s    | | j t| j| j||S r-   )r@   r  r8   r   r   )rK   r   kwr1   r1   r2   r   K  s    z portable_instancemethod.__call__N)r1   )	rV   rW   rX   rY   rZ   r'  r)  r   r   r1   r1   r1   r2   r$  2  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   | ]}| kr|V  qd S r-   r1   ri   _Zhierr1   r2   rk   _  s      z"class_hierarchy.<locals>.<genexpr>r   r`   c                   s   g | ]}| kr|qS r1   r1   r,  r.  r1   r2   r  h  s   z#class_hierarchy.<locals>.<listcomp>)r   __mro__r]   r   r   r^   rW   r~   
issubclassr5   r`   )r[   processr   r   r   sr1   r.  r2   class_hierarchyP  s$    




	
r3  c                 c  s@   t | }|D ].}| jD ]"}||jk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)dirr/  r6   )r[   keyskeyr   r1   r1   r2   iterate_attributesv  s    

r7  
self.proxyc              	     s<  |r
|}n$dkrd fddt |D }|D ]}z4t||}t|dsRW q2t|d|}ttj|}	W n tk
r   Y q2Y nX z2t|	}
t	|
d }t	|
d dd }W n t
k
r   d	}d
}Y nX dt  }|dk	r||ipi }t|| z|	j|| _W n tk
r$   Y nX t |||  q2dS )z9Automates delegation of __specials__ for a proxying type.N)rZ   __del____getattribute____metaclass__r'  r)  c                   s6   g | ].}| d r|d rt |s|kr|qS )r   )
startswithendswithr~   ri   rB   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)r4  r8   r~   r   r   r   r   r   r   r  r   localsr   r   setattr)r@  Zfrom_clsrA  onlyr   Zfrom_instanceZdundersr  Zmaybe_fnr   r   Zfn_argsZd_argspyr   r1   r?  r2   monkeypatch_proxied_specials  sF    







rF  c                 C  s   t | d| t |d|kS )z;Return True if the two methods are the same implementation.r   )r8   )Zmeth1Zmeth2r1   r1   r2   methods_equivalent  s
      rG  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krdpd}t d| |d
|f G dd	 d	}|rd
|j |_t }	t| D ]R\}
}|
|k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 )r-  )r<  r>  r1   r1   r2   r    s     
 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rV   rW   rX   rY   r1   r1   r1   r2   AnonymousInterface  s   rI  Z	Anonymousz%r: unknown in this interfacez%r=%r is not callablez,dictionary does not contain required keys %sN)r   r4   r5   r\   r4  operatorgegtintersectionr   rl   rV   dictlike_iteritemsr   rC  staticmethodr^   )r+   r[   r  requiredZ	interfaceZimplementedZcompliesZ	qualifierrI  foundr  r   r1   r1   r2   as_interface  sP    !



rR  _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]fgetOptional[str]rY   r;   rV   NrU  docc                 C  s   || _ |p|j| _|j| _d S r-   rU  rY   rV   rK   rU  rX  r1   r1   r2   r   9  s    zgeneric_fn_descriptor.__init__rS  rF   r   rK   r+   r[   r,   c                 C  s   d S r-   r1   rK   r+   r[   r1   r1   r2   __get__>  s    zgeneric_fn_descriptor.__get__r  r!   r+   r[   r,   c                 C  s   d S r-   r1   r\  r1   r1   r2   r]  B  s    zUnion[_GFD, _T_co]c                 C  s
   t  d S r-   NotImplementedErrorr\  r1   r1   r2   r]  F  s    instancerN   r,   c                 C  s   d S r-   r1   rK   rb  rN   r1   r1   r2   __set__K  s    zgeneric_fn_descriptor.__set__rb  r,   c                 C  s   d S r-   r1   )rK   rb  r1   r1   r2   
__delete__N  s    z generic_fn_descriptor.__delete__r*   c                 C  s
   t  d S r-   r_  rK   r+   r1   r1   r2   _resetQ  s    zgeneric_fn_descriptor._reset)r+   r   r,   c                 C  s
   t  d S r-   r_  r[   r+   r   r1   r1   r2   resetT  s    zgeneric_fn_descriptor.reset)N)rV   rW   rX   rY   r3   r   r   r]  r   rd  rf  rh  classmethodrj  r1   r1   r1   r2   rT  *  s    

rT  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 kr| S |  |S r-   rU  r\  r1   r1   r2   r]  d  s    z_non_memoized_property.__get__N)rV   rW   rX   rY   r   r]  r1   r1   r1   r2   rl  Y  s   rl  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 kr| S |  | |j| j< }|S r-   )rU  r6   rV   rK   r+   r[   resultr1   r1   r2   r]  o  s    z_memoized_property.__get__c                 C  s   t || j d S r-   )rn  rj  rV   rg  r1   r1   r2   rh  u  s    z_memoized_property._resetc                 C  s   |j |d  d S r-   )r6   r]   ri  r1   r1   r2   rj  x  s    z_memoized_property.resetN)	rV   rW   rX   rY   r   r]  rh  rk  rj  r1   r1   r1   r2   rn  j  s   rn  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                   s<   | f||  fdd}j |_ j|_|| jj <  S )Nc                    s    S r-   r1   ar+  rp  r1   r2   memo  s    z6memoized_instancemethod.<locals>.oneshot.<locals>.memo)rV   rY   r6   rK   r   r+  rt  r   rs  r2   oneshot  s    z(memoized_instancemethod.<locals>.oneshotr   )r   rw  r1   rv  r2   memoized_instancemethod  s    	rx  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_keysrF   rG   c                 C  s   | j D ]}| j|d  qd S r-   )rz  r6   r]   rK   r   r1   r1   r2   _reset_memoizations  s    
zHasMemoized._reset_memoizationsc                 C  s   | j D ]}|| jkstqd S r-   )rz  r6   rP   r{  r1   r1   r2   _assert_no_memoizations  s    
z#HasMemoized._assert_no_memoizationsr;   r   )r6  rN   r,   c                 C  s   || j |< |  j|hO  _d S r-   )r6   rz  )rK   r6  rN   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]rU  rV  rY   r;   rV   NrW  c                 C  s   || _ |p|j| _|j| _d S r-   rY  rZ  r1   r1   r2   r     s    z'HasMemoized.memoized_attribute.__init__r&   rF   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 kr| S |  | |j| j< }| j| jhO  _|S r-   )rU  r6   rV   rz  ro  r1   r1   r2   r]    s
    )N)rV   rW   rX   rY   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   )rK   r   r+  r,   c                   sN   | f||  fdd}j |_ j|_|| jj < |  jj hO  _ S )Nc                    s    S r-   r1   rq  rs  r1   r2   rt    s    zBHasMemoized.memoized_instancemethod.<locals>.oneshot.<locals>.memo)rV   rY   r6   rz  ru  rv  rs  r2   rw    s    z4HasMemoized.memoized_instancemethod.<locals>.oneshotr   )r[   r   rw  r1   rv  r2   rx    s    z#HasMemoized.memoized_instancemethodN)rV   rW   rX   rY   r   rZ   	frozensetrz  r3   r|  r}  r~  memoized_propertyr    r  rk  rx  r1   r1   r1   r2   ry    s   
 ry  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   )rK   r6  r1   r1   r2   _fallback_getattr  s    zMemoizedSlots._fallback_getattrr;   r   )r6  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                    s6   | |  fdd}j |_ j|_t|  S )Nc                    s    S r-   r1   rq  rs  r1   r2   rt  &  s    z8MemoizedSlots.__getattr__.<locals>.oneshot.<locals>.memo)rV   rY   rC  )r   r+  rt  r   r6  rK   rs  r2   rw  #  s    
z*MemoizedSlots.__getattr__.<locals>.oneshot)r<  r   r~   ru   r8   rC  rY   r  )rK   r6  rN   rw  r1   r  r2   __getattr__  s    
zMemoizedSlots.__getattr__N)rV   rW   rX   rY   rZ   r  r  r1   r1   r1   r2   r    s   r  c                 C  sB   t | tr:|   } | dkr"dS | dk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   
ValueErrorrr   r0   r1   r1   r2   asbool5  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   |  kr| S t | S d S r-   )r  r0   r  r1   r2   bool_or_valueG  s    z"bool_or_str.<locals>.bool_or_valuer1   )r  r  r1   r  r2   bool_or_strA  s    r  Optional[int])rN   r,   c                 C  s   | dkr| S t | S )zCoerce to integer.N)r   )rN   r1   r1   r2   asintP  s    r  zOptional[Dict[str, Any]]rF   )r+  r6  rM   
flexi_booldestr,   c                 C  sj   |dkr| }|| krft |tr,t | | |sf| | dk	rf|tk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+  r6  rM   r  r  r1   r1   r2   coerce_kw_typeX  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 kr| j | fV  qd S r-   r6   ri   kr0   r1   r2   rk   x  s    
 z"constructor_key.<locals>.<genexpr>)r   r   )r+   r[   r   r1   r0   r2   constructor_keyr  s    r  )r+   r[   r   r+  r,   c                   s0   t |}| fdd||D  |||S )zInstantiate cls using the __dict__ of obj as constructor arguments.

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

    c                 3  s&   | ]}| j kr| j | fV  qd S r-   r  r  r0   r1   r2   rk     s    
 z#constructor_copy.<locals>.<genexpr>)r   r@   
difference)r+   r[   r   r+  r   r1   r0   r2   constructor_copy}  s
    r  zCallable[[], int]rG   c                    s$   t  td  fdd} | S )z%Return a threadsafe counter function.r   c                
     s$    t  W  5 Q R  S Q R X 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k	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^   r\   )r~   r  r0  r\   r4   r5   r   r   )r  r  Zisar1   r1   r2   duck_type_collection  s*    
 





r  z'Union[Tuple[Type[Any], ...], Type[Any]])r   argtyper   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   rr  r1   r1   r2   rk     s     z"assert_arg_type.<locals>.<genexpr>z6Argument '%s' is expected to be of type '%s', got '%s')r4   r   r   ArgumentErrorrl   r5   )r   r  r   r1   r1   r2   assert_arg_type  s    

r  c                   s   t  drt  S t dt dddk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 k	st| | fV  qd S r-   )r  rP   )r6  dictlikegetterr1   r2   iterator  s    z$dictlike_iteritems.<locals>.iteratorr5  c                 3  s   | ]}| |fV  qd S r-   r1   )ri   r6  )r  r1   r2   rk     s     z%dictlike_iteritems.<locals>.<genexpr>)r~   r   r!  r8   r   iterr5  )r  r  r1   r  r2   rN    s    


rN  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]rU  r   )rU  r   r+  c                   s    t  j|f|| |j| _d S r-   )superr   rY   )rK   rU  r   r+  ru   r1   r2   r     s    zclassproperty.__init__NzOptional[type]r^  c                 C  s
   |  |S r-   rm  r\  r1   r1   r2   r]    s    zclassproperty.__get__)N)rV   rW   rX   rY   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rK   r   r1   r1   r2   r     s    zhybridproperty.__init__r   r    rb  ownerr,   c                 C  s$   |d kr|  |}|S | |S d S r-   r  r   rK   rb  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)rV   rW   rX   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 kr|  |}|S | |S d S r-   r  r  r1   r1   r2   r]    s    
zrw_hybridproperty.__get__rF   ra  c                 C  s   | j d k	st|  || d S r-   )r  rP   rc  r1   r1   r2   rd    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)rV   rW   rX   r   r]  rd  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 kr| j ||jS | j||S d S r-   )r  r]  ru   r   )rK   rb  r  r1   r1   r2   r]  -  s    zhybridmethod.__get__rq   zhybridmethod[_T]r   c                 C  s
   || _ | S r-   r  r  r1   r1   r2   r  3  s    zhybridmethod.classlevelN)rV   rW   rX   rY   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;   r   zDict[str, symbol]symbolsNrV  r  )r   rX  	canonicalr,   c              
   C  s   | j  | j|}|d krbt|ts*t|d kr:t|}tt	|}||_
|rV||_|| j|< n |r||krtd| d| |W  5 Q R  S Q R X d S )Nz#Can't replace canonical symbol for z with new int value )_lockr  r7   r4   r;   rP   hashr   __new__r  r   rY   r   )r[   r   rX  r  r   r1   r1   r2   r  L  s     zsymbol.__new__c                 C  s   t | jdt| ffS )Nr<   )r  r   r   rJ   r1   r1   r2   
__reduce__j  s    zsymbol.__reduce__c                 C  s   t | S r-   r  rJ   r1   r1   r2   __str__m  s    zsymbol.__str__c                 C  s   d| j dS )Nzsymbol()r   rJ   r1   r1   r2   __repr__p  s    zsymbol.__repr__)NN)rV   rW   rX   rY   r3   r  r  r  r  r  r  r  r  r1   r1   r1   r2   r  8  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   rF   )	classnamer   dict_r+  r,   c           	      K  sz   g  | _ }| D ]L\}}t|tr2t||d}n|dstdnqt| || || qt	
dd |D | _d S )N)r  r-  z#Expected integer values for IntFlagc                 S  s   i | ]}|j |qS r1   r  )ri   r   r1   r1   r2   
<dictcomp>  s      z)_IntFlagMeta.__init__.<locals>.<dictcomp>)Z_itemsr!  r4   r   r  r<  r   rC  r   r   Zimmutabledict__members__)	r[   r  r   r  r+  r!  r  vr   r1   r1   r2   r   u  s    



z_IntFlagMeta.__init__zIterator[symbol]rG   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/99304r_  rJ   r1   r1   r2   __iter__  s    z_IntFlagMeta.__iter__N)rV   rW   rX   r   r  r1   r1   r1   r2   r  t  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.

    NrH  r1   r1   r1   r2   r    s   r  )	metaclass)IntFlag_EzDict[_E, List[Any]]zOptional[_E])r   choicesr   resolve_symbol_namesr,   c                 C  sn   |  D ]>\}}| |kr |  S |r6| |jkr6|  S | |kr|  S q| dk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!  r   r   r  )r   r  r   r  Z
enum_valuechoicer1   r1   r2   parse_user_argument_for_enum  s    
r  re  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)rb  r1   r1   r2   set_creation_order  s    	r  )r   r   r  r,   c                 O  s>   z| ||W S  t k
r8   tdt dd   Y nX dS )zXexecutes the given function, catches all exceptions and converts to
    a warning.

    z%s('%s') ignoredr   r   N)re   warnrH   rI   )r   r   r  r1   r1   r2   warn_exception  s    r     c                 C  sF   z(t | |kr d| d|  W S | W S W n tk
r@   |  Y S X d S )Nz%s...r   )r  r   )rN   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])rN   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  )r[   rN   r  r   ZinterpolatedrK   r  r1   r2   r    s    z_hash_limit_string.__new__rG   c                 C  s   | j S r-   )r  rJ   r1   r1   r2   __hash__  s    z_hash_limit_string.__hash__r   rr   )otherr,   c                 C  s   t | t |kS r-   )r  )rK   r  r1   r1   r2   __eq__
  s    z_hash_limit_string.__eq__)	rV   rW   rX   rY   r3   r  r  r  r  r1   r1   r  r2   r    s
   


r  rV  )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   rv  r  r  r1   r2   go+  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k
r&   d}Y n   d}Y nX d }}|d k	r|sdtt|jddsdd}|jt	krd}t	|j \}}|p|}|  d| d} |j
}|s|d7 }q>|r>|r>qq>|d k	rtj| ||d d	 ntj| |d d	 d S )
Nr   FrV   r  Tz (r  r   )r  )rH   	_getframer  rm   match_not_sa_pattern	f_globalsr7   f_coder  f_backwarningsr  )r  r  r  frameZstacklevel_foundZwarning_tag_found_suffixZ	_categoryr1   r1   r2   r  5  s4    
 

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                    s@    }r<  }z|| |W S    r4d|  Y nX d S )Nr   )r]   insert)r   r+  Z	strong_fnZonce_fnr   oncer  r1   r2   r  q  s    zonly_once.<locals>.gor1   )r   r  r  r1   r	  r2   	only_oncei  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 = valuer\   )rB  copyr   )attrnamer   r   r1   r1   r2   
attrsetter  s    

r  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   rF   rG   c                   sL   t | jkr>t| jdddddh}|r>td|  d| dt   d S )	NrW   rY   rZ   __orig_bases__r3   zClass z< directly inherits TypingOnly but has additional attributes r   )r  r   r\   r6   r  rP   r  __init_subclass__)r[   	remainingr  r1   r2   r    s    

	zTypingOnly.__init_subclass__)rV   rW   rX   rY   rZ   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_kwargrF   rG   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_kwrC  r  r  )r[   Zfn_regZclsdictr6  rB   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+  rv  r1   r2   wrap  s    z$EnsureKWArg._wrap_w_kw.<locals>.wrapr   )r[   r   r  r1   rv  r2   r    s    zEnsureKWArg._wrap_w_kw)	rV   rW   rX   rY   r3   r  rk  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

    rV   rW   rY   N)r~   r   ru   rV   rW   r   rY   )wrapperr   _fr1   r1   r2   wrap_callable  s    



r   c                 C  s   d| k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   )ri   r   r1   r1   r2   r  0  s     z'quoted_token_parser.<locals>.<listcomp>)r   r  r   )rN   r(  rp  idxlvcharr1   r1   r2   quoted_token_parser  s$    
$


r%  )paramsr  r,   c                   s   t    fdd}|S )Nc                   s:   | j d k	r| j pd}|r0t|fdd D }|| _ | S )Nr  c                   s   i | ]
}| qS r1   r1   )ri   paramr  r1   r2   r  9  s      z8add_parameter_text.<locals>.decorate.<locals>.<dictcomp>)rY   inject_param_text)r   rX  r&  r  r1   r2   r   6  s
    z$add_parameter_text.<locals>.decorate)r   r  )r&  r  r   r1   r)  r2   add_parameter_text3  s    
r*  c                 C  sN   |  dd}t|dkr| S |\}}|ds@|d t| S t| S d S )N
r   rg   )r   r  r<  textwrapdedent)r  Z
split_text	firstliner  r1   r1   r2   _dedent_docstring@  s    
r/  )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  )ri   r  liner1   r1   r2   r  W  s      z)inject_docstring_text.<locals>.<listcomp>)
r/  r   r  r   r,  r-  r  r  minrl   )r0  r1  r2  doctextlinesZinjectlinesZblanksZ
inject_posr1   r1   r2   inject_docstring_textL  s    

r7  z(\s+):param (.+?):zDict[str, str])r5  inject_paramsr,   c           
      C  s  t |  }g }d }|r| }t|}|d kr|r|dd}||k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   r+  z::)collectionsdeque
splitlinespopleft
_param_regr  r   lstripr  rm   r_   rstripr=  r   rl   )
r5  r8  Zdoclinesr6  Z	to_injectr3  rB   r'  indentm2r1   r1   r2   r(  c  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  )ri   r   r1   r1   r2   r    s     z$repr_tuple_names.<locals>.<listcomp>r  z%s, ..., %s)r  rl   )r   flagresr1   r1   r2   repr_tuple_names  s    (
rF  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    rH  )FF)T)T)r1   r1   r1   )r1   Nr1   )NNr8  N)NNN)TN)N)F)r  )N)Nr   )F)rY   
__future__r   r:  enum	functoolsr   r>   r.   r   rJ  rm   rH   r,  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/   rC   rD   rc   rf   rp   rw   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r  r  r#  r$  r3  r7  rF  rG  rR  rS  rT  rl  rn  r  Znon_memoized_propertypropertyZro_memoized_propertyZro_non_memoized_propertyrx  ry  Z!HasMemoized_ro_memoized_attributer  r  r  r  r  r  r  r  r  r  r  rN  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/  r7  r>  r(  rF  rH  r1   r1   r1   r2   <module>	   sh  ;
	=(	  5  ;u#    N&   
CV/P. #< 
"


  4 ),+