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)Z	covariant_F.)Z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 r2   A./venv/lib/python3.8/site-packages/sqlalchemy/util/langhelpers.py_get_and_call_annotateF   s    
r4   __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 )Nr5   z+.__annotations__ is neither a dict nor None)r,   type_BASE_GET_ANNOTATIONSAttributeErrorr+   r-   r.   r/   r1   r2   r2   r3   _get_dunder_annotationsR   s    

r:   r   r(   Mapping[str, Any])r/   r0   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-   r4   r,   r6   callable	TypeError)r/   r0   r1   r2   r2   r3   _vendored_get_annotationsd   s     
r@   r/   r<   c                 C  s   t | tjdS )N)r0   )r@   r(   Z
FORWARDREFr/   r2   r2   r3   get_annotations   s    rC   c                 C  s
   t | S N)inspectrC   rB   r2   r2   r3   rC      s    c                 C  sB   t | tr| jdd }nt| dd }|d kr4tjS td|S d S )Nr5   r;   )r,   r6   __dict__getr+   r   Z
EMPTY_DICTr   r9   r2   r2   r3   rC      s    
str)xr<   c                 C  s*   |  d} t }||  tt| S )Nzutf-8)encoder   Zmd5_not_for_securityupdater   rH   Z	hexdigest)rI   mr2   r2   r3   md5_hex   s    

rM   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)]]rO   Noner<   c                 C  s   t  | _d S rD   )sysexc_inforO   selfr2   r2   r3   	__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 rD   )rO   AssertionErrorwith_traceback)rU   rW   rX   rY   exc_type	exc_valueexc_tbr2   r2   r3   __exit__   s    zsafe_reraise.__exit__N)__name__
__module____qualname____doc__	__slots__r5   rV   r_   r2   r2   r2   r3   rN      s
   

rN   zType[_T]zIterator[Type[_T]])clsr<   c                 c  sH   t  }| g}|rD| } | |kr$qn
||  ||   | V  qd S rD   )setpopaddextend__subclasses__)re   seenstackr2   r2   r3   walk_subclasses   s    
rm   )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,   rH   r=   )rn   r2   r2   r3   string_or_unprintable   s    

ro   z	Type[Any]Optional[str])re   use_namer<   c                 C  s&   |p| j }ddd td|D S )N c                 s  s   | ]}|  V  qd S rD   )lower).0nr2   r2   r3   	<genexpr>  s     z(clsname_as_plain_name.<locals>.<genexpr>z([A-Z][a-z]+|SQL))r`   joinrefindall)re   rq   namer2   r2   r3   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,   r6   	__class__r`   r+   )r~   r   Zcurrent_clsZmethod_nameZcurrent_methodr2   r2   r3   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   retrI   r2   r2   r3   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 rD   rH   )ibaser2   r3   <lambda>+      z!_unique_symbols.<locals>.<lambda>i  z&exhausted namespace for symbol base %s)rf   	itertoolschainmaprangerh   	NameError)r   r   Zused_setZpoolsymr2   r   r3   _unique_symbols&  s    
r   zCallable[[int], Any]intzIterator[Any])fnru   r<   c                 c  s*   |r&|| d @ }| |V  ||N }q dS )z6Call the given function given each nonzero bit from n.r   Nr2   )r   ru   br2   r2   r3   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)   rD   r2   )r   defaultskwonlydefaultszTuple[str, ...]r   r      r   r   )r   r   Fgroupedrz   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)
r`   )rE   
isfunctionismethodr=   r+   r)   r   inspect_getfullargspeclenr   r-   fromkeysr   _replacer   r   r`   r   rK   format_argspec_plusZiscoroutinefunctionreprra   typesFunctionType_exec_code_in_env__defaults____kwdefaults__r   )r   ZannofuncspecZempty_defaultsZempty_kwdefaultsnamesZ	targ_namefn_nameZmetadatacodeenvZ	decoratedr   r2   r3   decorateG  sl    




		   zdecorator.<locals>.decorater   )r   r   r2   r   r3   	decoratorD  s    Vr   zUnion[str, types.CodeType]Dict[str, Any])r   r   r   r<   c                 C  s   t | | || S rD   )exec)r   r   r   r2   r2   r3   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 )PluginLoaderNrH   zOptional[Callable[..., Any]])groupauto_fnc                 C  s   || _ i | _|| _d S rD   )r   implsr   )rU   r   r   r2   r2   r3   __init__  s    zPluginLoader.__init__c                 C  s   | j   d S rD   )r   clearrT   r2   r2   r3   r     s    zPluginLoader.clearr   )rz   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   rz   loadr   ZNoSuchModuleError)rU   rz   loaderimplr2   r2   r3   r     s    



zPluginLoader.loadrP   )rz   
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   r2   r3   r     s    z#PluginLoader.register.<locals>.loadr   )rU   rz   r   r   r   r2   r   r3   register  s    zPluginLoader.registerc                 C  s   | j |= d S rD   r   )rU   rz   r2   r2   r3   
deregister  s    zPluginLoader.deregister)N)r`   ra   rb   r   r   r   r   r   r2   r2   r2   r3   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   )rE   ZCO_VARKEYWORDSr8   r   r   r}   __code__co_argcountlistco_varnamesco_flags)r   Zco_varkeywordsr   conargsr2   r2   r3   _inspect_func_args  s    

r   )_setraiseerrr6   zOptional[Set[str]]zLiteral[True]zSet[str])re   r   r   r<   c                C  s   d S rD   r2   re   r   r   r2   r2   r3   get_cls_kwargs  s    r   Fc                C  s   d S rD   r2   r   r2   r2   r3   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   rU   )rf   rZ   rF   rG   r,   r   r   r   r   r   rK   r?   	__bases__r   discard)	re   r   r   ZtoplevelZctrZhas_initr   Zhas_kwcr2   r2   r3   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   r2   r2   r3   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)rE   Z	isbuiltinr?   r   r   r   ZFullArgSpecargsvarargsvarkwr   Z
kwonlyargsr   r   r   __self__r   Zisclassget_callable_argspecr   r   r   )r   r   r   r   r2   r2   r3   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   r2   c                 S  s   dt |  S N=r   rI   r2   r2   r3   r     r   z%format_argspec_plus.<locals>.<lambda>)Zformatvaluec                 S  s   dt |  S r   r   r   r2   r2   r3   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   Znum_defaultsZ	name_argsZdefaulted_valsr   r   r2   r2   r3   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)rU   z()r   r   z(self, *args, **kwargs)zself, *args, **kwargsz(*args, **kwargs)z*args, **kwargs)r   r   r   r   r   r   )objectr   r   r?   r-   )methodr   r   r   Zproxiedr2   r2   r3   format_argspec_init  s$    
r  r2   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 rD   r2   )re   r2   r2   r3   r     s    z&create_proxy_methods.<locals>.decorater2   )r  r  r  r  r  r  r	  r   r2   r2   r3   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)

    rU   Nr   kwargs)r   r   r?   r   r   )r  r2   r2   r3   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_clsr2   r2   r3   unbound_method_to_callable4  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 r2   r2   rt   arg)missingr2   r3   
<listcomp>d  s     z generic_repr.<locals>.<listcomp>c                 S  s   g | ]\}}||fqS r2   r2   )rt   r  defaultr2   r2   r3   r  j  s   c                 3  s   | ]}t t |d V  qd S rD   )r   r+   r  rB   r2   r3   rv   s  s     zgeneric_repr.<locals>.<genexpr>c                 S  s   g | ]}t |qS r2   r   )rt   valr2   r2   r3   r  v  s     z%s=%rz%s(%s), )r   to_listr   OrderedDict	enumerater   r   r   r?   r   r   r   ri   r   rK   rZ   zipr   r+   itemsr   r=   r   r`   rw   )r/   r  r  r  Zpos_argsZkw_argsZvargsr   Zinspr   Zdefault_lenoutputr  Zdefvalr  r2   )r  r/   r3   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   rz   r  __weakref__c                 C  s   | j | j| jdS )Nr   rz   r  r#  rT   r2   r2   r3   __getstate__  s    z$portable_instancemethod.__getstate__c                 C  s&   |d | _ |d | _|dd| _d S )Nr   rz   r  r2   )r   rz   rG   r  )rU   stater2   r2   r3   __setstate__  s    

z$portable_instancemethod.__setstate__r2   c                 C  s   |j | _|j| _|| _d S rD   )r   r   r`   rz   r  )rU   methr  r2   r2   r3   r     s    z portable_instancemethod.__init__c                 O  s    | | j t| j| j||S rD   )rK   r  r+   r   rz   )rU   r  kwr2   r2   r3   r     s    z portable_instancemethod.__call__N)r2   )	r`   ra   rb   rc   rd   r$  r&  r   r   r2   r2   r2   r3   r!    s   
r!  c                   s   | h t | j}|r| } fdd|jD }|D ]}||  | q4|jdkst|dsdq fddt|t	s|
 n|
|D D ]}||  | qqt  S )a'  Return an unordered sequence of all classes related to cls.

    Traverses diamond hierarchies.

    Fibs slightly: subclasses of builtin types are not returned.  Thus
    class_hierarchy(class A(object)) returns (A, object), not A plus every
    class systemwide that derives from object.

    c                 3  s   | ]}| kr|V  qd S rD   r2   rt   _Zhierr2   r3   rv     s      z"class_hierarchy.<locals>.<genexpr>builtinsrj   c                   s   g | ]}| kr|qS r2   r2   r)  r+  r2   r3   r    s   z#class_hierarchy.<locals>.<listcomp>)r   __mro__rg   r   r   rh   ra   r   
issubclassr6   rj   )re   Zprocessr   r   r   sr2   r+  r3   class_hierarchy  s$    




	
r0  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-  rF   )re   keyskeyr   r2   r2   r3   iterate_attributes  s    

r4  
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)rd   __del____getattribute__Z__metaclass__r$  r&  c                   s6   g | ].}| d r|d rt |s|kr|qS )r   )
startswithendswithr   rt   rL   into_clsskipr2   r3   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)r1  r+   r   r   r   r   r8   r   r   r   r?   localsr   r   setattr)r<  Zfrom_clsr=  Zonlyrz   Zfrom_instanceZdundersr  Zmaybe_fnr   r   Zfn_argsZd_argspyr   r2   r;  r3   monkeypatch_proxied_specials  sF    







rA  c                 C  s   t | d| t |d|kS )z;Return True if the two methods are the same implementation.r   )r+   )Zmeth1Zmeth2r2   r2   r3   methods_equivalent%  s
      rB  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*  )r8  r:  r2   r2   r3   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r`   ra   rb   rc   r2   r2   r2   r3   AnonymousInterfacek  s   rD  Z	Anonymousz%r: unknown in this interfacez%r=%r is not callablez,dictionary does not contain required keys %sN)r?   r,   r6   rf   r1  operatorgegtintersectionr-   rw   r`   dictlike_iteritemsr>   r?  staticmethodrh   )r/   re   r  requiredZ	interfaceZimplementedZcompliesZ	qualifierrD  foundr  r   r2   r2   r3   as_interface-  sP    !



rM  _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]fgetrp   rc   rH   r`   NrP  docc                 C  s   || _ |p|j| _|j| _d S rD   rP  rc   r`   rU   rP  rR  r2   r2   r3   r     s    zgeneric_fn_descriptor.__init__rN  rP   r   rU   r/   re   r<   c                 C  s   d S rD   r2   rU   r/   re   r2   r2   r3   __get__  s    zgeneric_fn_descriptor.__get__r   r!   r/   re   r<   c                 C  s   d S rD   r2   rV  r2   r2   r3   rW    s    zUnion[_GFD, _T_co]c                 C  s
   t  d S rD   NotImplementedErrorrV  r2   r2   r3   rW    s    instancerX   r<   c                 C  s   d S rD   r2   rU   r\  rX   r2   r2   r3   __set__  r   zgeneric_fn_descriptor.__set__r\  r<   c                 C  s   d S rD   r2   )rU   r\  r2   r2   r3   
__delete__  r   z generic_fn_descriptor.__delete__rA   c                 C  s
   t  d S rD   rY  rU   r/   r2   r2   r3   _reset  s    zgeneric_fn_descriptor._reset)r/   rz   r<   c                 C  s
   t  d S rD   rY  re   r/   rz   r2   r2   r3   reset  s    zgeneric_fn_descriptor.reset)N)r`   ra   rb   rc   r5   r   r   rW  r   r^  r`  rb  classmethodrd  r2   r2   r2   r3   rO    s    

rO  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 rD   rP  rV  r2   r2   r3   rW    s    z_non_memoized_property.__get__N)r`   ra   rb   rc   r   rW  r2   r2   r2   r3   rf    s   rf  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 rD   )rP  rF   r`   rU   r/   re   resultr2   r2   r3   rW    s    z_memoized_property.__get__c                 C  s   t || j d S rD   )rh  rd  r`   ra  r2   r2   r3   rb    s    z_memoized_property._resetc                 C  s   |j |d  d S rD   )rF   rg   rc  r2   r2   r3   rd    s    z_memoized_property.resetN)	r`   ra   rb   rc   r   rW  rb  re  rd  r2   r2   r2   r3   rh    s   rh  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 rD   r2   ar(  rj  r2   r3   memo  s    z6memoized_instancemethod.<locals>.oneshot.<locals>.memo)r`   rc   rF   rU   r   r(  rn  r   rm  r3   oneshot  s    z(memoized_instancemethod.<locals>.oneshotr   )r   rq  r2   rp  r3   memoized_instancemethod  s    	rr  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.

    r2   zFrozenSet[str]_memoized_keysrP   rQ   c                 C  s   | j D ]}| j|d  qd S rD   )rt  rF   rg   rU   elemr2   r2   r3   _reset_memoizations  s    
zHasMemoized._reset_memoizationsc                 C  s   | j D ]}|| jkstqd S rD   )rt  rF   rZ   ru  r2   r2   r3   _assert_no_memoizations  s    
z#HasMemoized._assert_no_memoizationsrH   r   )r3  rX   r<   c                 C  s   || j |< |  j|hO  _d S rD   )rF   rt  )rU   r3  rX   r2   r2   r3   _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]rP  rp   rc   rH   r`   NrQ  c                 C  s   || _ |p|j| _|j| _d S rD   rS  rT  r2   r2   r3   r   ,  s    z'HasMemoized.memoized_attribute.__init__r$   rP   r   rU  c                 C  s   d S rD   r2   rV  r2   r2   r3   rW  1  s    z&HasMemoized.memoized_attribute.__get__r    rX  c                 C  s   d S rD   r2   rV  r2   r2   r3   rW  4  s    c                 C  s8   |d kr| S |  | |j| j< }| j| jhO  _|S rD   )rP  rF   r`   rt  ri  r2   r2   r3   rW  7  s
    )N)r`   ra   rb   rc   r5   r   r   rW  r2   r2   r2   r3   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   )rU   r   r(  r<   c                   sN   | f||  fdd}j |_ j|_|| jj < |  jj hO  _ S )Nc                    s    S rD   r2   rk  rm  r2   r3   rn  I  s    zBHasMemoized.memoized_instancemethod.<locals>.oneshot.<locals>.memo)r`   rc   rF   rt  ro  rp  rm  r3   rq  F  s    z4HasMemoized.memoized_instancemethod.<locals>.oneshotr   )re   r   rq  r2   rp  r3   rr  >  s    z#HasMemoized.memoized_instancemethodN)r`   ra   rb   rc   r   rd   	frozensetrt  r5   rw  rx  ry  memoized_propertyr    r{  re  rr  r2   r2   r2   r3   rs    s   
rs  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__.

    r2   c                 C  s   t |d S rD   )r8   )rU   r3  r2   r2   r3   _fallback_getattre  s    zMemoizedSlots._fallback_getattrrH   r   )r3  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 rD   r2   rk  rm  r2   r3   rn  z  s    z8MemoizedSlots.__getattr__.<locals>.oneshot.<locals>.memo)r`   rc   r?  )r   r(  rn  r   r3  rU   rm  r3   rq  w  s    
z*MemoizedSlots.__getattr__.<locals>.oneshot)r8  r8   r   r   r+   r?  rc   r  )rU   r3  rX   rq  r2   r  r3   __getattr__h  s    
zMemoizedSlots.__getattr__N)r`   ra   rb   rc   rd   r  r  r2   r2   r2   r3   r~  [  s   r~  c                 C  sB   t | tr:|   } | dkr"dS | dkr.dS td|  t| S )N)trueZyesZonyt1T)ZfalsenoZoffru   f0FzString is not true/false: %r)r,   rH   striprs   r.   r}   rB   r2   r2   r3   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.

    rH   zUnion[str, bool]rA   c                   s   |  kr| S t | S d S rD   )r  rB   r  r2   r3   bool_or_value  s    z"bool_or_str.<locals>.bool_or_valuer2   )r  r  r2   r  r3   bool_or_str  s    r  Optional[int])rX   r<   c                 C  s   | dkr| S t | S )zCoerce to integer.N)r   )rX   r2   r2   r3   asint  s    r  zOptional[Dict[str, Any]]rP   )r(  r3  rW   
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,   r6   r}   r  )r(  r3  rW   r  r  r2   r2   r3   coerce_kw_type  s    
r  rX  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 rD   rF   rt   krB   r2   r3   rv     s    
 z"constructor_key.<locals>.<genexpr>)r   r   )r/   re   r   r2   rB   r3   constructor_key  s    r  )r/   re   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 rD   r  r  rB   r2   r3   rv     s    
 z#constructor_copy.<locals>.<genexpr>)r   rK   
difference)r/   re   r   r(  r   r2   rB   r3   constructor_copy  s
    r  zCallable[[], int]rQ   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 rD   )nextr2   counterlockr2   r3   _next  s    zcounter.<locals>._next)	threadingLockr   count)r  r2   r  r3   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   rh   rf   )r   r  r.  rf   r,   r6   r   r-   )r  r  Zisar2   r2   r3   duck_type_collection  s*    
 





r  z'Union[Tuple[Type[Any], ...], Type[Any]])r  argtyperz   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'Nr2   )rt   rl  r2   r2   r3   rv     s     z"assert_arg_type.<locals>.<genexpr>z6Argument '%s' is expected to be of type '%s', got '%s')r,   r   r   ArgumentErrorrw   r6   )r  r  rz   r2   r2   r3   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__rG   NzObject '%r' is not dict-likeiterkeysc                  3  s,      D ]} d k	st| | fV  qd S rD   )r  rZ   )r3  dictlikegetterr2   r3   iterator.  s    z$dictlike_iteritems.<locals>.iteratorr2  c                 3  s   | ]}| |fV  qd S rD   r2   )rt   r3  )r  r2   r3   rv   5  s     z%dictlike_iteritems.<locals>.<genexpr>)r   r   r  r+   r?   iterr2  )r  r  r2   r  r3   rI  "  s    


rI  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]rP  r   )rP  r  r(  c                   s    t  j|f|| |j| _d S rD   )superr   rc   )rU   rP  r  r(  r   r2   r3   r   G  s    zclassproperty.__init__NzOptional[type]rX  c                 C  s
   |  |S rD   rg  rV  r2   r2   r3   rW  K  s    zclassproperty.__get__)N)r`   ra   rb   rc   r5   r   rW  __classcell__r2   r2   r  r3   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 )hybridpropertyrz  r   c                 C  s   || _ || _d S rD   )r   clslevelrU   r   r2   r2   r3   r   P  s    zhybridproperty.__init__r   r    r\  r*   r<   c                 C  s$   |d kr|  |}|S | |S d S rD   r  r   rU   r\  r*   Zclsvalr2   r2   r3   rW  T  s    
zhybridproperty.__get__r|   zhybridproperty[_T]r   c                 C  s
   || _ | S rD   r  r  r2   r2   r3   
classlevel[  s    zhybridproperty.classlevelN)r`   ra   rb   r   rW  r  r2   r2   r2   r3   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_hybridpropertyrz  r   c                 C  s   || _ || _d | _d S rD   )r   r  setfnr  r2   r2   r3   r   a  s    zrw_hybridproperty.__init__r   r    r  c                 C  s$   |d kr|  |}|S | |S d S rD   r  r  r2   r2   r3   rW  f  s    
zrw_hybridproperty.__get__rP   r[  c                 C  s   | j d k	st|  || d S rD   )r  rZ   r]  r2   r2   r3   r^  m  s    zrw_hybridproperty.__set__r|   zrw_hybridproperty[_T]r   c                 C  s
   || _ | S rD   )r  r  r2   r2   r3   setterq  s    zrw_hybridproperty.setterc                 C  s
   || _ | S rD   r  r  r2   r2   r3   r  u  s    zrw_hybridproperty.classlevelN)r`   ra   rb   r   rW  r^  r  r  r2   r2   r2   r3   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.rz  r   c                 C  s   | | _ | _|| _d S rD   )r   r   r  r  r2   r2   r3   r   }  s    zhybridmethod.__init__r   r  c                 C  s*   |d kr| j ||jS | j||S d S rD   )r  rW  r   r   )rU   r\  r*   r2   r2   r3   rW    s    zhybridmethod.__get__r|   zhybridmethod[_T]r   c                 C  s
   || _ | S rD   r  r  r2   r2   r3   r    s    zhybridmethod.classlevelN)r`   ra   rb   rc   r   rW  r  r2   r2   r2   r3   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.

    rH   rz   zDict[str, symbol]symbolsNrp   r  )rz   rR  	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  rG   r,   rH   rZ   hashr   __new__r  rz   rc   r?   )re   rz   rR  r  r   r2   r2   r3   r    s     zsymbol.__new__c                 C  s   t | jdt| ffS )NrI   )r  rz   r   rT   r2   r2   r3   
__reduce__  s    zsymbol.__reduce__c                 C  s   t | S rD   r  rT   r2   r2   r3   __str__  s    zsymbol.__str__c                 C  s   d| j dS )Nzsymbol()rz   rT   r2   r2   r3   __repr__  s    zsymbol.__repr__)NN)r`   ra   rb   rc   r5   r  r  r  r  r  r  r  r  r2   r2   r2   r3   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 )_IntFlagMetarH   zTuple[Type[Any], ...]r   r   rP   )	classnamer   dict_r(  r<   c           	      K  s   g  | _ }| D ]Z\}}td|r(qt|tr@t||d}n|dstdnqt	| || |
| qtdd |D | _d S )Nz^__.*__$)r  r*  z#Expected integer values for IntFlagc                 S  s   i | ]}|j |qS r2   r  )rt   r   r2   r2   r3   
<dictcomp>  s      z)_IntFlagMeta.__init__.<locals>.<dictcomp>)Z_itemsr  rx   matchr,   r   r  r8  r?   r?  r   r   Zimmutabledict__members__)	re   r  r   r  r(  r  r  vr   r2   r2   r3   r     s    



z_IntFlagMeta.__init__zIterator[symbol]rQ   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/99304rY  rT   r2   r2   r3   __iter__  s    z_IntFlagMeta.__iter__N)r`   ra   rb   r   r  r2   r2   r2   r3   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.

    NrC  r2   r2   r2   r3   r    s   r  )	metaclass)IntFlag_EzDict[_E, List[Any]]zOptional[_E])r  choicesrz   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  rz   r   r  )r  r  rz   r  Z
enum_valuechoicer2   r2   r3   parse_user_argument_for_enum  s    
r  r_  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)r\  r2   r2   r3   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=   warnrR   rS   )r   r   r  r2   r2   r3   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   r?   )rX   Zlen_r2   r2   r3   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   _hashrH   Sequence[Any])rX   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  )re   rX   r  r   ZinterpolatedrU   r  r2   r3   r  S  s    z_hash_limit_string.__new__rQ   c                 C  s   | j S rD   )r  rT   r2   r2   r3   __hash__]  s    z_hash_limit_string.__hash__r   r}   )otherr<   c                 C  s   t | t |kS rD   )r  )rU   r  r2   r2   r3   __eq__`  s    z_hash_limit_string.__eq__)	r`   ra   rb   rc   r5   r  r  r  r  r2   r2   r  r3   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   r2   r2   r3   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   r2   r2   r3   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 rD   )r  r   rp  r  r  r2   r3   go  s    z#tag_method_for_warnings.<locals>.gor2   )r  r  r  r2   r  r3   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   Fr`   r   Tz (r  r   )r  )rR   	_getframer.   rx   r  _not_sa_pattern	f_globalsrG   f_coder  f_backwarningsr  )r  r  r  frameZstacklevel_foundZwarning_tag_foundZ_suffixZ	_categoryr2   r2   r3   r    s4    
 

r  rz  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   )rg   insert)r  r(  Z	strong_fnZonce_fnr   oncer  r2   r3   r    s    zonly_once.<locals>.gor2   )r   r  r  r2   r  r3   	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   endr2   r2   r3   chop_traceback  s    

r  c                 C  s$   d|  }t   }t|| |d S )Nz&def set(obj, value):    obj.%s = valuerf   )r>  copyr   )attrnamer   r   r2   r2   r3   
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.

    r2   rP   rQ   c                   sB   t | jkr4dd | jD }|r4td|  d| dt   d S )Nc                 S  s   h | ]}t |s|qS r2   )_dundersr  rt   rz   r2   r2   r3   	<setcomp>  s    
 z/TypingOnly.__init_subclass__.<locals>.<setcomp>zClass z< directly inherits TypingOnly but has additional attributes r   )r	  r   rF   rZ   r  __init_subclass__)re   	remainingr  r2   r3   r    s    
zTypingOnly.__init_subclass__)r`   ra   rb   rc   rd   r  r  r2   r2   r  r3   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.

    rH   ensure_kwargrP   rQ   c                   sf   | j }| j}|rX|D ]B}t||}|r|| }t|}|js| |}t| || qt	 
  d S rD   )r  rF   rx   r  r   r   r   
_wrap_w_kwr?  r  r  )re   Zfn_regZclsdictr3  rL   r   r   wrappedr  r2   r3   r  +  s    

zEnsureKWArg.__init_subclass__r|   r   c                   s    dddd fdd}t | S )Nr   r  c                    s    |  S rD   r2   )r  r(  rp  r2   r3   wrap;  s    z$EnsureKWArg._wrap_w_kw.<locals>.wrapr   )re   r   r  r2   rp  r3   r  9  s    zEnsureKWArg._wrap_w_kw)	r`   ra   rb   rc   r5   r  re  r  r  r2   r2   r  r3   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

    r`   ra   rc   N)r   r   r   r`   ra   r   rc   )wrapperr   Z_fr2   r2   r3   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   )rw   )rt   r   r2   r2   r3   r    s     z'quoted_token_parser.<locals>.<listcomp>)r   r   r   )rX   r%  rj  idxlvcharr2   r2   r3   quoted_token_parserY  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 r2   r2   )rt   paramr  r2   r3   r    s      z8add_parameter_text.<locals>.decorate.<locals>.<dictcomp>)rc   inject_param_text)r   rR  r  r  r2   r3   r     s
    z$add_parameter_text.<locals>.decorate)r   r  )r  r  r   r2   r  r3   add_parameter_text  s    
r  c                 C  sN   |  dd}t|dkr| S |\}}|ds@|d t| S t| S d S )N
r   rr   )r   r   r8  textwrapdedent)r  Z
split_text	firstliner  r2   r2   r3   _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 r2   )r  )rt   r  liner2   r2   r3   r    s      z)inject_docstring_text.<locals>.<listcomp>)
r$  r   r   r   r!  r"  r  r  minrw   )r%  r&  r'  doctextlinesZinjectlinesZblanksZ
inject_posr2   r2   r3   inject_docstring_text  s    

r,  z(\s+):param (.+?):zDict[str, str])r*  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   *rr   r   z(\s+)\Sr   r   z::)collectionsdeque
splitlinespopleft
_param_regr  r   lstripr   rx   ri   rstripr9  r   rw   )
r*  r-  Zdoclinesr+  Z	to_injectr(  rL   r  indentZm2r2   r2   r3   r    s6    

r  )r   r<   c                 C  s   t | dkrdS t | dk}|r,| dd n| dd | dd  } dd | D }|r`d|S d	d|dd |d f S dS )
zTrims a list of strings from the middle and return a string of up to
    four elements. Strings greater than 11 characters will be truncatedr   Nr   r   r   c                 S  s,   g | ]$}t |d kr$d|dd   n|qS )   z%s..N)r   r  r2   r2   r3   r    s     z$repr_tuple_names.<locals>.<listcomp>r  z%s, ..., %s)r   rw   )r   flagresr2   r2   r3   repr_tuple_names  s    (
r:  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_r2   r2   r3   has_compiled_ext  s    r<  c                   @  s   e Zd Ze ZdS )_MissingN)r`   ra   rb   enumautoMissingr2   r2   r2   r3   r=    s   r=  )N)FF)T)T)r2   r2   r2   r2   )r2   Nr2   )NNr5  N)NNN)TN)N)F)r  )N)Nr   )F)rc   Z
__future__r   r/  r>  	functoolsr   rE   r   rE  rx   rR   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(   r4   r6   rF   rW  r7   r:   r@   rC   Zpy310rM   rN   rm   ro   r{   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r
  r  r  r   r!  r0  r4  rA  rB  rM  rN  rO  rf  rh  r}  Znon_memoized_propertypropertyZro_memoized_propertyZro_non_memoized_propertyrr  rs  Z!HasMemoized_ro_memoized_attributer{  r~  r  r  r  r  r  r  r  r  r  rI  r  r  r  r  r   r  r  r  r  ZFastIntFlagEnumr  r  r  r  r  r  rH   r  r  r  r  r5   r  compiler  r  r  Z_SQLA_REZ_UNITTEST_REr  ZNoneTyper  r
  r	  r  r  r  r  r$  r,  r3  r  r:  r<  r=  r@  Z	MissingOrr2   r2   r2   r3   <module>	   s  
!;	\+  5  9u%     N&   
CV+M. #<"
"


  3 ),+