B
    \                 @   s  d 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G dd deZdd Zddd Zd!d" Zdd$d%Zdd'd(Zdd)d*Z d+d, Z!d-d. Z"dd0d1Z#G d2d3 d3eZ$d4d5 Z%d6d7 Z&dd9d:Z'd;d< Z(dd=d>Z)G d?d@ d@eZ*dAdB Z+G dCdD dDeZ,G dEdF dFeZ-ddGdHZ.G dIdJ dJeZ/dKdL Z0dMdN Z1dOdP Z2ddQdRZ3dSdT Z4dUdV Z5ddWdXZ6dYdZ Z7d[d\ Z8G d]d^ d^e9Z:G d_d` d`eZ;G dadb dbeZ<G dcdd dde=Z>dee>_?G dfde deeZ@daAdgdh ZBdidj ZCddldmZDG dndo doejEZFdpdq ZGdrds ZHdtdu ZIeJdvZKeJdwZLeLeKfdxdyZMeNdZOdzd{ ZPG d|d} d}eNZQd~d ZRdd ZSdd ZTdd ZUdd ZVdd ZWdS )zRoutines to help with the creation, loading and introspection of
modules, classes, hierarchies, attributes, functions, and methods.

    )update_wrapperN   )_collections)compat   )excc             C   s*   t jr| d} t }||  | S )Nzutf-8)r   py3kencodehashlibZmd5updateZ	hexdigest)xm r   :lib/python3.7/site-packages/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__8   s    zsafe_reraise.__init__c             C   s   t  | _d S )N)sysexc_infor   )r   r   r   r   	__enter__;   s    zsafe_reraise.__enter__c             C   sz   |d kr0| j \}}}d | _ | jsvt||| nFtjsb| j rb| j d rbtd| j d | j d f  d | _ t||| d S )Nr   zfAn exception has occurred during handling of a previous exception.  The previous exception is:
 %s %s
r   )r   r   r   Zreraiser   warn)r   type_value	tracebackexc_type	exc_valueZ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   s   d dd td| jD S )N c             s   s   | ]}|  V  qd S )N)lower).0nr   r   r   	<genexpr>T   s    z(clsname_as_plain_name.<locals>.<genexpr>z([A-Z][a-z]+))joinrefindallr    )clsr   r   r   clsname_as_plain_nameR   s    r.   c             C   sB   g }x4| j | j| jfD ] }t|dr,| }|| qW 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)ZslcZretr   r   r   r   decode_sliceX   s    
r6   c          	   '   sp   t | } xb|D ]Z t ft fddtd}x2|D ]}|| kr:| | |V  P q:W td  qW d S )Nc                s    t |  S )N)str)i)baser   r   <lambda>k   s    z!_unique_symbols.<locals>.<lambda>i  z&exhausted namespace for symbol base %s)set	itertoolschainr   Zitertools_imaprangeadd	NameError)ZusedbasesZpoolsymr   )r9   r   _unique_symbolsf   s    


rC   c             c   s.   x(|r(|| d @ }| |V  ||N }qW dS )z6Call the given function given each nonzero bit from n.r   Nr   )fnr(   br   r   r   map_bitsv   s    
rF   c                s    fdd}t | S )z'A signature-matching decorator factory.c                s   t | st | stdt| }t|d |dd  | jf }t|dd\}}t	||d}|
t|dd	 | j|d
< d| }t|| || i| j}t| d| j|_| |_t|| S )Nznot a decoratable functionr   r      targetrD   )rH   rD   F)groupednamezDdef %(name)s(%(args)s):
    return %(target)s(%(fn)s, %(apply_kw)s)
im_func)inspect
isfunctionismethod	Exceptionr   inspect_getfullargspecr5   r    rC   dictr   format_argspec_plus_exec_code_in_envgetattr__defaults____wrapped__r   )rD   specnamesZ	targ_namefn_namemetadatacode	decorated)rH   r   r   decorate   s    
 
zdecorator.<locals>.decorate)r   )rH   r]   r   )rH   r   	decorator   s    r^   c             C   s   t | | || S )N)exec)r[   envrY   r   r   r   rS      s    
rS   c             C   s   t | tr$| j}| }d| j|f }n|  }}d| }|dd }t|}|d d= t|dd}||d< d	| }|td
}	t	||	 |	| }
|j
|
_
d|ddd  |
_tjst|dr||j_
n||_
|
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:`~%s` for a full usage and argument description.zJThis function is mirrored; see :func:`~%s` for a description of arguments..r   F)rI   rJ   z5def %(name)s(%(args)s):
    return cls(%(apply_kw)s)
)r-   symbolZ
sqlalchemyr   __func__)
isinstancetyper   r    splitr   rP   rR   rc   r_   r#   rsplitr!   py2kr3   rd   )rH   locationrD   Z	callable_docZlocation_namerW   rZ   r[   r`   r\   r   r   r   public_factory   s0    





rl   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 )N)groupimplsauto_fn)r   rn   rp   r   r   r   r      s    zPluginLoader.__init__c             C   s   | j   d S )N)ro   clear)r   r   r   r   rq      s    zPluginLoader.clearc             C   s   || j kr| j |  S | jr:| |}|r:|| j |< | S ydd l}W n tk
rZ   Y n,X x(|| j|D ]}|j| j |< | S W td| j|f d S )Nr   zCan't load plugin: %s:%s)	ro   rp   pkg_resourcesImportErrorZiter_entry_pointsrn   loadr   ZNoSuchModuleError)r   rJ   loaderrr   implr   r   r   rt      s     



zPluginLoader.loadc                s    fdd}|| j |< d S )Nc                 s:   t  } x$ ddd  D ]}t| |} qW t| S )Nra   r   )r   import_rg   rT   )modtoken)
modulepathobjnamer   r   rt      s    
z#PluginLoader.register.<locals>.load)ro   )r   rJ   rz   r{   rt   r   )rz   r{   r   register   s    zPluginLoader.register)N)r    r!   r"   r   rq   rt   r|   r   r   r   r   rm      s   
rm   c             C   sl   y
t j}W n. tk
r8   t| }|d t|d fS X | j}|j}t|j	d | t|j
t j@ fS d S )Nr   r   )rL   ZCO_VARKEYWORDSAttributeErrorr   rP   bool__code__co_argcountlistco_varnamesco_flags)rD   Zco_varkeywordsrW   conargsr   r   r   _inspect_func_args   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|rx| j
D ]}t||dkrtP qtW |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__getre   typesFunctionTyper   CodeTyper   r   	__bases__get_cls_kwargsdiscard)r-   Z_setZtoplevelZctrZhas_initrX   Zhas_kwcr   r   r   r     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   rP   )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_initrd   __call__)r   zCan't inspect callable: %s)rL   Z	isbuiltin	TypeErrorrM   r   rP   ZFullArgSpecargsvarargsvarkwdefaultsZ
kwonlyargsZkwonlydefaultsZannotationsrN   __self__rd   Zisclassget_callable_argspecr   r3   r   )rD   r   r   rW   r   r   r   r   G  sH    	




r   Tc       
      C   s6  t | rt | }n| }t j| }|d r:|d d }n|d rPd|d  }nd}t |d |d |d d|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}	|r
t||||	dS t|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.

    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   z%s[0]Nr      rG   r   c             S   s   d|  S )N=r   )r   r   r   r   r:     s    z%format_argspec_plus.<locals>.<lambda>)Zformatvalue)r   self_arg	apply_posapply_kwrb   )r   callablerP   inspect_formatargspeclenrQ   )
rD   rI   rW   r   r   r   Znum_defaultsZ	name_argsZdefaulted_valsr   r   r   r   rR   }  sJ     



rR   c             C   sV   | t jkr|rdpd}n.yt| |dS  tk
rD   |r<dp>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   )rI   z(self, *args, **kwargs)zself, *args, **kwargs)r   r   r   r   )objectr   rR   r   rQ   )methodrI   r   r   r   r   format_argspec_init  s    


r   c             C   sJ   y
t | S  tk
rD   | tjkr2dgdddfS dgdddf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   rP   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)re   r   
MethodTyper   rd   )Zfunc_or_clsr   r   r   unbound_method_to_callable  s    r   r   c          	      sV  |dkrg}n
t |}t  g }t  }d}xt|D ]\}}yt|j}	W n tk
rh   w:Y q:X |	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  |
r:|dd t|	j|
 d |	j	D  q:W g }|fdd|D  |dk	rdt|rd|d	d t|D  xr| D ]f\}}||krqny6t| }| k	r||kr|d
||f  W n tk
r   Y nX qnW |r@x`|D ]X\}}y6t| }| k	r ||kr |d
||f  W n tk
r8   Y nX qW d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'   arg)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 )N)reprrT   )r'   r   )objr   r   r)   3  s    zgeneric_repr.<locals>.<genexpr>c             S   s   g | ]}t |qS r   )r   )r'   valr   r   r   r   6  s    z%s=%rz%s(%s)z, )r   to_listr   OrderedDict	enumerater   rP   r   r   r   r   r   extendr   r   zipr3   rT   itemsr4   rO   	__class__r    r*   )r   Zadditional_kwZ
to_inspectZ
omit_kwargZpos_argsZkw_argsZvargsr8   ZinsprW   Zdefault_lenoutputr   Zdefvalr   r   )r   r   r   generic_repr  s`    
  
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.

    )rH   rJ   r   __weakref__c             C   s   | j | j| jdS )N)rH   rJ   r   )rH   rJ   r   )r   r   r   r   __getstate__V  s    z$portable_instancemethod.__getstate__c             C   s&   |d | _ |d | _|dd| _d S )NrH   rJ   r   r   )rH   rJ   r   r   )r   stater   r   r   __setstate__]  s    

z$portable_instancemethod.__setstate__r   c             C   s   |j | _|j| _|| _d S )N)r   rH   r    rJ   r   )r   methr   r   r   r   r   b  s    z portable_instancemethod.__init__c             O   s    | | j t| j| j||S )N)r   r   rT   rH   rJ   )r   r   kwr   r   r   r   g  s    z portable_instancemethod.__call__N)r   )	r    r!   r"   r#   r$   r   r   r   r   r   r   r   r   r   N  s   
r   c                s  t jrt| tjrt S | h t| j}x|r| }t jrbt|tjrLq* fdd|jD }n fdd|jD }x |D ]}|	|  
| q|W t jr|jdks*t|dsq*n|jdks*t|dsq*x2 fdd| D D ]}|	|  
| qW q*W 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 )N)re   r   	ClassType)r'   _)hierr   r   r)     s   z"class_hierarchy.<locals>.<genexpr>c             3   s   | ]}| kr|V  qd S )Nr   )r'   r   )r   r   r   r)     s    builtins__subclasses__Z__builtin__c                s   g | ]}| kr|qS r   r   )r'   r   )r   r   r   r     s    z#class_hierarchy.<locals>.<listcomp>)r   ri   re   r   r   r   __mro__popr   r4   r?   r   r!   r3   r   )r-   Zprocessr   rA   rE   sr   )r   r   class_hierarchyl  s4    




r   c             c   sF   t | }x8|D ]0}x*| jD ] }||jkr||j| fV  P qW qW 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   )r-   keyskeyr   r   r   r   iterate_attributes  s    

r   
self.proxyc          	      s0  |r
|}n$dkrd fddt |D }x|D ]}y&t||}t|dsPw4t|d|}W n tk
rt   w4Y nX y2t|}	t|	d }
t|	d dd }W n tk
r   d	}
d
}Y nX dt  }|dk	r||ipi }t	|| y|j
|| _
W n tk
r   Y nX t |||  q4W dS )z9Automates delegation of __specials__ for a proxying type.N)r$   __del____getattribute__Z__metaclass__r   r   c                s6   g | ].}| d r|d rt |s|kr|qS )__)
startswithendswithr3   )r'   r   )into_clsskipr   r   r     s
   


z0monkeypatch_proxied_specials.<locals>.<listcomp>r   rK   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   rT   r3   r}   r   rP   r   r   localsZexec_rU   setattr)r   Zfrom_clsr   ZonlyrJ   Zfrom_instanceZdundersr   rD   rW   Zfn_argsZd_argspyr`   r   )r   r   r   monkeypatch_proxied_specials  s<    
	




r   c             C   s   t | d| t |d|kS )z;Return True if the two methods are the same implementation.rd   )rT   )Zmeth1Zmeth2r   r   r   methods_equivalent  s    r   c             C   sx  |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 }	x`t| D ]T\}
}|
|krt d|
 t|s0t d|
|f t||
t| |	|
 qW ||	|r^|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   r     s    z as_interface.<locals>.<listcomp>zany ofzall ofz%r does not implement %s: %sz, 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   AnonymousInterface4  s   r   Z	Anonymousz%r: unknown in this interfacez%r=%r is not callablez,dictionary does not contain required keys %sN)r   re   rf   r;   r   operatorgegtintersectionrQ   r*   r   r    dictlike_iteritemsr   r   r   staticmethodr?   )r   r-   methodsZrequiredZ	interfaceZimplementedZcompliesZ	qualifierr   foundr   rv   r   r   r   as_interface  sH    !


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 )N)fgetr#   r    )r   r   rk   r   r   r   r   O  s    zmemoized_property.__init__c             C   s&   |d kr| S |  | |j| j< }|S )N)r   r   r    )r   r   r-   resultr   r   r   __get__T  s    zmemoized_property.__get__c             C   s   t || j d S )N)r   resetr    )r   r   r   r   r   _resetZ  s    zmemoized_property._resetc             C   s   |j |d  d S )N)r   r   )r-   r   rJ   r   r   r   r   ]  s    zmemoized_property.reset)N)	r    r!   r"   r#   r   r   r   classmethodr   r   r   r   r   r   L  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 )Nr   )ar   )r   r   r   memon  s    z6memoized_instancemethod.<locals>.oneshot.<locals>.memo)r    r#   r   )r   r   r   r   )rD   )r   r   oneshotk  s    z(memoized_instancemethod.<locals>.oneshot)r   )rD   r   r   )rD   r   memoized_instancemethodb  s    	r   c               @   s2   e Zd ZdZdddZdd Zdd Zd	d
 ZdS )!group_expirable_memoized_propertyz?A family of @memoized_properties that can be expired in tandem.r   c             C   s   g | _ |r| j | d S )N)
attributesr   )r   r   r   r   r   r   |  s    z*group_expirable_memoized_property.__init__c             C   s&   |j }x| jD ]}||d qW dS )z.Expire all memoized properties for *instance*.N)r   r   r   )r   instanceZstashZ	attributer   r   r   expire_instance  s    z1group_expirable_memoized_property.expire_instancec             C   s   | j |j t|S )N)r   r4   r    r   )r   rD   r   r   r   r     s    z*group_expirable_memoized_property.__call__c             C   s   | j |j t|S )N)r   r4   r    r   )r   rD   r   r   r   r     s    z(group_expirable_memoized_property.methodN)r   )r    r!   r"   r#   r   r   r   r   r   r   r   r   r   y  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 )N)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 )Nr   )r   r   )r   r   r   r     s    z8MemoizedSlots.__getattr__.<locals>.oneshot.<locals>.memo)r    r#   r   )r   r   r   )rD   r   r   )r   r   r     s    
z*MemoizedSlots.__getattr__.<locals>.oneshot)r   r}   r3   rT   r   r#   r   )r   r   r   r   r   )rD   r   r   r   __getattr__  s    

zMemoizedSlots.__getattr__N)r    r!   r"   r#   r$   r   r   r   r   r   r   r     s   r   c                s    fdd}|S )Nc                sn    d}td|dd t t |d g}t||d }t|| j|   rjt	|drj|j
| j | S )Nra   r   rb   __all__)rg   r   rw   r*   globalsr   rT   r   r    r3   r   r4   )r   tokensrx   )
add_to_all
modulenamer   r   r]     s    
$z dependency_for.<locals>.decorater   )r   r   r]   r   )r   r   r   dependency_for  s    r   c               @   sF   e Zd ZdZdd Zdd Zedd Ze Z	i Z
G dd	 d	eZd
S )dependenciesa  Apply imported dependencies as arguments to a function.

    E.g.::

        @util.dependencies(
            "sqlalchemy.sql.widget",
            "sqlalchemy.engine.default"
        );
        def some_func(self, widget, default, arg1, arg2, **kw):
            # ...

    Rationale is so that the impact of a dependency cycle can be
    associated directly with the few functions that cause the cycle,
    and not pollute the module-level namespace.

    c          
   G   sH   g | _ x<|D ]4}|d}| j td|dd |d  qW d S )Nra   r   rb   )import_depsrg   r4   r   _importlaterr*   )r   ZdepsZdepr   r   r   r   r     s
    

zdependencies.__init__c             C   s   | j }t|}t|d }|d dk}x0tt|D ] }d| |d ||rPdnd < q6W t|dd}x|D ]}||rzdnd= qlW ||d d d < t|dd}	d|	d |d	 d
 }
t|
t }t	|d|j
|_
t||S )Nr   )r   r-   zimport_deps[%r]r   F)rI   z!lambda %(args)s: fn(%(apply_kw)s)r   r   )r   r   rK   )r   r   rP   r   r>   r   rR   evalr   rT   rU   r   )r   rD   r   rW   Z	spec_zeroZhasselfr8   Z
inner_specZimpnameZ
outer_specr[   r\   r   r   r   r     s"    
 
zdependencies.__call__c             C   s,   x&t tjD ]}|j|r|  qW d S )N)r   r   _unresolved
_full_pathr   _resolve)r-   pathr   r   r   r   resolve_all  s    zdependencies.resolve_allc               @   sN   e Zd Ze Zi Zdd Zdd Zedd Z	e
dd Zd	d
 Zdd ZdS )zdependencies._importlaterc             C   s<   |d | }|t jkr t j| S t|  t j|< }|S d S )Nra   )r   _by_keyr   __new__)r-   r  addtlr   impr   r   r   r  
  s
    

z!dependencies._importlater.__new__c             C   s   || _ || _tj|  d S )N)_il_path	_il_addtlr   r  r?   )r   r  r	  r   r   r   r     s    z"dependencies._importlater.__init__c             C   s   | j d | j S )Nra   )r  r  )r   r   r   r   r    s    z$dependencies._importlater._full_pathc             C   s,   | t jkrtd| j| jf t| j| jS )Nz<importlater.resolve_all() hasn't been called (this is %s %s))r   r  rs   r  r  rT   _initial_import)r   r   r   r   module  s
    
z dependencies._importlater.modulec             C   s,   t j|  t| jt t | jg| _	d S )N)
r   r  r   r   rw   r  r   r   r  r  )r   r   r   r   r  &  s    z"dependencies._importlater._resolvec             C   s\   |dkrt d| j yt| j|}W n& tk
rL   td| j|f Y nX || j|< |S )Nr  zCould not resolve module %szModule %s has no attribute '%s')rs   r  rT   r  r}   r   )r   r   attrr   r   r   r   ,  s    
z%dependencies._importlater.__getattr__N)r    r!   r"   r;   r  r  r  r   propertyr  r   r  r  r   r   r   r   r   r     s   r   N)r    r!   r"   r#   r   r   r   r  r;   r  r  r   r   r   r   r   r   r     s   r   c             C   sD   t | tjr<|   } | dkr$dS | dkr0dS td|  t| S )N)trueZyesZonyt1T)ZfalseZnoZoffr(   f0FzString is not true/false: %r)re   r   string_typesstripr&   
ValueErrorr~   )r   r   r   r   asbool<  s    r  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 )N)r  )r   )textr   r   bool_or_valueN  s    z"bool_or_str.<locals>.bool_or_valuer   )r  r  r   )r  r   bool_or_strH  s    r  c             C   s   | dkr| S t | S )zCoerce to integer.N)int)r   r   r   r   asintW  s    r  c             C   s^   || krZt |tr t | | |sZ| | dk	rZ|tkrJ|rJt| | | |< 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)re   rf   r~   r  )r   r   r   Z
flexi_boolr   r   r   coerce_kw_type_  s    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 )N)r   )r'   k)r   r   r   r)   y  s    z#constructor_copy.<locals>.<genexpr>)r   r   
difference)r   r-   r   r   rX   r   )r   r   constructor_copyp  s    r#  c                 s&   t j td  fdd} | S )z%Return a threadsafe counter function.r   c                  s       zt S   X d S )N)acquirenextreleaser   )counterlockr   r   _next  s    zcounter.<locals>._next)r   	threadingLockr<   count)r)  r   )r'  r(  r   r'  ~  s    

r'  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__Nr4   r?   r;   )r3   r-  
issubclassr;   re   rf   r   rQ   )Zspecimenr   Zisar   r   r   duck_type_collection  s&    







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'Nr   )r'   r   r   r   r   r)     s    z"assert_arg_type.<locals>.<genexpr>z6Argument '%s' is expected to be of type '%s', got '%s')re   r5   r   ZArgumentErrorr*   rf   )r   ZargtyperJ   r   r   r   assert_arg_type  s    

$r0  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$   x   D ]} | | fV  q
W d S )N)r3  )r   )dictlikegetterr   r   iterator  s    z$dictlike_iteritems.<locals>.iteratorr   c             3   s   | ]}| |fV  qd S )Nr   )r'   r   )r5  r   r   r)     s    z%dictlike_iteritems.<locals>.<genexpr>)
r   r   r3   r   r   r1  iterrT   r   r   )r4  r6  r   )r4  r5  r   r     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 )N)superr8  r   r#   )r   r   r   r   )r   r   r   r     s    zclassproperty.__init__c             C   s
   |  |S )N)r   )Zdescr   r-   r   r   r   r     s    zclassproperty.__get__)r    r!   r"   r#   r   r   __classcell__r   r   )r   r   r8    s   	r8  c               @   s   e Zd Zdd Zdd ZdS )hybridpropertyc             C   s
   || _ d S )N)r   )r   r   r   r   r   r     s    zhybridproperty.__init__c             C   s.   |d kr |  |}| j j|_|S |  |S d S )N)r   r#   )r   r   ownerZclsvalr   r   r   r     s
    

zhybridproperty.__get__N)r    r!   r"   r   r   r   r   r   r   r;    s   r;  c               @   s    e Zd ZdZdd Zdd ZdS )hybridmethodz/Decorate a function as cls- or instance- level.c             C   s
   || _ d S )N)r   )r   r   r   r   r   r      s    zhybridmethod.__init__c             C   s*   |d kr| j ||jS | j ||S d S )N)r   r   r   )r   r   r<  r   r   r   r     s    zhybridmethod.__get__N)r    r!   r"   r#   r   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)
re   r   r  AssertionErrorhashr  r  r>  rJ   r#   )r   rJ   rk   	canonicalvr   r   r   r    s    z_symbol.__new__c             C   s   t | jdt| ffS )Nr   )rc   rJ   r  )r   r   r   r   
__reduce__  s    z_symbol.__reduce__c             C   s   t | S )N)r   )r   r   r   r   __str__  s    z_symbol.__str__c             C   s
   d| j  S )Nz
symbol(%r))rJ   )r   r   r   r   __repr__  s    z_symbol.__repr__)NN)r    r!   r"   r  rC  rD  rE  r   r   r   r   r>  
  s   
r>  rc   c               @   s(   e Zd ZdZi Zej ZdddZ	dS )rc   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   sJ   | j   z.| j|}|d kr6t||| | j|< }|S tj   X d S )N)_lockr$  symbolsr   r>  rc   r&  )r-   rJ   rk   rA  rB   r   r   r   r  <  s    
zsymbol.__new__)NN)
r    r!   r"   r#   rG  r   r*  r+  rF  r  r   r   r   r   rc   #  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_orderJ  s    	rI  c             O   s<   y
| ||S  t k
r6   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)rO   r   r   r   )r   r   r   r   r   r   warn_exceptionW  s    
rJ     c             C   s>   y$t | |krd| d|  S | S W n tk
r8   | S X d S )Nz%s...r   )r   r   )r   Zlen_r   r   r   ellipses_stringb  s    rL  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)r9  rM  r  r@  _hash)r-   r   numr   Zinterpolatedr   )r   r   r   r  w  s
    
z_hash_limit_string.__new__c             C   s   | j S )N)rN  )r   r   r   r   __hash__  s    z_hash_limit_string.__hash__c             C   s   t | t |kS )N)r@  )r   otherr   r   r   __eq__  s    z_hash_limit_string.__eq__)r    r!   r"   r#   r  rP  rR  r:  r   r   )r   r   rM  l  s   	rM  c             C   s   t j| tjdd dS )zdIssue a warning.

    If msg is a string, :class:`.exc.SAWarning` is used as
    the category.

    r   )
stacklevelN)warningsr   r   	SAWarning)msgr   r   r   r     s    r   c             C   s&   |rt | d|} tj| tjdd dS )z\Issue a warning with a parameterized string, limiting the number
    of registrations.

    
   r   )rS  N)rM  rT  r   r   rU  )rV  r   r   r   r   warn_limited  s    rX  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   }|| |S d S )N)r   )r   r   Zonce_fn)oncer   r   go  s    zonly_once.<locals>.gor   )rD   rZ  r   )rY  r   	only_once  s    r[  z%sqlalchemy/([a-z_]+/){0,2}[a-z_]+\.pyzunit(?:2|test2?/)c             C   sh   d}t | d }x"||kr2|| | r2|d7 }qW x"||krV|| | rV|d8 }q6W | ||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_suffixr0   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_   )Zattrnamer[   r`   r   r   r   
attrsetter  s    

ra  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       
         sv   | j }|r^xR|D ]J}t||}|r|| }t|}|js| | ||< }	t| ||	 qW tt	| 
||| d S )N)Zensure_kwargr+   matchr   rP   r   
_wrap_w_kwr   r9  rb  r   )
r-   ZclsnamerA   ZclsdictZfn_regr   r   rD   rW   wrapped)r   r   r   r     s    

zEnsureKWArgType.__init__c                s    fdd}t | S )Nc                 s    |  S )Nr   )r   r   )rD   r   r   wrap  s    z(EnsureKWArgType._wrap_w_kw.<locals>.wrap)r   )r   rD   rf  r   )rD   r   rd    s    zEnsureKWArgType._wrap_w_kw)r    r!   r"   r#   r   rd  r:  r   r   )r   r   rb    s   rb  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)r3   r   r   r    r!   r   r#   )wrapperrD   Z_fr   r   r   wrap_callable  s    



rh  c             C   s   d| kr|  dS d}g g}d}t| }x||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*W 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']

    "ra   r   r   rb   c             S   s   g | ]}d  |qS ) )r*   )r'   ry   r   r   r   r   '  s    z'quoted_token_parser.<locals>.<listcomp>)rg   r   r4   )r   r   r   idxZlvcharr   r   r   quoted_token_parser  s$    

$

rm  c                s   t    fdd}|S )Nc                s:   | j d k	r| j pd}|r0t|fdd D }|| _ | S )Nrj  c                s   i | ]
} |qS r   r   )r'   param)r  r   r   
<dictcomp>0  s    z8add_parameter_text.<locals>.decorate.<locals>.<dictcomp>)r#   inject_param_text)rD   rk   )paramsr  r   r   r]   -  s
    z$add_parameter_text.<locals>.decorate)r   r   )rq  r  r]   r   )rq  r  r   add_parameter_text*  s    
rr  c             C   sN   |  dd}t|dkr| S |\}}|ds@|d t| S t| S d S )N
r   r%   )rg   r   r   textwrapdedent)r  Z
split_text	firstlineZ	remainingr   r   r   _dedent_docstring7  s    
rw  c             C   s   t | pd} | d}t|d}|d r:|dd dd t|D }|dd |t|t|d  }|d| | ||d   }d|S )Nrj  rs  r   c             S   s   g | ]\}}|  s|qS r   )r  )r'   rO  liner   r   r   r   J  s    z)inject_docstring_text.<locals>.<listcomp>r   )	rw  rg   rt  ru  insertr   minr   r*   )doctextZ
injecttextposlinesZinjectlinesZblanksZ
inject_posr   r   r   inject_docstring_textC  s    
r~  c       
      C   s:  |   }g }d }x|r.|d}|d krtd|}|r|d}||krdt|d d }|rtd|d }	|	rdt|	d }|||  }n| dr|d || |d d }nT|	 s|| || |d d }n(|
d	r"|| ||d q|| qW d|S )
Nr   z(\s+):param (?:\\\*\*?)?(.+?):r   r%   r   z(\s+)\Sz:param rs  z::)
splitlinesr   r+   rc  rn   r   lstripr   r4   rstripr   r*   )
r{  Zinject_paramsZdoclinesr}  Z	to_injectrx  r   rn  indentZm2r   r   r   rp  S  sB    









rp  )N)FF)T)T)r   Nr   )NNr   N)NNN)F)T)N)rK  )Xr#   	functoolsr   r
   rL   r<   r   r+   r   rt  r   rT  rj  r   r   r   r   r   r   r.   r6   rC   rF   r^   rS   rl   rm   r   r   r   r   rR   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r  r  r   r#  r'  r/  r0  r   r  r8  r;  r=  r  r>  r    rc   rH  rI  rJ  rL  Z	text_typerM  r   rX  r[  compileZ_SQLA_REZ_UNITTEST_REr_  rf   ZNoneTypera  rb  rh  rm  rr  rw  r~  rp  r   r   r   r   <module>   s   .	0*
+
6
S

H3   
9
V(
u

!$

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