U
    h                 
   @  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rZdd/l4m5Z5 dd0l4m6Z6 d1d2 Z7e8j9d3 j:Z;d4d5 Z<d6d7d8d9d:d;Z=d6d8d<d=d>Z>n*e'j?rtd6d8d<d?d>Z>nd6d8d<d@d>Z>d6dAdBdCdDZ@G dEdF dFZAdGdHdIdJdKZBd6dAdLdMdNZCd@dOdPdAdQdRdSZDdTdUdVdWdXdYZEdZd[d\d]d^ZFd_dAd`dadbdcZGdddedfdgdhdiZHe"djdUd&ZIdUdkdldmdnZJdodpdAdUdqdrdsZKe"dtZLe"duZMG dvdw dwZNdxdy ZOedd%dzd{d|d}d~dddZPedddzd{d|dVd|dddZPdddzd{d|dVd|dddZPdUddddZQdAdUdVdVddddZRdBddVddddZSdCddZTdDdOdAdAd_d_d_d_ddddZUdd ZVdd ZWdEd6ddd_dAdddZXG dd dZYdd ZZdd Z[dFddZ\dd Z]dGddZ^e"ddd&Z_G dd dee- Z`G dd de`e- ZaG dd de`e- Zbe!re`Zce`ZdeeZfeeZgneb ZcZfea ZdZgd$d$dddZhG dd dZie!r<eeZjneijkZjG dd dZld6dVd<ddZmdAddddÄZnd6ddŜddǄZodHdpdAdOdVdddʜdd̄Zpd6dOd[d͜ddτZqd dGd6d6d dМdd҄ZrddԜddքZsdId6ddd؜ddڄZtd6ddAd6dܜddބZudd ZvG dd deeZwG dd dee, ZxG dd dee, ZyG dd dee, ZzG dd de{Z|G dd de8Z}G dd de}dZ~e!rddlmZ eZne~Ze"dejd&ZdJd6ddAdVddddZdad6ddddZdUd6d6d6dddZdKddZG d d deZdLdAdPdɐdddZdAddɐdddZi Zd	ed
< dAdddddZe
dZdMdddedɐdddZddVddddZe
dZe
dZeefddddddd Ze8dZd!d" Ze
d#ZG d$d% d%ZG d&d' d'Zd(d) Zd*d+ Zd6dAdd,d-d.ZdAdAdd/d0ZdPdAdedAd1d2d3Ze
d4ZdAd5dAd6d7d8ZddPd9d:d;ZdNd<d=ZG d>d? d?ejZejZe#e,e*ej f ZdS (O  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])call_annotate_function)Formatc                 C  sB   t | dd }|d k	r>t||| d}t|ts:t| d|S d S )N__annotate__)ownerz!.__annotate__ returned a non-dict)getattrr)   
isinstancedict
ValueError)objformatZannotateann r4   ?/tmp/pip-unpacked-wheel-y9ln43lq/sqlalchemy/util/langhelpers.py_get_and_call_annotateF   s    
r6   __annotations__c                 C  sj   t | tr2zt| }W qJ tk
r.   i  Y S X nt| dd }|d krJi S t |tsbt| dt|S )Nr7   z+.__annotations__ is neither a dict nor None)r.   type_BASE_GET_ANNOTATIONSAttributeErrorr-   r/   r0   r1   r3   r4   r4   r5   _get_dunder_annotationsR   s    

r<   r   r*   Mapping[str, Any])r1   r2   returnc                C  s   zt | }W n tk
r    Y nX |dk	r2t|S t| |}|dkrLt | }|dkrxt| tsft| rji S t| d|si S t|S )z:A sparse implementation of annotationlib.get_annotations()Nz does not have annotations)r<   	Exceptionr/   r6   r.   r8   callable	TypeError)r1   r2   r3   r4   r4   r5   _vendored_get_annotationsd   s     
rB   r1   r>   c                 C  s   t | tjdS )N)r2   )rB   r*   Z
FORWARDREFr1   r4   r4   r5   get_annotations   s    rE   c                 C  s
   t | S N)inspectrE   rD   r4   r4   r5   rE      s    c                 C  sB   t | tr| jdd }nt| dd }|d kr4tjS td|S d S )Nr7   r=   )r.   r8   __dict__getr-   r   
EMPTY_DICTr   r;   r4   r4   r5   rE      s    
str)xr>   c                 C  s*   |  d} t }||  tt| S )Nzutf-8)encoder   Zmd5_not_for_securityupdater   rK   	hexdigest)rL   mr4   r4   r5   md5_hex   s    

rQ   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)]]rS   Noner>   c                 C  s   t  | _d S rF   )sysexc_inforS   selfr4   r4   r5   	__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 rF   )rS   AssertionErrorwith_traceback)rY   r[   r\   r]   exc_type	exc_valueexc_tbr4   r4   r5   __exit__   s    zsafe_reraise.__exit__N)__name__
__module____qualname____doc__	__slots__r7   rZ   rc   r4   r4   r4   r5   rR      s
   

rR   zType[_T]zIterator[Type[_T]])clsr>   c                 c  sH   t  }| g}|rD| } | |kr$qn
||  ||   | V  qd S rF   )setpopaddextend__subclasses__)ri   seenstackr4   r4   r5   walk_subclasses   s    
rq   )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)r.   rK   r?   )rr   r4   r4   r5   string_or_unprintable   s    

rs   z	Type[Any]Optional[str])ri   use_namer>   c                 C  s&   |p| j }ddd td|D S )N c                 s  s   | ]}|  V  qd S rF   )lower).0nr4   r4   r5   	<genexpr>  s     z(clsname_as_plain_name.<locals>.<genexpr>z([A-Z][a-z]+|SQL))rd   joinrefindall)ri   ru   namer4   r4   r5   clsname_as_plain_name   s    
r   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.)r.   r8   	__class__rd   r-   )r   r   Zcurrent_clsmethod_nameZcurrent_methodr4   r4   r5   method_is_overridden  s    

r   slicezTuple[Any, ...])slcr>   c                 C  s>   g }| j | j| jfD ] }t|dr*| }|| qt|S )zrdecode a slice object as sent to __getitem__.

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

    	__index__)startstopstephasattrr   appendtuple)r   retrL   r4   r4   r5   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 rF   rK   )ibaser4   r5   <lambda>+      z!_unique_symbols.<locals>.<lambda>i  z&exhausted namespace for symbol base %s)rj   	itertoolschainmaprangerl   	NameError)r   r   Zused_setpoolsymr4   r   r5   _unique_symbols&  s    
r   zCallable[[int], Any]intzIterator[Any])fnry   r>   c                 c  s*   |r&|| d @ }| |V  ||N }q dS )z6Call the given function given each nonzero bit from n.r   Nr4   )r   ry   br4   r4   r5   map_bits6  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| dd }|d k	rPd | _zt| }W 5 || _X n
t| }dt|j	pfd }t
|jpxd}|ji ||d}ttd|d td|dd	  | jf }t|d
d\}}t
||d}|t|dd | j|d< t | rd|d< d|d< nd|d< d|d< dt|d kr:d| }	nd| }	| || d| ji}
ttjt|	|
| j}| j|_| j|_t|| S )Nznot a decoratable functionr+   rF   r4   )r   defaultskwonlydefaultszTuple[str, ...]r   r      r   r   )r   r   Fgroupedr~   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)
rd   )rG   
isfunctionismethodr?   r-   r+   r   inspect_getfullargspeclenr   r/   fromkeysr   _replacer   r   rd   r   rN   format_argspec_plusiscoroutinefunctionreprre   typesFunctionType_exec_code_in_env__defaults____kwdefaults__r   )r   ZannofuncspecZempty_defaultsZempty_kwdefaultsnamesZ	targ_namefn_namemetadatacodeenvZ	decoratedr   r4   r5   decorateG  sl    




		   zdecorator.<locals>.decorater   )r   r   r4   r   r5   	decoratorD  s    Vr   zUnion[str, types.CodeType]Dict[str, Any])r   r   r   r>   c                 C  s   t | | || S rF   )exec)r   r   r   r4   r4   r5   r     s    
r   _PF_TEc                   @  sZ   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dd
ddZdS )PluginLoaderNrK   zOptional[Callable[..., Any]])groupauto_fnc                 C  s   || _ i | _|| _d S rF   )r   implsr   )rY   r   r   r4   r4   r5   __init__  s    zPluginLoader.__init__c                 C  s   | j   d S rF   )r   clearrX   r4   r4   r5   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)rY   r~   loaderimplr4   r4   r5   r     s    



zPluginLoader.loadrT   )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__splitr-   )modtokenr   r   r4   r5   r     s    z#PluginLoader.register.<locals>.loadr   )rY   r~   r   r   r   r4   r   r5   register  s    zPluginLoader.registerc                 C  s   | j |= d S rF   r   )rY   r~   r4   r4   r5   
deregister  s    zPluginLoader.deregister)N)rd   re   rf   r   r   r   r   r   r4   r4   r4   r5   r     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   )rG   CO_VARKEYWORDSr:   r   r   r   __code__co_argcountlistco_varnamesco_flags)r   Zco_varkeywordsr   conargsr4   r4   r5   _inspect_func_args  s    

r   )_setraiseerrr8   zOptional[Set[str]]zLiteral[True]zSet[str])ri   r   r   r>   c                C  s   d S rF   r4   ri   r   r   r4   r4   r5   get_cls_kwargs  s    r   Fc                C  s   d S rF   r4   r   r4   r4   r5   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   rY   )rj   r^   rH   rI   r.   r   r   r   r   r   rN   rA   	__bases__r   discard)	ri   r   r   toplevelZctrZhas_initr   Zhas_kwcr4   r4   r5   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   r4   r4   r5   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   __func____call__)r   zCan't inspect callable: %s)rG   	isbuiltinrA   r   r   r   FullArgSpecargsvarargsvarkwr   
kwonlyargsr   r   r   __self__r   isclassget_callable_argspecr   r   r   )r   r   r   r   r4   r4   r5   r  9  sR    






  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   r4   c                 S  s   dt |  S N=r   rL   r4   r4   r5   r     r   z%format_argspec_plus.<locals>.<lambda>)formatvaluec                 S  s   dt |  S r  r   r  r4   r4   r5   r     r   )grouped_argsself_arg	apply_posapply_kwapply_pos_proxiedapply_kw_proxied)	r@   r   r   inspect_formatargspecr   r   r   r   r/   )r   r   r   r   r	  r  r  num_defaultsZ	name_argsZdefaulted_valsr
  r  r4   r4   r5   r   q  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:

    .. sourcecode:: text

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

    z(self)rY   z()r   r   z(self, *args, **kwargs)zself, *args, **kwargsz(*args, **kwargs)z*args, **kwargs)r  r  r	  r
  r  r  )objectr   r   rA   r/   )methodr   r  r   Zproxiedr4   r4   r5   format_argspec_init  s$    
r  r4   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 rF   r4   )ri   r4   r4   r5   r     s    z&create_proxy_methods.<locals>.decorater4   )r  r  r  r  r  r  r  r   r4   r4   r5   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 )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)

    rY   Nr   kwargs)r   r   rA   r  r   )r  r4   r4   r5   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)r.   r   
MethodTyper   r   )Zfunc_or_clsr4   r4   r5   unbound_method_to_callable4  s    r  zSequence[Tuple[str, Any]]z%Optional[Union[object, List[object]]])r1   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 r4   r4   rx   arg)missingr4   r5   
<listcomp>d  s     z generic_repr.<locals>.<listcomp>c                 S  s   g | ]\}}||fqS r4   r4   )rx   r#  defaultr4   r4   r5   r%  j  s   c                 3  s   | ]}t t |d V  qd S rF   )r   r-   r"  rD   r4   r5   rz   s  s     zgeneric_repr.<locals>.<genexpr>c                 S  s   g | ]}t |qS r4   r   )rx   valr4   r4   r5   r%  v  s     z%s=%rz%s(%s), )r   to_listr  OrderedDict	enumerater   r   r   rA   r   r   r   rm   r   rN   r^   zipr   r-   itemsr   r?   r   rd   r{   )r1   r  r   r!  Zpos_argsZkw_argsZvargsr   Zinspr   Zdefault_lenoutputr#  Zdefvalr(  r4   )r$  r1   r5   generic_repr@  sl    



 


r0  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  r3  rX   r4   r4   r5   __getstate__  s    z$portable_instancemethod.__getstate__c                 C  s&   |d | _ |d | _|dd| _d S )Nr   r~   r  r4   )r   r~   rI   r  )rY   stater4   r4   r5   __setstate__  s    

z$portable_instancemethod.__setstate__r4   c                 C  s   |j | _|j| _|| _d S rF   )r   r   rd   r~   r  )rY   methr  r4   r4   r5   r     s    z portable_instancemethod.__init__c                 O  s    | | j t| j| j||S rF   )rN   r  r-   r   r~   )rY   r#  kwr4   r4   r5   r     s    z portable_instancemethod.__call__N)r4   )	rd   re   rf   rg   rh   r4  r6  r   r   r4   r4   r4   r5   r1    s   
r1  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 rF   r4   rx   _Zhierr4   r5   rz     s      z"class_hierarchy.<locals>.<genexpr>builtinsrn   c                   s   g | ]}| kr|qS r4   r4   r9  r;  r4   r5   r%    s   z#class_hierarchy.<locals>.<listcomp>)r   __mro__rk   r   r   rl   re   r   
issubclassr8   rn   )ri   processr   r   r   sr4   r;  r5   class_hierarchy  s$    




	
rA  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=  rH   )ri   keyskeyr   r4   r4   r5   iterate_attributes  s    

rE  
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)rh   __del____getattribute____metaclass__r4  r6  c                   s6   g | ].}| d r|d rt |s|kr|qS )r   )
startswithendswithr   rx   rP   into_clsskipr4   r5   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)rB  r-   r   r   r   r   r:   r   r   r  rA   localsr   r   setattr)rN  Zfrom_clsrO  onlyr~   Zfrom_instanceZdundersr  Zmaybe_fnr   r   Zfn_argsZd_argspyr   r4   rM  r5   monkeypatch_proxied_specials  sF    







rT  c                 C  s   t | d| t |d|kS )z;Return True if the two methods are the same implementation.r   )r-   )Zmeth1Zmeth2r4   r4   r5   methods_equivalent%  s
      rU  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:  )rJ  rL  r4   r4   r5   r%  T  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rd   re   rf   rg   r4   r4   r4   r5   AnonymousInterfacek  s   rW  Z	Anonymousz%r: unknown in this interfacez%r=%r is not callablez,dictionary does not contain required keys %sN)rA   r.   r8   rj   rB  operatorgegtintersectionr/   r{   rd   dictlike_iteritemsr@   rQ  staticmethodrl   )r1   ri   r  requiredZ	interfaceZimplementedZcompliesZ	qualifierrW  foundr  r   r4   r4   r5   as_interface-  sP    !



r`  _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]fgetrt   rg   rK   rd   Nrc  docc                 C  s   || _ |p|j| _|j| _d S rF   rc  rg   rd   rY   rc  re  r4   r4   r5   r     s    zgeneric_fn_descriptor.__init__ra  rT   r   rY   r1   ri   r>   c                 C  s   d S rF   r4   rY   r1   ri   r4   r4   r5   __get__  s    zgeneric_fn_descriptor.__get__r  r!   r1   ri   r>   c                 C  s   d S rF   r4   ri  r4   r4   r5   rj    s    zUnion[_GFD, _T_co]c                 C  s
   t  d S rF   NotImplementedErrorri  r4   r4   r5   rj    s    instancer\   r>   c                 C  s   d S rF   r4   rY   ro  r\   r4   r4   r5   __set__  r   zgeneric_fn_descriptor.__set__ro  r>   c                 C  s   d S rF   r4   )rY   ro  r4   r4   r5   
__delete__  r   z generic_fn_descriptor.__delete__rC   c                 C  s
   t  d S rF   rl  rY   r1   r4   r4   r5   _reset  s    zgeneric_fn_descriptor._reset)r1   r~   r>   c                 C  s
   t  d S rF   rl  ri   r1   r~   r4   r4   r5   reset  s    zgeneric_fn_descriptor.reset)N)rd   re   rf   rg   r7   r   r   rj  r   rq  rs  ru  classmethodrw  r4   r4   r4   r5   rb    s    

rb  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 rF   rc  ri  r4   r4   r5   rj    s    z_non_memoized_property.__get__N)rd   re   rf   rg   r   rj  r4   r4   r4   r5   ry    s   ry  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 rF   )rc  rH   rd   rY   r1   ri   resultr4   r4   r5   rj    s    z_memoized_property.__get__c                 C  s   t || j d S rF   )r{  rw  rd   rt  r4   r4   r5   ru    s    z_memoized_property._resetc                 C  s   |j |d  d S rF   )rH   rk   rv  r4   r4   r5   rw    s    z_memoized_property.resetN)	rd   re   rf   rg   r   rj  ru  rx  rw  r4   r4   r4   r5   r{    s   r{  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 rF   r4   ar8  r}  r4   r5   memo  s    z6memoized_instancemethod.<locals>.oneshot.<locals>.memo)rd   rg   rH   rY   r   r8  r  r   r  r5   oneshot  s    z(memoized_instancemethod.<locals>.oneshotr   )r   r  r4   r  r5   memoized_instancemethod  s    	r  c                   @  s~   e Zd ZU dZesdZe Zded< ddddZ	ddd	d
Z
ddddddZG dd dee ZedddddZdS )HasMemoizedzA mixin class that maintains the names of memoized elements in a
    collection for easy cache clearing, generative, etc.

    r4   zFrozenSet[str]_memoized_keysrT   rU   c                 C  s   | j D ]}| j|d  qd S rF   )r  rH   rk   rY   elemr4   r4   r5   _reset_memoizations  s    
zHasMemoized._reset_memoizationsc                 C  s   | j D ]}|| jkstqd S rF   )r  rH   r^   r  r4   r4   r5   _assert_no_memoizations  s    
z#HasMemoized._assert_no_memoizationsrK   r   )rD  r\   r>   c                 C  s   || j |< |  j|hO  _d S rF   )rH   r  )rY   rD  r\   r4   r4   r5   _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]rc  rt   rg   rK   rd   Nrd  c                 C  s   || _ |p|j| _|j| _d S rF   rf  rg  r4   r4   r5   r   ,  s    z'HasMemoized.memoized_attribute.__init__r&   rT   r   rh  c                 C  s   d S rF   r4   ri  r4   r4   r5   rj  1  s    z&HasMemoized.memoized_attribute.__get__r    rk  c                 C  s   d S rF   r4   ri  r4   r4   r5   rj  4  s    c                 C  s8   |d kr| S |  | |j| j< }| j| jhO  _|S rF   )rc  rH   rd   r  r|  r4   r4   r5   rj  7  s
    )N)rd   re   rf   rg   r7   r   r   rj  r4   r4   r4   r5   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   )rY   r   r8  r>   c                   sN   | f||  fdd}j |_ j|_|| jj < |  jj hO  _ S )Nc                    s    S rF   r4   r~  r  r4   r5   r  I  s    zBHasMemoized.memoized_instancemethod.<locals>.oneshot.<locals>.memo)rd   rg   rH   r  r  r  r  r5   r  F  s    z4HasMemoized.memoized_instancemethod.<locals>.oneshotr   )ri   r   r  r4   r  r5   r  >  s    z#HasMemoized.memoized_instancemethodN)rd   re   rf   rg   r   rh   	frozensetr  r7   r  r  r  memoized_propertyr    r  rx  r  r4   r4   r4   r5   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__.

    r4   c                 C  s   t |d S rF   )r:   )rY   rD  r4   r4   r5   _fallback_getattre  s    zMemoizedSlots._fallback_getattrrK   r   )rD  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 rF   r4   r~  r  r4   r5   r  z  s    z8MemoizedSlots.__getattr__.<locals>.oneshot.<locals>.memo)rd   rg   rQ  )r   r8  r  r   rD  rY   r  r5   r  w  s    
z*MemoizedSlots.__getattr__.<locals>.oneshot)rJ  r:   r   r   r-   rQ  rg   r  )rY   rD  r\   r  r4   r  r5   __getattr__h  s    
zMemoizedSlots.__getattr__N)rd   re   rf   rg   rh   r  r  r4   r4   r4   r5   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offry   f0FzString is not true/false: %r)r.   rK   striprw   r0   r   rD   r4   r4   r5   asbool  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.

    rK   zUnion[str, bool]rC   c                   s   |  kr| S t | S d S rF   )r  rD   r  r4   r5   bool_or_value  s    z"bool_or_str.<locals>.bool_or_valuer4   )r  r  r4   r  r5   bool_or_str  s    r  Optional[int])r\   r>   c                 C  s   | dkr| S t | S )zCoerce to integer.N)r   )r\   r4   r4   r5   asint  s    r  zOptional[Dict[str, Any]]rT   )r8  rD  r[   
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)r.   r8   r   r  )r8  rD  r[   r  r  r4   r4   r5   coerce_kw_type  s    
r  rk  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 rF   rH   rx   krD   r4   r5   rz     s    
 z"constructor_key.<locals>.<genexpr>)r   r   )r1   ri   r   r4   rD   r5   constructor_key  s    r  )r1   ri   r   r8  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 rF   r  r  rD   r4   r5   rz     s    
 z#constructor_copy.<locals>.<genexpr>)r   rN   
difference)r1   ri   r   r8  r   r4   rD   r5   constructor_copy  s
    r  zCallable[[], int]rU   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 rF   )nextr4   counterlockr4   r5   _next  s    zcounter.<locals>._next)	threadingLockr   count)r  r4   r  r5   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   rl   rj   )r   r  r>  rj   r.   r8   r   r/   )r  r&  Zisar4   r4   r5   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'Nr4   )rx   r  r4   r4   r5   rz     s     z"assert_arg_type.<locals>.<genexpr>z6Argument '%s' is expected to be of type '%s', got '%s')r.   r   r   ArgumentErrorr{   r8   )r#  r  r~   r4   r4   r5   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__rI   NzObject '%r' is not dict-likeiterkeysc                  3  s,      D ]} d k	st| | fV  qd S rF   )r  r^   )rD  dictlikegetterr4   r5   iterator.  s    z$dictlike_iteritems.<locals>.iteratorrC  c                 3  s   | ]}| |fV  qd S rF   r4   )rx   rD  )r  r4   r5   rz   5  s     z%dictlike_iteritems.<locals>.<genexpr>)r   r   r.  r-   rA   iterrC  )r  r  r4   r  r5   r\  "  s    


r\  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]rc  r   )rc  r#  r8  c                   s    t  j|f|| |j| _d S rF   )superr   rg   )rY   rc  r#  r8  r   r4   r5   r   G  s    zclassproperty.__init__NzOptional[type]rk  c                 C  s
   |  |S rF   rz  ri  r4   r4   r5   rj  K  s    zclassproperty.__get__)N)rd   re   rf   rg   r7   r   rj  __classcell__r4   r4   r  r5   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 rF   )r   clslevelrY   r   r4   r4   r5   r   P  s    zhybridproperty.__init__r   r    ro  r,   r>   c                 C  s$   |d kr|  |}|S | |S d S rF   r  r   rY   ro  r,   Zclsvalr4   r4   r5   rj  T  s    
zhybridproperty.__get__r   zhybridproperty[_T]r   c                 C  s
   || _ | S rF   r  r  r4   r4   r5   
classlevel[  s    zhybridproperty.classlevelN)rd   re   rf   r   rj  r  r4   r4   r4   r5   r  O  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 rF   )r   r  setfnr  r4   r4   r5   r   a  s    zrw_hybridproperty.__init__r   r    r  c                 C  s$   |d kr|  |}|S | |S d S rF   r  r  r4   r4   r5   rj  f  s    
zrw_hybridproperty.__get__rT   rn  c                 C  s   | j d k	st|  || d S rF   )r  r^   rp  r4   r4   r5   rq  m  s    zrw_hybridproperty.__set__r   zrw_hybridproperty[_T]r   c                 C  s
   || _ | S rF   )r  r  r4   r4   r5   setterq  s    zrw_hybridproperty.setterc                 C  s
   || _ | S rF   r  r  r4   r4   r5   r  u  s    zrw_hybridproperty.classlevelN)rd   re   rf   r   rj  rq  r  r  r4   r4   r4   r5   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 rF   )r   r   r  r  r4   r4   r5   r   }  s    zhybridmethod.__init__r   r  c                 C  s*   |d kr| j ||jS | j||S d S rF   )r  rj  r   r   )rY   ro  r,   r4   r4   r5   rj    s    zhybridmethod.__get__r   zhybridmethod[_T]r   c                 C  s
   || _ | S rF   r  r  r4   r4   r5   r    s    zhybridmethod.classlevelN)rd   re   rf   rg   r   rj  r  r4   r4   r4   r5   r  z  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.

    rK   r~   zDict[str, symbol]symbolsNrt   r  )r~   re  	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  rI   r.   rK   r^   hashr   __new__r  r~   rg   rA   )ri   r~   re  r  r   r4   r4   r5   r    s     zsymbol.__new__c                 C  s   t | jdt| ffS )NrL   )r  r~   r   rX   r4   r4   r5   
__reduce__  s    zsymbol.__reduce__c                 C  s   t | S rF   r'  rX   r4   r4   r5   __str__  s    zsymbol.__str__c                 C  s   d| j dS )Nzsymbol()r~   rX   r4   r4   r5   __repr__  s    zsymbol.__repr__)NN)rd   re   rf   rg   r7   r  r  r  r  r  r  r  r  r4   r4   r4   r5   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 )_IntFlagMetarK   zTuple[Type[Any], ...]r   r   rT   )	classnamer   dict_r8  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  r:  z#Expected integer values for IntFlagc                 S  s   i | ]}|j |qS r4   r  )rx   r   r4   r4   r5   
<dictcomp>  s      z)_IntFlagMeta.__init__.<locals>.<dictcomp>)Z_itemsr.  r|   matchr.   r   r  rJ  rA   rQ  r   r   Zimmutabledict__members__)	ri   r  r   r  r8  r.  r  vr   r4   r4   r5   r     s    



z_IntFlagMeta.__init__zIterator[symbol]rU   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/99304rl  rX   r4   r4   r5   __iter__  s    z_IntFlagMeta.__iter__N)rd   re   rf   r   r  r4   r4   r4   r5   r    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.

    NrV  r4   r4   r4   r5   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choicer4   r4   r5   parse_user_argument_for_enum  s    
r  rr  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)ro  r4   r4   r5   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)r?   warnrV   rW   )r   r   r  r4   r4   r5   warn_exception1  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   rA   )r\   Zlen_r4   r4   r5   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   _hashrK   Sequence[Any])r\   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  )ri   r\   r  r   ZinterpolatedrY   r  r4   r5   r  S  s    z_hash_limit_string.__new__rU   c                 C  s   | j S rF   )r  rX   r4   r4   r5   __hash__]  s    z_hash_limit_string.__hash__r   r   )otherr>   c                 C  s   t | t |kS rF   )r  )rY   r  r4   r4   r5   __eq__`  s    z_hash_limit_string.__eq__)	rd   re   rf   rg   r7   r  r  r  r  r4   r4   r  r5   r  F  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   r4   r4   r5   r  d  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   r4   r4   r5   warn_limitedq  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 rF   )r  r   r  r  r  r4   r5   go  s    z#tag_method_for_warnings.<locals>.gor4   )r  r  r  r4   r  r5   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   Frd   r   Tz (r  r   )r	  )rV   	_getframer0   r|   r  _not_sa_pattern	f_globalsrI   f_coder  f_backwarningsr  )r  r  r	  frameZstacklevel_foundZwarning_tag_found_suffixZ	_categoryr4   r4   r5   r    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#  r8  r>   c                    s@    }r<  }z|| |W S    r4d|  Y nX d S )Nr   )rk   insert)r#  r8  Z	strong_fnZonce_fnr   oncer  r4   r5   r    s    zonly_once.<locals>.gor4   )r   r  r  r4   r  r5   	only_once  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   endr4   r4   r5   chop_traceback  s    

r  c                 C  s$   d|  }t   }t|| |d S )Nz&def set(obj, value):    obj.%s = valuerj   )rP  copyr   )attrnamer   r   r4   r4   r5   
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.

    r4   rT   rU   c                   sB   t | jkr4dd | jD }|r4td|  d| dt   d S )Nc                 S  s   h | ]}t |s|qS r4   )_dundersr  rx   r~   r4   r4   r5   	<setcomp>  s    
 z/TypingOnly.__init_subclass__.<locals>.<setcomp>zClass z< directly inherits TypingOnly but has additional attributes r   )r!  r   rH   r^   r  __init_subclass__)ri   	remainingr  r4   r5   r%    s    
zTypingOnly.__init_subclass__)rd   re   rf   rg   rh   r%  r  r4   r4   r  r5   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.

    rK   ensure_kwargrT   rU   c                   sf   | j }| j}|rX|D ]B}t||}|r|| }t|}|js| |}t| || qt	 
  d S rF   )r(  rH   r|   r  r   r   r   
_wrap_w_kwrQ  r  r%  )ri   Zfn_regZclsdictrD  rP   r   r   wrappedr  r4   r5   r%  +  s    

zEnsureKWArg.__init_subclass__r   r   c                   s    dddd fdd}t | S )Nr   r  c                    s    |  S rF   r4   )r#  r8  r  r4   r5   wrap;  s    z$EnsureKWArg._wrap_w_kw.<locals>.wrapr   )ri   r   r+  r4   r  r5   r)  9  s    zEnsureKWArg._wrap_w_kw)	rd   re   rf   rg   r7   r%  rx  r)  r  r4   r4   r  r5   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

    rd   re   rg   N)r   r   r   rd   re   r   rg   )wrapperr   _fr4   r4   r5   wrap_callableA  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   )r{   )rx   r   r4   r4   r5   r%    s     z'quoted_token_parser.<locals>.<listcomp>)r   r   r   )r\   r5  r}  idxlvcharr4   r4   r5   quoted_token_parserY  s$    
$


r3  )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 r4   r4   )rx   paramr  r4   r5   r    s      z8add_parameter_text.<locals>.decorate.<locals>.<dictcomp>)rg   inject_param_text)r   re  r4  r  r4   r5   r     s
    z$add_parameter_text.<locals>.decorate)r   r*  )r4  r  r   r4   r7  r5   add_parameter_text  s    
r8  c                 C  sN   |  dd}t|dkr| S |\}}|ds@|d t| S t| S d S )N
r   rv   )r   r   rJ  textwrapdedent)r  Z
split_text	firstliner&  r4   r4   r5   _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   r9  r   r   c                 S  s   g | ]\}}|  s|qS r4   )r  )rx   r  liner4   r4   r5   r%    s      z)inject_docstring_text.<locals>.<listcomp>)
r=  r   r   r   r:  r;  r  r,  minr{   )r>  r?  r@  doctextlinesZinjectlinesZblanksZ
inject_posr4   r4   r5   inject_docstring_text  s    

rE  z(\s+):param (.+?):zDict[str, str])rC  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   *rv   r   z(\s+)\Sr   r9  z::)collectionsdeque
splitlinespopleft
_param_regr  r   lstripr   r|   rm   rstriprK  r   r{   )
rC  rF  ZdoclinesrD  Z	to_injectrA  rP   r5  indentm2r4   r4   r5   r6    s6    

r6  )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#  r4   r4   r5   r%    s     z$repr_tuple_names.<locals>.<listcomp>r)  z%s, ..., %s)r   r{   )r   flagresr4   r4   r5   repr_tuple_names  s    (
rT  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_r4   r4   r5   has_compiled_ext  s    rV  c                   @  s   e Zd Ze ZdS )_MissingN)rd   re   rf   enumautoMissingr4   r4   r4   r5   rW    s   rW  )N)FF)T)T)r4   r4   r4   r4   )r4   Nr4   )NNrF  N)NNN)TN)N)F)r  )N)Nr   )F)rg   
__future__r   rH  rX  	functoolsr   rG   r   rX  r|   rV   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py314Zannotationlibr)   r*   r6   r8   rH   rj  r9   r<   rB   rE   Zpy310rQ   rR   rq   rs   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r   r  r  r  r  r0  r1  rA  rE  rT  rU  r`  ra  rb  ry  r{  r  Znon_memoized_propertypropertyZro_memoized_propertyZro_non_memoized_propertyr  r  Z!HasMemoized_ro_memoized_attributer  r  r  r  r  r  r  r  r  r  r  r\  r  r  r  r  r   r  r  r  r  ZFastIntFlagEnumr  r  r  r  r  r  rK   r  r  r  r  r7   r  compiler  r  r  Z_SQLA_REZ_UNITTEST_REr  ZNoneTyper   r"  r!  r'  r.  r3  r8  r=  rE  rL  r6  rT  rV  rW  rZ  Z	MissingOrr4   r4   r4   r5   <module>	   s  
!;	\+  5  9u%     N&   
CV+M. #<"
"


  3 ),+