U
    [h                     @   sd  d Z ddlZddlmZ ddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZddlZddlmZ ddlmZ ddlmZ d	d
 ZG dd deZdd Zdd Zdd Zdd Zdd Zdd Zdd Zdd Zdd Zdd  Zdd!d"ZG d#d$ d$eZd%d& Z dd'd(Z!d)d* Z"dd,d-Z#dd/d0Z$dd1d2Z%dd4d5Z&d6d7 Z'd8d9 Z(dd:d;Z)G d<d= d=eZ*d>d? Z+d@dA Z,ddCdDZ-dEdF Z.ddGdHZ/G dIdJ dJeZ0dKdL Z1G dMdN dNeZ2G dOdP dPeZ3dQdR Z4dSdT Z5dUdV Z6ddWdXZ7dYdZ Z8d[d\ Z9d]d^ Z:dd_d`Z;dadb Z<dcdd Z=G dedf dfe>Z?G dgdh dheZ@G didj djeZAG dkdl dleBZCdmeC_DG dndm dmeZEdaFdodp ZGdqdr ZHddtduZIG dvdw dwejJZKddxdyZLdzd{ ZMdd|d}ZNd~d ZOePdZQePdZReReQfddZSeTdZUdd ZVG dd deTZWdd ZXdd ZYdd ZZdd Z[dd Z\ePdZ]dd Z^dd Z_dd Z`dS )zRoutines to help with the creation, loading and introspection of
modules, classes, hierarchies, attributes, functions, and methods.

    Nupdate_wrapper   )_collections)compat   )excc                 C   s*   t jr| d} t }||  | S )Nzutf-8)r   py3kencodehashlibmd5update	hexdigest)xm r   ?/tmp/pip-unpacked-wheel-joqu7d3y/sqlalchemy/util/langhelpers.pymd5_hex   s
    

r   c                   @   s.   e Zd ZdZdZdddZdd Zdd	 Zd
S )safe_reraiseaK  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()

    )	warn_only	_exc_infoFc                 C   s
   || _ d S N)r   )selfr   r   r   r   __init__:   s    zsafe_reraise.__init__c                 C   s   t  | _d S r   )sysexc_infor   r   r   r   r   	__enter__=   s    zsafe_reraise.__enter__c                 C   sz   |d kr0| j \}}}d | _ | jsvtj||d nFtjsb| j rb| j d rbtd| j d | j d f  d | _ tj||d d S )N)with_tracebackr   zfAn exception has occurred during handling of a previous exception.  The previous exception is:
 %s %s
r   )r   r   r   Zraise_r	   warn)r   type_value	tracebackexc_type	exc_valueexc_tbr   r   r   __exit__@   s     zsafe_reraise.__exit__N)F)__name__
__module____qualname____doc__	__slots__r   r   r&   r   r   r   r   r   &   s
   
r   c                 c   sH   t  }| g}|rD| } | |kr$qn
||  ||   | V  qd S r   )setpopaddextend__subclasses__)clsseenstackr   r   r   walk_subclassesW   s    
r4   c                 C   s<   t | tjr| S z
t| W S  tk
r6   d|   Y S X d S )Nzunprintable element %r)
isinstancer   string_typesstr	Exception)elementr   r   r   string_or_unprintablee   s    
r:   c                 C   s   d dd td| jD S )N c                 s   s   | ]}|  V  qd S r   )lower).0nr   r   r   	<genexpr>p   s    z(clsname_as_plain_name.<locals>.<genexpr>z([A-Z][a-z]+))joinrefindallr'   )r1   r   r   r   clsname_as_plain_nameo   s    
rC   c                 C   s.   t | ts| j}n| }|j}t||}||kS )z1Return True if the two class methods don't match.)r5   type	__class__r'   getattr)Zinstance_or_clsZagainst_methodZcurrent_clsmethod_nameZcurrent_methodr   r   r   method_is_overriddenu   s    

rH   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hasattrrI   appendtuple)Zslcretr   r   r   r   decode_slice   s    
rQ   c              	   '   sj   t | } |D ]X t ft fddtd}|D ] }|| kr6| | |V   qq6td  qd S )Nc                    s    t |  S r   )r7   )ibaser   r   <lambda>       z!_unique_symbols.<locals>.<lambda>i  z&exhausted namespace for symbol base %s)r,   	itertoolschainr   Zitertools_imapranger.   	NameError)usedbasespoolsymr   rS   r   _unique_symbols   s    
r_   c                 c   s*   |r&|| d @ }| |V  ||N }q dS )z6Call the given function given each nonzero bit from n.r   Nr   )fnr>   br   r   r   map_bits   s    
rb   c                    s    fdd}t | S )z'A signature-matching decorator factory.c           	         s   t | st | stdt| }i }t||}t|d |dd  | jf }t	|dd\}}t
||d}|t|dd	 | j|d
< d| }|| || d| ji t||| j}t| d| j|_| |_t|| S )Nznot a decoratable functionr   r      targetr`   )rd   r`   FgroupednamezDdef %(name)s(%(args)s):
    return %(target)s(%(fn)s, %(apply_kw)s)
r'   __func__)inspect
isfunctionismethodr8   r   inspect_getfullargspec!_update_argspec_defaults_into_envrO   r'   r_   dictr   format_argspec_plusr(   _exec_code_in_envrF   __defaults____wrapped__r   )	r`   specenvnamesZ	targ_namefn_namemetadatacode	decoratedrd   r   r   decorate   s&    

 
zdecorator.<locals>.decorater   )rd   r{   r   rz   r   	decorator   s    r|   c                 C   s|   | j rtg }d}| j D ]@}t|jdkrJd| }|||< || |d7 }q|| qt| }t||d< tj| S | S dS )zCgiven a FullArgSpec, convert defaults to be symbol names in an env.r   )builtins__builtin__zx%dr   rc   N)defaultsrD   r(   rN   listrO   r   FullArgSpec)rs   rt   Znew_defaultsrR   argrg   elemr   r   r   rm      s    



rm   c                 C   s   t | | || S r   )exec)rx   rt   rv   r   r   r   rp      s    
rp   c                 C   s  t | tr0| j}| }d|r|nd| j |f }n|  }}d| }|dd }t|}|d d= t|dd}||d	< d
| }	|t|j	d}
t
|	|
 |
| }t|dr|j\}}|j}|dkrd| j	| jf }t|d|||f d}||_n|j|_d|ddd  |_	|j	tjkr*td|j	f tjs>t|drb||j_t|jds~||f|j_n||_t|ds~||f|_|S )zProduce a wrapping function for the given cls or classmethod.

    Rationale here is so that the __init__ method of the
    class can serve as documentation for the function.

    zConstruct a new :class:`%s` object. 

This constructor is mirrored as a public API function; see :func:`sqlalchemy%s` for a full usage and argument description.z.%szSThis function is mirrored; see :func:`sqlalchemy%s` for a description of arguments..r   Fre   rg   z5def %(name)s(%(args)s):
    return cls(%(apply_kw)s)
)r1   symbolr'   
_linked_toNz%s.%sz.. container:: inherited_member

    This documentation is inherited from :func:`sqlalchemy%s`; this constructor, :func:`sqlalchemy%s`,   creates a :class:`sqlalchemy%s` object.  See that class for additional details describing this subclass.r   
sqlalchemyz0public_factory location %s is not in sys.modulesrh   )r5   rD   r   r'   splitr   rl   ro   r   r(   r   rM   r   r*   inject_docstring_textrsplitr   modulesImportErrorpy2krh   )rd   locationZclass_locationr`   Z	callable_docZlocation_namers   rw   rx   rt   ry   Z	linked_toZlinked_to_locationZlinked_to_docr   r   r   public_factory   st    







r   c                   @   s.   e Zd Zd
ddZdd Zdd Zdd	 ZdS )PluginLoaderNc                 C   s   || _ i | _|| _d S r   )groupimplsauto_fn)r   r   r   r   r   r   r   @  s    zPluginLoader.__init__c                 C   s   | j   d S r   )r   clearr   r   r   r   r   E  s    zPluginLoader.clearc                 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   rg   loadr   ZNoSuchModuleError)r   rg   loaderimplr   r   r   r   H  s    



zPluginLoader.loadc                    s    fdd}|| j |< d S )Nc                     s6   t  }  ddd  D ]}t| |} qt| S )Nr   r   )r   import_r   rF   )modtoken
modulepathobjnamer   r   r   \  s    
z#PluginLoader.register.<locals>.load)r   )r   rg   r   r   r   r   r   r   register[  s    zPluginLoader.register)N)r'   r(   r)   r   r   r   r   r   r   r   r   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   )ri   CO_VARKEYWORDSAttributeErrorr   rl   bool__code__co_argcountr   co_varnamesco_flags)r`   Zco_varkeywordsrs   conargsr   r   r   _inspect_func_argse  s    

r   c                 C   s   |dk}|rt  }| jdd}|o<t|tjo<t|jtj}|rdt|\}}|	| |sd|sddS |rl|r| j
D ]}t||dkrr qqr|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   Fr   )r,   __dict__getr5   typesFunctionTyper   CodeTyper   r   	__bases__get_cls_kwargsdiscard)r1   Z_settoplevelZctrZhas_initru   Zhas_kwcr   r   r   r   y  s(    



r   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   rl   )funcr   r   r   get_func_kwargs  s    r   Fc              	   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)no_self_is_initrh   __call__)r   zCan't inspect callable: %s)ri   	isbuiltin	TypeErrorrj   r   rl   r   argsvarargsvarkwr   
kwonlyargskwonlydefaultsannotationsrk   __self__rh   isclassget_callable_argspecr   rM   r   )r`   r   r   rs   r   r   r   r     sR    	






  r   Tc              	   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|d 7 }|d r|t|d 7 }|d |d  }|r|d| d }	nd}	t j||d |d |	d	d
 d}
|d r\t j|dd |d |d |	dd
 d}n|
}|rzt||||
||dS t|dd ||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)
      {'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]rc   r   c                 S   s   d|  S N=r   r   r   r   r   rU   3  rV   z%format_argspec_plus.<locals>.<lambda>)formatvaluec                 S   s   d|  S r   r   r   r   r   r   rU   <  rV   )r   self_arg	apply_posapply_kwapply_pos_proxiedapply_kw_proxiedr   )r   callablerl   inspect_formatargspeclenrn   )r`   rf   rs   r   r   r   r   num_defaultsZ	name_argsZdefaulted_valsr   r   r   r   r   ro     s    "

        

	




ro   c                 C   st   | t jkr$|rdnd}|rdnd}n<zt| |dW S  tk
r^   |rJdnd}|rVdnd	}Y nX td|||||d
S )a  format_argspec_plus with considerations for typical __init__ methods

    Wraps format_argspec_plus with error handling strategies for typical
    __init__ cases::

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

    z(self)r   z() re   z(self, *args, **kwargs)zself, *args, **kwargsz(*args, **kwargs)z*args, **kwargs)r   r   r   r   r   r   )objectr   ro   r   rn   )methodrf   r   Zproxiedr   r   r   format_argspec_initU  s&    

r   r   c                    s    fdd}|S )zA class decorator that will copy attributes to a proxy class.

    The class to be instrumented must define a single accessor "_proxied".

    c                    s   d	fdd	}fdd}D ].}t | |rDtd| |f t| ||| q& D ].}t | |rxtd| |f t| ||| qZD ]2}t | |rtd| |f t| |||dd q| S )
NFc           	         s   t | }t|}d|ji}t||}t|dd}|j|d |d |d |d d}|rld	| }|d
< nd| }t|||j}t |d|j|_t	|j
d f d|_
|rt|}|S )Nr'   Fre   r   r   r   r   )rg   r   r   r   r   zLdef %(name)s(%(args)s):
    return target_cls.%(name)s(%(apply_kw_proxied)s)
target_clszWdef %(name)s(%(args)s):
    return %(self_arg)s._proxied.%(name)s(%(apply_kw_proxied)s)rh   S.. container:: class_bases

    Proxied for the %s class on behalf of the %s class.r   )rF   r   rl   r(   rm   ro   r'   rp   rq   r   r*   classmethod)	rg   clslevelr`   rs   rt   Zcaller_argspecrw   rx   Zproxy_fnproxy_cls_sphinx_namer   target_cls_sphinx_namer   r   
instrument  sB    




z:create_proxy_methods.<locals>.decorate.<locals>.instrumentc                    sR   j | d }|d k	r.t|jd f d}nd }dd| i }t|d|id}|S )Nr   r   zdef set_(self, attr):
    self._proxied.%(name)s = attr
def get(self):
    return self._proxied.%(name)s
get.__doc__ = doc
getset = property(get, set_)rg   r   getset)r   r   r   r*   rp   )rg   attrr   rx   r   r   r   r   makeprop  s"    	z8create_proxy_methods.<locals>.decorate.<locals>.makepropz class %s already has a method %sTr   )F)rM   r   setattr)r1   r   r   methprop
attributesclassmethodsmethodsr   r   r   r   r   r{     s*    -





z&create_proxy_methods.<locals>.decorater   )r   r   r   r   r   r   r{   r   r   r   create_proxy_methodsv  s    cr   c                 C   sT   zt | W S  tk
rN   | tjkr8dgdddf Y S dgdddf Y S Y nX dS )zinspect.getargspec with considerations for typical __init__ methods

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

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

    r   Nr   kwargs)r   rl   r   r   r   )r   r   r   r   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)r5   r   
MethodTyper   rh   )Zfunc_or_clsr   r   r   unbound_method_to_callable  s    r   c              	      sL  |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	p|d}
|dkr|	jr|	j}|
r||	jd|
   q||	jdd  n$| fdd|	jd|
  D  |
r8|dd t|	j|
 d |	j	D  q8g }|fdd|D  |dk	rbt|rb|d	d t|D  | D ]f\}}||krqjz6t| }| k	r||kr|d
||f  W n tk
r   Y nX qj|r6|D ]X\}}z6t| }| k	r||kr|d
||f  W n tk
r0   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 r   r   r=   r   )missingr   r   
<listcomp>'  s     z generic_repr.<locals>.<listcomp>c                 S   s   g | ]\}}||fqS r   r   )r=   r   defaultr   r   r   r   ,  s   c                 3   s   | ]}t t |d V  qd S r   )reprrF   r   objr   r   r?   5  s     zgeneric_repr.<locals>.<genexpr>c                 S   s   g | ]}t |qS r   r   )r=   valr   r   r   r   8  s     z%s=%rz%s(%s), )r   to_listr   OrderedDict	enumerater   rl   r   r   r   r   r   r/   r   r   ziprM   rF   itemsrN   r8   rE   r'   r@   )r   Zadditional_kwZ
to_inspectZ
omit_kwargZpos_argsZkw_argsZvargsrR   Zinsprs   Zdefault_lenoutputr   Zdefvalr   r   )r   r   r   generic_repr  sj    

 


r   c                   @   s6   e Zd ZdZdZdd Zdd Zddd	Zd
d ZdS )portable_instancemethodz_Turn an instancemethod into a (parent, name) pair
    to produce a serializable callable.

    )rd   rg   r   __weakref__c                 C   s   | j | j| jdS )Nrd   rg   r   r  r   r   r   r   __getstate__X  s    z$portable_instancemethod.__getstate__c                 C   s&   |d | _ |d | _|dd| _d S )Nrd   rg   r   r   )rd   rg   r   r   )r   stater   r   r   __setstate___  s    

z$portable_instancemethod.__setstate__r   c                 C   s   |j | _|j| _|| _d S r   )r   rd   r'   rg   r   )r   r   r   r   r   r   r   d  s    z portable_instancemethod.__init__c                 O   s    | | j t| j| j||S r   )r   r   rF   rd   rg   )r   r   kwr   r   r   r   i  s    z portable_instancemethod.__call__N)r   )	r'   r(   r)   r*   r+   r  r  r   r   r   r   r   r   r  P  s   
r  c                    s   t jrt| tjrt S | h t| j}|r| }t jr^t|tjrHq( fdd|jD }n fdd|jD }|D ]}|	|  
| qvt jr|jdks(t|dsq(n|jdks(t|dsq( fdd| 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.

    Old-style classes are discarded and hierarchies rooted on them
    will not be descended.

    c                 3   s&   | ]}| krt |tjs|V  qd S r   )r5   r   	ClassTyper=   _Zhierr   r   r?     s    z"class_hierarchy.<locals>.<genexpr>c                 3   s   | ]}| kr|V  qd S r   r   r	  r  r   r   r?     s      r}   r0   r~   c                    s   g | ]}| kr|qS r   r   r	  r  r   r   r     s      z#class_hierarchy.<locals>.<listcomp>)r   r   r5   r   r  r   __mro__r-   r   rN   r.   r	   r(   rM   r0   )r1   processr   r\   ra   sr   r  r   class_hierarchyn  s:    


 
r  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  r   )r1   keyskeyr   r   r   r   iterate_attributes  s    

r  
self.proxyc              	      s0  |r
|}n$dkrd fddt |D }|D ]}z(t||}t|dsPW q2t|d|}W n tk
rv   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)r+   __del____getattribute____metaclass__r  r  c                    s6   g | ].}| d r|d rt |s|kr|qS )__)
startswithendswithrM   r=   r   into_clsskipr   r   r     s   


z0monkeypatch_proxied_specials.<locals>.<listcomp>r   rh   r   r   z(self, *args, **kw)z(*args, **kw)z?def %(method)s%(fn_args)s: return %(name)s.%(method)s%(d_args)s)r  rF   rM   r   r   rl   r   r   localsexec_rq   r   )r  Zfrom_clsr  onlyrg   Zfrom_instanceZdundersr   r`   rs   Zfn_argsZd_argspyrt   r   r  r   monkeypatch_proxied_specials  sB    





r#  c                 C   s   t | d| t |d|kS )z;Return True if the two methods are the same implementation.rh   )rF   )Zmeth1Zmeth2r   r   r   methods_equivalent  s
      r$  c                 C   st  |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	t}|rd
|j |_t }	t| D ]T\}
}|
|krt d|
 t|s.t d|
|f t||
t| |	|
 q||	|rZ|S t dd
||	  dS )a  Ensure basic interface compliance for an instance or dict of callables.

    Checks that ``obj`` implements public methods of ``cls`` or has members
    listed in ``methods``. If ``required`` is not supplied, implementing at
    least one interface method is sufficient. Methods present on ``obj`` that
    are not in the interface are ignored.

    If ``obj`` is a dict and ``dict`` does not meet the interface
    requirements, the keys of the dictionary are inspected. Keys present in
    ``obj`` that are not in the interface will raise TypeErrors.

    Raises TypeError if ``obj`` does not meet the interface criteria.

    In all passing cases, an object with callable members is returned.  In the
    simple case, ``obj`` is returned as-is; if dict processing kicks in then
    an anonymous class is returned.

    obj
      A type, instance, or dictionary of callables.
    cls
      Optional, a type.  All public methods of cls are considered the
      interface.  An ``obj`` instance of cls will always pass, ignoring
      ``required``..
    methods
      Optional, a sequence of method names to consider as the interface.
    required
      Optional, a sequence of mandatory implementations. If omitted, an
      ``obj`` that provides at least one interface method is considered
      sufficient.  As a convenience, required may be a type, in which case
      all public methods of the type are required.

    z2a class or collection of method names are requiredc                 S   s   g | ]}| d s|qS )r
  )r  r  r   r   r   r     s     
 z as_interface.<locals>.<listcomp>zany ofzall ofz%r does not implement %s: %sr   c                   @   s   e Zd ZdZdS )z(as_interface.<locals>.AnonymousInterfacezA callable-holding shell.N)r'   r(   r)   r*   r   r   r   r   AnonymousInterface6  s   r%  Z	Anonymousz%r: unknown in this interfacez%r=%r is not callablez,dictionary does not contain required keys %sN)r   r5   rD   r,   r  operatorgegtintersectionrn   r@   r   r'   dictlike_iteritemsr   r   r   staticmethodr.   )r   r1   r   requiredZ	interfaceZimplementedZcompliesZ	qualifierr%  foundr   r   r   r   r   as_interface  sP    !


r.  c                   @   s6   e Zd ZdZdddZdd Zdd Zed	d
 ZdS )memoized_propertyz2A read-only @property that is only evaluated once.Nc                 C   s   || _ |p|j| _|j| _d S r   fgetr*   r'   r   r1  r   r   r   r   r   Q  s    zmemoized_property.__init__c                 C   s&   |d kr| S |  | |j| j< }|S r   )r1  r   r'   r   r   r1   resultr   r   r   __get__V  s    zmemoized_property.__get__c                 C   s   t || j d S r   )r/  resetr'   )r   r   r   r   r   _reset\  s    zmemoized_property._resetc                 C   s   |j |d  d S r   )r   r-   )r1   r   rg   r   r   r   r6  _  s    zmemoized_property.reset)N)	r'   r(   r)   r*   r   r5  r7  r   r6  r   r   r   r   r/  N  s   
r/  c                    s    fdd}t | S )zDecorate a method memoize its return value.

    Best applied to no-arg methods: memoization is not sensitive to
    argument values, and will always return the same value even when
    called with different arguments.

    c                    s<   | f||  fdd}j |_ j|_|| jj <  S )Nc                     s    S r   r   ar  r4  r   r   memop  s    z6memoized_instancemethod.<locals>.oneshot.<locals>.memo)r'   r*   r   r   r   r  r;  r`   r:  r   oneshotm  s    z(memoized_instancemethod.<locals>.oneshotr   )r`   r>  r   r=  r   memoized_instancemethodd  s    	r?  c                   @   sN   e Zd ZdZdZe Zdd Zdd Zdd Z	G d	d
 d
e
Zedd ZdS )HasMemoizedzyA class that maintains the names of memoized elements in a
    collection for easy cache clearing, generative, etc.

    r   c                 C   s   | j D ]}| j|d  qd S r   )_memoized_keysr   r-   r   r   r   r   r   _reset_memoizations  s    
zHasMemoized._reset_memoizationsc                 C   s   | j D ]}|| jkstqd S r   )rA  r   AssertionErrorrB  r   r   r   _assert_no_memoizations  s    
z#HasMemoized._assert_no_memoizationsc                 C   s   || j |< |  j|hO  _d S r   )r   rA  )r   r  r!   r   r   r   _set_memoized_attribute  s    
z#HasMemoized._set_memoized_attributec                   @   s"   e Zd ZdZdddZdd ZdS )zHasMemoized.memoized_attributezTA read-only @property that is only evaluated once.

        :meta private:

        Nc                 C   s   || _ |p|j| _|j| _d S r   r0  r2  r   r   r   r     s    z'HasMemoized.memoized_attribute.__init__c                 C   s8   |d kr| S |  | |j| j< }| j| jhO  _|S r   )r1  r   r'   rA  r3  r   r   r   r5    s
    z&HasMemoized.memoized_attribute.__get__)N)r'   r(   r)   r*   r   r5  r   r   r   r   memoized_attribute  s   
rG  c                    s    fdd}t | S )z+Decorate a method memoize its return value.c                    sN   | f||  fdd}j |_ j|_|| jj < |  jj hO  _ S )Nc                     s    S r   r   r8  r:  r   r   r;    s    zBHasMemoized.memoized_instancemethod.<locals>.oneshot.<locals>.memo)r'   r*   r   rA  r<  r=  r:  r   r>    s    z4HasMemoized.memoized_instancemethod.<locals>.oneshotr   )r1   r`   r>  r   r=  r   r?    s    z#HasMemoized.memoized_instancemethodN)r'   r(   r)   r*   r+   	frozensetrA  rC  rE  rF  r   rG  r   r?  r   r   r   r   r@  {  s   r@  c                   @   s$   e Zd ZdZdZdd Z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__.

    r   c                 C   s   t |d S r   )r   )r   r  r   r   r   _fallback_getattr  s    zMemoizedSlots._fallback_getattrc                    s    drtnptd rBtd  }t| |S td rztd   fdd} j|_|S S d S )NZ	_memoizedz_memoized_attr_%sz_memoized_method_%sc                     s6   | |  fdd}j |_ j|_t|  S )Nc                     s    S r   r   r8  r:  r   r   r;    s    z8MemoizedSlots.__getattr__.<locals>.oneshot.<locals>.memo)r'   r*   r   )r   r  r;  r`   r  r   r:  r   r>    s    
z*MemoizedSlots.__getattr__.<locals>.oneshot)r  r   rM   rF   r   r*   rJ  )r   r  r!   r>  r   rK  r   __getattr__  s    

zMemoizedSlots.__getattr__N)r'   r(   r)   r*   r+   rJ  rL  r   r   r   r   rI    s   rI  c                 C   sD   t | tjr<|   } | dkr$dS | dkr0dS td|  t| S )N)trueyesonyt1T)falsenooffr>   f0FzString is not true/false: %r)r5   r   r6   stripr<   
ValueErrorr   r   r   r   r   asbool  s    rZ  c                     s    fdd}|S )zqReturn a callable that will evaluate a string as
    boolean, or one of a set of "alternate" string values.

    c                    s   |  kr| S t | S d S r   )rZ  r   textr   r   bool_or_value  s    z"bool_or_str.<locals>.bool_or_valuer   )r\  r]  r   r[  r   bool_or_str  s    r^  c                 C   s   | dkr| S t | S )zCoerce to integer.N)int)r!   r   r   r   asint  s    r`  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)r5   rD   r   rZ  )r  r  r    Z
flexi_booldestr   r   r   coerce_kw_type  s    
rb  c                    s$   t |}|ft fdd|D  S )zbProduce a tuple structure that is cacheable using the __dict__ of
    obj to retrieve values

    c                 3   s&   | ]}| j kr| j | fV  qd S r   r   r=   kr   r   r   r?     s    
 z"constructor_key.<locals>.<genexpr>)r   rO   )r   r1   ru   r   r   r   constructor_key  s    rf  c                    s0   t |}| fdd||D  |||S )zInstantiate cls using the __dict__ of obj as constructor arguments.

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

    c                 3   s&   | ]}| j kr| j | fV  qd S r   rc  rd  r   r   r   r?   *  s    
 z#constructor_copy.<locals>.<genexpr>)r   r   
difference)r   r1   r   r  ru   r   r   r   constructor_copy"  s
    rh  c                     s&   t j td  fdd} | S )z%Return a threadsafe counter function.r   c                
      s$    t  W  5 Q R  S Q R X d S r   )nextr   counterlockr   r   _next7  s    zcounter.<locals>._next)r   	threadingLockrW   count)rm  r   rj  r   rk  0  s    

rk  c                 C   s   t | dr*| jdk	r$t| jtr$tS | jS t| tr8tp: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__NrN   r.   r,   )rM   rq  
issubclassr,   r5   rD   r   rn   )Zspecimenr   Zisar   r   r   duck_type_collection>  s*    
 





rs  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'Nr   )r=   r9  r   r   r   r?   f  s     z"assert_arg_type.<locals>.<genexpr>z6Argument '%s' is expected to be of type '%s', got '%s')r5   rO   r   ArgumentErrorr@   rD   )r   Zargtyperg   r   r   r   assert_arg_type_  s    

ru  c                    s   t jrt drFt  S n(t dr0  S t drFt  S t dt dddkrnt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   	iteritems__getitem__r   NzObject '%r' is not dict-likeiterkeysc                  3   s       D ]} | | fV  qd S r   )rx  )r  dictlikegetterr   r   iterator  s    z$dictlike_iteritems.<locals>.iteratorr  c                 3   s   | ]}| |fV  qd S r   r   )r=   r  )r{  r   r   r?     s     z%dictlike_iteritems.<locals>.<genexpr>)
r   r	   rM   r   r   rv  iterrF   r   r  )rz  r|  r   ry  r   r*  o  s     




r*  c                       s(   e Zd ZdZ fddZ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.

    c                    s$   t t| j|f|| |j| _d S r   )superr~  r   r*   )r   r1  r   r  rE   r   r   r     s    zclassproperty.__init__c                 C   s
   |  |S r   )r1  )descr   r1   r   r   r   r5    s    zclassproperty.__get__)r'   r(   r)   r*   r   r5  __classcell__r   r   r  r   r~    s   
r~  c                   @   s$   e Zd Zdd Zdd Zdd ZdS )hybridpropertyc                 C   s   || _ || _d S r   )r   r   r   r   r   r   r   r     s    zhybridproperty.__init__c                 C   s$   |d kr|  |}|S | |S d S r   )r   r   )r   instanceownerZclsvalr   r   r   r5    s    
zhybridproperty.__get__c                 C   s
   || _ | S r   r   r  r   r   r   
classlevel  s    zhybridproperty.classlevelN)r'   r(   r)   r   r5  r  r   r   r   r   r    s   r  c                   @   s(   e Zd ZdZdd Zdd Zdd ZdS )	hybridmethodz/Decorate a function as cls- or instance- level.c                 C   s   | | _ | _|| _d S r   )r   rh   r   r  r   r   r   r     s    zhybridmethod.__init__c                 C   s*   |d kr| j ||jS | j||S d S r   )r   r5  rE   r   )r   r  r  r   r   r   r5    s    zhybridmethod.__get__c                 C   s
   || _ | S r   r   r  r   r   r   r    s    zhybridmethod.classlevelN)r'   r(   r)   r*   r   r5  r  r   r   r   r   r    s   r  c                   @   s.   e Zd Zd
ddZdd Zdd Zdd	 ZdS )_symbolNc                 C   s@   t |tjst|dkr t|}tt|}||_|r<||_	|S )zConstruct a new named symbol.N)
r5   r   r6   rD  hashr_  __new__r  rg   r*   )r   rg   r   	canonicalvr   r   r   r    s    z_symbol.__new__c                 C   s   t | jdt| ffS )Nr   )r   rg   r_  r   r   r   r   
__reduce__  s    z_symbol.__reduce__c                 C   s   t | S r   r   r   r   r   r   __str__  s    z_symbol.__str__c                 C   s
   d| j  S )Nz
symbol(%r))rg   r   r   r   r   __repr__  s    z_symbol.__repr__)NN)r'   r(   r)   r  r  r  r  r   r   r   r   r    s   
r  r   c                   @   s6   e Zd ZdZi Zej ZdddZ	e
d	ddZdS )
r   a  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.

    The optional ``doc`` argument assigns to ``__doc__``.  This
    is strictly so that Sphinx autoattr picks up the docstring we want
    (it doesn't appear to pick up the in-module docstring if the datamember
    is in a different module - autoattribute also blows up completely).
    If Sphinx fixes/improves this then we would no longer need
    ``doc`` here.

    Nc              
   C   sL   | j < | j|}|d kr2t||| | j|< }|W  5 Q R  S Q R X d S r   )_locksymbolsr   r  )r1   rg   r   r  r^   r   r   r   r    s
    zsymbol.__new__Fc                 C   sj   |  D ]>\}}||kr |  S |r6||jkr6|  S ||kr|  S q|dkrTdS td||f dS )a  Given a user parameter, parse the parameter into a chosen symbol.

        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 symbol object to list of possible
         entries.
        :param name: name of the argument.   Used in an :class:`.ArgumentError`
         that is raised if the parameter doesn't match any available argument.
        :param resolve_symbol_names: include the name of each symbol as a valid
         entry.

        NzInvalid value for '%s': %r)r   rg   r   rt  )r1   r   choicesrg   Zresolve_symbol_namesr^   choicer   r   r   parse_user_argument  s    
zsymbol.parse_user_argument)NN)F)r'   r(   r)   r*   r  r   rn  ro  r  r  r   r  r   r   r   r   r     s   

 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  r   r   r   set_creation_order"  s    	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)r8   r   r   r   )r   r   r   r   r   r   warn_exception/  s    r     c                 C   sF   z(t | |kr d| d|  W S | W S W n tk
r@   |  Y S X d S )Nz%s...r   )r   r   )r!   Zlen_r   r   r   ellipses_string:  s    
r  c                       s0   e Zd ZdZ fddZdd Z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,


    c                    s@   || d|  }t t| | |}td|t|| f |_|S )Nz6 (this warning may be suppressed after %d occurrences)z%s_%d)r  r  r  r  _hash)r1   r!   numr   Zinterpolatedr   r  r   r   r  O  s    z_hash_limit_string.__new__c                 C   s   | j S r   )r  r   r   r   r   __hash__W  s    z_hash_limit_string.__hash__c                 C   s   t | t |kS r   )r  )r   otherr   r   r   __eq__Z  s    z_hash_limit_string.__eq__)r'   r(   r)   r*   r  r  r  r  r   r   r  r   r  D  s   
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.

    )rx   N)_warnings_warnr   	SAWarning)msgrx   r   r   r   r   ^  s    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   r   r   r   warn_limitedk  s    r  c                 C   s   zt |}W n& tk
r&   d}Y n>   d}Y n0X |d k	rdtd|jddrd|j}|d7 }q6|d k	rtj	| ||d d ntj	| |d d d S )Nr   z^(?:sqlalchemy\.|alembic\.)r'   r   r   )
stacklevel)
r   	_getframerY  rA   match	f_globalsr   f_backwarningsr   )messagecategoryr  framer   r   r   r  u  s    
 
r  c                    s    g fdd}|S )zNDecorate the given function to be a no-op after it is called exactly
    once.c                     s@    }r<  }z|| |W S    r4d|  Y nX d S )Nr   )r-   insert)r   r  Z	strong_fnZonce_fnr`   onceretry_on_exceptionr   r   go  s    zonly_once.<locals>.gor   )r`   r  r  r   r  r   	only_once  s    r  z%sqlalchemy/([a-z_]+/){0,2}[a-z_]+\.pyzunit(?:2|test2?/)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)tbZexclude_prefixZexclude_suffixrJ   endr   r   r   chop_traceback  s    

r  c                 C   s$   d|  }t   }t|| |d S )Nz&def set(obj, value):    obj.%s = valuer,   )r  copyr   )attrnamerx   rt   r   r   r   
attrsetter  s    

r  c                       s(   e Zd ZdZ fddZdd Z  ZS )EnsureKWArgTypezYApply translation of functions to accept \**kw arguments if they
    don't already.

    c           
         sr   | j }|rZ|D ]J}t||}|r|| }t|}|js| | ||< }	t| ||	 qtt	| 
||| d S r   )Zensure_kwargrA   r  r   rl   r   
_wrap_w_kwr   r  r  r   )
r1   Zclsnamer\   ZclsdictZfn_regr  r   r`   rs   wrappedr  r   r   r     s    
zEnsureKWArgType.__init__c                    s    fdd}t | S )Nc                     s    |  S r   r   )r   r  r=  r   r   wrap  s    z(EnsureKWArgType._wrap_w_kw.<locals>.wrapr   )r   r`   r  r   r=  r   r    s    zEnsureKWArgType._wrap_w_kw)r'   r(   r)   r*   r   r  r  r   r   r  r   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'   r(   r*   N)rM   r   rE   r'   r(   r   r*   )wrapperr`   _fr   r   r   wrap_callable  s    



r  c                 C   s   d| kr|  dS d}g g}d}t| }||k r| | }|dkr|dkr|||d k r|| |d  dkr||d d |d7 }q|dN }n*|dkr|dkr|g  n|d | |d7 }q(dd |D S )a  Parse a dotted identifier with accommodation for quoted names.

    Includes support for SQL-style double quotes as a literal character.

    E.g.::

        >>> quoted_token_parser("name")
        ["name"]
        >>> quoted_token_parser("schema.name")
        ["schema", "name"]
        >>> quoted_token_parser('"Schema"."Name"')
        ['Schema', 'Name']
        >>> quoted_token_parser('"Schema"."Name""Foo"')
        ['Schema', 'Name""Foo']

    "r   r   r   r   c                 S   s   g | ]}d  |qS )r   )r@   )r=   r   r   r   r   r   '  s     z'quoted_token_parser.<locals>.<listcomp>)r   r   rN   )r!   r  r4  idxlvcharr   r   r   quoted_token_parser  s$    
$


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 r   r   )r=   paramr[  r   r   
<dictcomp>0  s      z8add_parameter_text.<locals>.decorate.<locals>.<dictcomp>)r*   inject_param_text)r`   r   paramsr\  r   r   r{   -  s
    z$add_parameter_text.<locals>.decorate)r   r   )r  r\  r{   r   r  r   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   r;   )r   r   r  textwrapdedent)r\  Z
split_text	firstline	remainingr   r   r   _dedent_docstring7  s    
r  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 r   )rX  )r=   r  liner   r   r   r   L  s      z)inject_docstring_text.<locals>.<listcomp>)
r  r   r   rN   r  r  r  r   minr@   )doctextZ
injecttextposlinesZinjectlinesZblanksZ
inject_posr   r   r   r   C  s    

r   z(\s+):param (.+?):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   *r;   r   z(\s+)\Sr   r  z::)collectionsdeque
splitlinespopleft
_param_regr  r   lstripr   rA   r/   rstripr  rN   r@   )
r  Zinject_paramsZdoclinesr  Z	to_injectr  r   r  indentm2r   r   r   r  X  s6    

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   rc   r   c                 S   s,   g | ]$}t |d kr$d|dd   n|qS )   z%s..N)r   )r=   rg   r   r   r   r     s     z$repr_tuple_names.<locals>.<listcomp>r   z%s, ..., %s)r   r@   )ru   flagresr   r   r   repr_tuple_names  s    (
r  c                  C   sF   z*ddl m}  ddl m} ddl m} W dS  tk
r@   Y dS X d S )Nr   )cimmutabledict)cprocessors)cresultproxyTF)r   r  r  r  r   )r  r  r  r   r   r   has_compiled_ext  s    r  )N)N)FF)T)T)r   r   r   )r   Nr   )NNr  N)NNN)TN)N)r  )N)Nr   )ar*   r  	functoolsr   r   ri   rW   r&  rA   r   r  r   r  r   r   r   r   r   r   r   r4   r:   rC   rH   rQ   r_   rb   r|   rm   rp   r   r   r   r   r   r   ro   r   r   r   r   r   r  r  r  r#  r$  r.  r/  r?  r@  rI  rZ  r^  r`  rb  rf  rh  rk  rs  ru  r*  propertyr~  r  r  r_  r  r'   r   r  r  r  r  	text_typer  r   r  r  r  compileZ_SQLA_REZ_UNITTEST_REr  rD   ZNoneTyper  r  r  r  r  r  r   r  r  r  r  r   r   r   r   <module>   s   1
	#
W&
+
6
p
%   
t
H3    
?
V<)

!D






,
+