o
    [h[                     @   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dd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&			8	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.dIdJ Z/dKdL Z0dMdN Z1ddOdPZ2dQdR Z3dSdT Z4ddUdVZ5dWdX Z6dYdZ Z7G d[d\ d\e8Z9G d]d^ d^eZ:G d_d` d`eZ;G dadb dbe<Z=dce=_>G dddc dceZ?da@dedf ZAdgdh ZBddjdkZCG dldm dmejDZEdndo ZFdpdq ZGdrds ZHeIdtZJeIduZKeKeJfdvdwZLeMdZNdxdy ZOG dzd{ d{eMZPd|d} 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hashlibmd5update	hexdigest)xm r   /home/ubuntu/experiments/live_experiments/Pythonexperiments/Otree/venv/lib/python3.10/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   
   || _ d S N)r   )selfr   r   r   r   __init__8      
zsafe_reraise.__init__c                 C   s   t  | _d S r   )sysexc_infor   r   r   r   r   	__enter__;      zsafe_reraise.__enter__c                 C   s   |d u r| j \}}}d | _ | jstj||d d S d S tjs4| j r4| j d r4t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   s   d dd td| jD S )N c                 s   s    | ]}|  V  qd S r   )lower).0nr   r   r   	<genexpr>V   s    
z(clsname_as_plain_name.<locals>.<genexpr>z([A-Z][a-z]+))joinrefindallr+   )clsr   r   r   clsname_as_plain_nameU   s   
r9   c                 C   s>   g }| j | j| jfD ]}t|dr| }|| q
t|S )zrdecode a slice object as sent to __getitem__.

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

    	__index__)startstopstephasattrr:   appendtuple)Zslcretr   r   r   r   decode_slice[   s   
rB   c              	   '   sl    t | } |D ], t ft fddtd}|D ]}|| vr,| | |V   nqtd  qd S )Nc                    s    t |  S r   )str)ibaser   r   <lambda>n   s    z!_unique_symbols.<locals>.<lambda>i  z&exhausted namespace for symbol base %s)set	itertoolschainr   Zitertools_imaprangeadd	NameError)usedbasespoolsymr   rE   r   _unique_symbolsi   s    
rR   c                 c   s2    |r|| d @ }| |V  ||N }|sdS dS )z6Call the given function given each nonzero bit from n.r   Nr   )fnr3   br   r   r   map_bitsy   s   
rU   c                        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      targetrS   )rX   rS   FgroupednamezDdef %(name)s(%(args)s):
    return %(target)s(%(fn)s, %(apply_kw)s)
im_func)inspect
isfunctionismethod	Exceptionr   inspect_getfullargspecr@   r+   rR   dictr   format_argspec_plus_exec_code_in_envgetattr__defaults____wrapped__r   )rS   specnamesZ	targ_namefn_namemetadatacode	decoratedrX   r   r   decorate   s$   
 

zdecorator.<locals>.decorater   )rX   ro   r   rn   r   	decorator   s   
rp   c                 C   s   t | | || S r   )exec)rl   envrj   r   r   r   rd      s   
rd   c                 C   sv  t | tr| j}| }d|r|nd| j |f }n|  }}d| }|dd }t|}|d d= t|dd}||d	< d
| }	|td}
t	|	|
 |
| }t
|dru|j\}}|j}|du rfd| j| jf }t|d|||f d}||_n|j|_d|ddd  |_|jtjvrtd|jf tjst
|dr||j_t
|jds||f|j_|S ||_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   FrY   r[   z5def %(name)s(%(args)s):
    return cls(%(apply_kw)s)
)r8   symbol
_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   Z
sqlalchemyz0public_factory location %s is not in sys.modules__func__)
isinstancetyper   r+   splitr   ra   rc   ru   rq   r>   rv   r.   r,   inject_docstring_textrsplitr   modulesImportErrorpy2krw   )rX   locationZclass_locationrS   Z	callable_docZlocation_namerh   rk   rl   rr   rm   Z	linked_toZlinked_to_locationZlinked_to_docr   r   r   public_factory   sp   









r   c                   @   .   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      r    zPluginLoader.clearc                 C   s   || j v r| j |  S | jr| |}|r|| j |< | S zdd l}W n	 ty,   Y nw || j|D ]}|j| j |< |   S td| j|f )Nr   zCan't load plugin: %s:%s)	r   r   pkg_resourcesr~   iter_entry_pointsr   loadr   ZNoSuchModuleError)r   r[   loaderr   implr   r   r   r     s$   


zPluginLoader.loadc                    s    fdd}|| j |< d S )Nc                     s6   t  }  ddd  D ]}t| |} qt| S )Nrs   r   )r   import_rz   re   )modtoken
modulepathobjnamer   r   r     s   

z#PluginLoader.register.<locals>.load)r   )r   r[   r   r   r   r   r   r   register  s   zPluginLoader.registerr   )r+   r,   r-   r   r   r   r   r   r   r   r   r      s
    
r   c                 C   sh   zt j}W n ty   t| }|d t|d f Y S w | j}|j}t|j	d | t|j
|@ fS )Nr   r   )r]   CO_VARKEYWORDSAttributeErrorr   ra   bool__code__co_argcountlistco_varnamesco_flags)rS   Zco_varkeywordsrh   conargsr   r   r   _inspect_func_args#  s   

	r   c                 C   s   |du }|r	t  }| jdd}|ot|tjot|jtj}|r2t|\}}|	| |s2|s2dS |r6|rE| j
D ]}t||du rD nq9|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   )rH   __dict__getrx   typesFunctionTyper   CodeTyper   r   	__bases__get_cls_kwargsdiscard)r8   Z_settoplevelZctrZhas_initri   Zhas_kwcr   r   r   r   7  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   ra   funcr   r   r   get_func_kwargsb  s   r   Fc              	   C   s0  t | rtd|  t | r4|r/|r/t| }t|jdd |j|j	|j
|j|j|jS t| S t | rb|r\|s@| jr\t| j}t|jdd |j|j	|j
|j|j|jS t| jS t | rot| j|ddS t| drzt| jS t| drt | jrt| j|dS td	|  td	|  )
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_initrw   __call__)r   zCan't inspect callable: %s)r]   	isbuiltin	TypeErrorr^   r   ra   FullArgSpecargsvarargsvarkwdefaults
kwonlyargskwonlydefaultsannotationsr_   __self__rw   isclassget_callable_argspecr   r>   r   )rS   r   r   rh   r   r   r   r   m  sN   
	








r   Tc           
      C   s0  t | rt | }n| }t j| }|d r|d d }n|d r(d|d  }nd}t |d |d |d d|d }d}|d rI|t|d 7 }|d rU|t|d 7 }|d |d  }|rh|d| d }nd}t j||d |d |d	d
 d}	|rt||||	dS t|dd ||dd |	dd 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      rW   r   c                 S   s   d|  S )N=r   )r   r   r   r   rG     s    z%format_argspec_plus.<locals>.<lambda>)formatvalue)r   self_arg	apply_posapply_kwrt   )r   callablera   inspect_formatargspeclenrb   )
rS   rZ   rh   r   r   r   num_defaultsZ	name_argsZdefaulted_valsr   r   r   r   rc     sR   
 



rc   c                 C   sV   | t ju r|r	dp
d}nzt| |dW S  ty"   |rdpd}Y nw 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   rY   z(self, *args, **kwargs)zself, *args, **kwargs)r   r   r   r   )objectr   rc   r   rb   )methodrZ   r   r   r   r   format_argspec_init  s   

r   c                 C   sJ   zt | W S  ty$   | tju rdgdddf Y S dgdddf Y S w )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   ra   r   r   r   )r   r   r   r   getargspec_init  s   	
r   c                 C   s   t | tjr| js| jS | S )zSAdjust the incoming callable such that a 'self' argument is not
    required.

    )rx   r   
MethodTyper   rw   )Zfunc_or_clsr   r   r   unbound_method_to_callable   s   r   r   c              	      s(  |du rg}nt |}t  g }t  }d}t|D ]k\}}zt|j}	W n	 ty1   Y qw |	j	r:t
|	j	p;d}
|dkr_|	jrF|	j}|
rT||	jd|
   n||	jdd  n| fdd|	jd|
  D  |
r|dd t|	j|
 d |	j	D  qg }|fdd|D  |durt|r|d	d t|D  | D ]+\}}||v rqzt| }| ur||kr|d
||f  W q ty   Y qw |r	|D ]'\}}zt| }| ur||kr|d
||f  W q ty   Y 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   r2   arg)missingr   r   
<listcomp>K      z generic_repr.<locals>.<listcomp>c                 S   s   g | ]\}}||fqS r   r   )r2   r   defaultr   r   r   r   P  s    c                 3   s     | ]}t t |d V  qd S r   )reprre   r   objr   r   r4   Y  s    zgeneric_repr.<locals>.<genexpr>c                 S   s   g | ]}t |qS r   r   )r2   valr   r   r   r   \  r   z%s=%rz%s(%s), )r   to_listr   OrderedDict	enumerater   ra   r   r   r   r   r   extendr   r   zipr>   re   itemsr?   r`   	__class__r+   r5   )r   Zadditional_kwZ
to_inspectZ
omit_kwargZpos_argsZkw_argsZvargsrD   Zinsprh   Zdefault_lenoutputr   Zdefvalr   r   )r   r   r   generic_repr,  st   
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.

    )rX   r[   r   __weakref__c                 C   s   | j | j| jdS )NrX   r[   r   r   r   r   r   r   __getstate__|  s   z$portable_instancemethod.__getstate__c                 C   s&   |d | _ |d | _|dd| _d S )NrX   r[   r   r   )rX   r[   r   r   )r   stater   r   r   __setstate__  s   

z$portable_instancemethod.__setstate__r   c                 C   s   |j | _|j| _|| _d S r   )r   rX   r+   r[   r   )r   methr   r   r   r   r     s   
z portable_instancemethod.__init__c                 O   s$   | | j t| j| j|i |S r   )r   r   re   rX   r[   )r   r   kwr   r   r   r     s   z portable_instancemethod.__call__Nr   )	r+   r,   r-   r.   r/   r   r   r   r   r   r   r   r   r   t  s    
r   c                    s   t jrt| tjrt S | h t| j}|r|| }t jr/t|tjr$q fdd|jD }n
 fdd|jD }|D ]}|	|  
| q;t jrW|jdksUt|dsVqn|jdksat|dsbq fdd| D D ]}|	|  
| qm|s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(    | ]}| vrt |tjs|V  qd S r   )rx   r   	ClassTyper2   _Zhierr   r   r4     s    z"class_hierarchy.<locals>.<genexpr>c                 3   s    | ]	}| vr|V  qd S r   r   r   r   r   r   r4         builtins__subclasses____builtin__c                    s   g | ]}| vr|qS r   r   r   r   r   r   r     s    z#class_hierarchy.<locals>.<listcomp>)r   r   rx   r   r   r   __mro__popr   r?   rL   r	   r,   r>   r   )r8   processr   rO   rT   sr   r   r   class_hierarchy  s<   



r   c                 c   sB    t | }|D ]}| jD ]}||jv r||j| fV   n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   )r8   keyskeyr   r   r   r   iterate_attributes  s   

r   
self.proxyc              	      s$  |r|}ndu rd fddt |D }|D ]v}zt||}t|ds(W qt|d|}W n	 ty8   Y qw zt|}	t|	d }
t|	d dd }W n ty_   d	}
d
}Y nw dt  }|durm||ipni }t	|| z|j
|| _
W n	 ty   Y nw t |||  q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|vr|qS )__)
startswithendswithr>   r2   r   into_clsskipr   r   r     s    z0monkeypatch_proxied_specials.<locals>.<listcomp>r   r\   r   r   z(self, *args, **kw)z(*args, **kw)z?def %(method)s%(fn_args)s: return %(name)s.%(method)s%(d_args)s)r   re   r>   r   r   ra   r   r   localsexec_rf   setattr)r  Zfrom_clsr  onlyr[   Zfrom_instanceZdundersr   rS   rh   Zfn_argsZd_argspyrr   r   r  r   monkeypatch_proxied_specials  sJ   



r  c                 C   s   t | d| t |d|u S )z;Return True if the two methods are the same implementation.rw   )re   )Zmeth1Zmeth2r   r   r   methods_equivalent  s   r  c                 C   sj  |s|st dt|trt| |r| S t|pdd t|D }tt| }tj}t|tr2|}n|s;t }tj}nt|}||||rI| S t| t	sc|tju rUdpVd}t d| |d
|f G dd	 d	t}|rsd
|j |_t }	t| D ](\}
}|
|vrt d|
 t|st d|
|f t||
t| |	|
 qz||	|r|S t dd
||	  )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   C  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   AnonymousInterfaceZ  s    r  Z	Anonymousz%r: unknown in this interfacez%r=%r is not callablez,dictionary does not contain required keys %s)r   rx   ry   rH   r   operatorgegtintersectionrb   r5   r   r+   dictlike_iteritemsr   r   r	  staticmethodrL   )r   r8   methods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   r  r   r   r   r   r   u  s   zmemoized_property.__init__c                 C   s&   |d u r| S |  | |j| j< }|S r   )r  r   r+   )r   r   r8   resultr   r   r   __get__z  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   )r8   r   r[   r   r   r   r    s   zmemoized_property.resetr   )	r+   r,   r-   r.   r   r  r  classmethodr  r   r   r   r   r  r  s    
r  c                    rV   )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                    sB   | g|R i |  fdd}j |_ j|_|| jj <  S )Nc                         S r   r   ar   r  r   r   memo     z6memoized_instancemethod.<locals>.oneshot.<locals>.memo)r+   r.   r   )r   r   r   r$  rS   r#  r   oneshot  s   z(memoized_instancemethod.<locals>.oneshotr   )rS   r'  r   r&  r   memoized_instancemethod  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 d S r   )
attributesr   )r   r*  r   r   r   r     s   z*group_expirable_memoized_property.__init__c                 C   s"   |j }| jD ]}||d qdS )z.Expire all memoized properties for *instance*.N)r   r*  r   )r   instancestash	attributer   r   r   expire_instance  s   
z1group_expirable_memoized_property.expire_instancec                 C      | j |j t|S r   )r*  r?   r+   r  r   rS   r   r   r   r        z*group_expirable_memoized_property.__call__c                 C   r/  r   )r*  r?   r+   r(  r0  r   r   r   r     r1  z(group_expirable_memoized_property.methodNr   )r+   r,   r-   r.   r   r.  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 |r   )r   )r   r   r   r   r   _fallback_getattr     zMemoizedSlots._fallback_getattrc                    s    dr	ttd r td  }t| |S td r<td   fdd} j|_|S S )NZ	_memoizedz_memoized_attr_%sz_memoized_method_%sc                     s:   | i |  fdd}j |_ j|_t|  S )Nc                     r   r   r   r!  r#  r   r   r$    r%  z8MemoizedSlots.__getattr__.<locals>.oneshot.<locals>.memo)r+   r.   r	  )r   r   r$  rS   r   r   r#  r   r'    s   z*MemoizedSlots.__getattr__.<locals>.oneshot)r  r   r>   re   r	  r.   r3  )r   r   r$   r'  r   r5  r   __getattr__  s   

zMemoizedSlots.__getattr__N)r+   r,   r-   r.   r/   r3  r6  r   r   r   r   r2    s
    r2  c                    s    fdd}|S )Nc                    sn    d}td|dd t t |d g}t||d }t|| j|   r5t	|dr5|j
| j | S )Nrs   r   rt   __all__)rz   r   r   r5   globalsr  re   r	  r+   r>   r7  r?   )r   tokensr   
add_to_all
modulenamer   r   ro     s   
 z dependency_for.<locals>.decorater   )r<  r;  ro   r   r:  r   dependency_for  s   r=  c                 C   sD   t | tjr|   } | dv rdS | dv rdS td|  t| S )N)trueyesonyt1T)falsenooffr3   f0FzString is not true/false: %r)rx   r   string_typesstripr1   
ValueErrorr   r   r   r   r   asbool  s   rL  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   |  v r| S t | S r   )rL  r   textr   r   bool_or_value  s   z"bool_or_str.<locals>.bool_or_valuer   )rN  rO  r   rM  r   bool_or_str  s   rP  c                 C   s   | du r| S t | S )zCoerce to integer.N)int)r$   r   r   r   asint  s   rR  c                 C   sx   |du r| }|| v r6t |trt | | |s:| | dur8|tu r,|r,t| | ||< dS || | ||< dS dS dS 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)rx   ry   r   rL  )r   r   r#   Z
flexi_booldestr   r   r   coerce_kw_type  s   rT  c                    s4   t |}| fdd||D  ||i |S )zInstantiate cls using the __dict__ of obj as constructor arguments.

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

    c                 3   s(    | ]}| j v r| j | fV  qd S r   )r   )r2   kr   r   r   r4   ,  s    z#constructor_copy.<locals>.<genexpr>)r   r   
difference)r   r8   r   r   ri   r   r   r   constructor_copy$  s
   rW  c                     s&   t j td  fdd} | S )z%Return a threadsafe counter function.r   c                      s&      z	t W   S   w r   )acquirenextreleaser   counterlockr   r   _next9  s   zcounter.<locals>._next)r   	threadingLockrI   count)r^  r   r[  r   r\  2  s   

r\  c                 C   s   t | dr| jdurt| jtrtS | jS t| trtpt}|| tr%tS || tr,tS || tr3tS t | dr:tS t | drAtS t | drHtS |S )zGiven an instance or class, guess if it is or is acting as one of
    the basic collection types: list, set and dict.  If the __emulates__
    property is present, return that preferentially.
    __emulates__Nr?   rL   rH   )r>   rb  
issubclassrH   rx   ry   r   rb   )Zspecimenr   Zisar   r   r   duck_type_collectionC  s(   






rd  c                 C   sX   t | |r| S t |tr td|ddd |D t| f td||t| f )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   )r2   r"  r   r   r   r4   k  s    z"assert_arg_type.<locals>.<genexpr>z6Argument '%s' is expected to be of type '%s', got '%s')rx   r@   r   ArgumentErrorr5   ry   )r   Zargtyper[   r   r   r   assert_arg_typed  s   

rf  c                    s   t jrt drt  S nt dr  S t dr#t  S t dt dddu r7td  t drF fdd	}| S t d
rXtfdd 	 D S td  )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   )ri  )r   dictlikegetterr   r   iterator  s   z$dictlike_iteritems.<locals>.iteratorr   c                 3   s    | ]	}| |fV  qd S r   r   )r2   r   )rl  r   r   r4     r   z%dictlike_iteritems.<locals>.<genexpr>)
r   r	   r>   r   r   rg  iterre   r   r   )rk  rm  r   rj  r   r  t  s"   




r  c                       (   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|g|R i | |j| _d S r   )superrp  r   r.   )r   r  r   r   r   r   r   r     s   zclassproperty.__init__c                 C   s
   |  |S r   )r  )Zdescr   r8   r   r   r   r    r   zclassproperty.__get__)r+   r,   r-   r.   r   r  __classcell__r   r   rr  r   rp    s    
rp  c                   @   s   e Zd Zdd Zdd ZdS )hybridpropertyc                 C   r   r   r   r   r   r   r   r   r     r   zhybridproperty.__init__c                 C   s*   |d u r|  |}| j j|_|S |  |S r   )r   r.   )r   r+  ownerZclsvalr   r   r   r    s
   


zhybridproperty.__get__N)r+   r,   r-   r   r  r   r   r   r   rt    s    rt  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   r   r   r   ru  r   r   r   r     r   zhybridmethod.__init__c                 C   s&   |d u r| j ||jS | j ||S r   )r   r  r   )r   r+  rv  r   r   r   r    s   zhybridmethod.__get__N)r+   r,   r-   r.   r   r  r   r   r   r   rw    s    rw  c                   @   r   )_symbolNc                 C   s@   t |tjsJ |du rt|}tt|}||_|r||_|S )zConstruct a new named symbol.N)	rx   r   rI  hashrQ  __new__rx  r[   r.   )r   r[   r   	canonicalvr   r   r   rz    s   z_symbol.__new__c                 C   s   t | jdt| ffS )Nr   )ru   r[   rQ  r   r   r   r   
__reduce__  s   z_symbol.__reduce__c                 C   s   t | S r   r   r   r   r   r   __str__  r4  z_symbol.__str__c                 C   s
   d| j  S )Nz
symbol(%r))r[   r   r   r   r   __repr__  r   z_symbol.__repr__NN)r+   r,   r-   rz  r}  r~  r  r   r   r   r   rx    s
    
rx  ru   c                   @   s8   e Zd ZdZi Zej ZdddZ	e
	d	ddZdS )
ru   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   sR   | j   z| j|}|d u rt||| | j|< }|W tj   S tj   w r   )_lockrX  symbolsr   rx  ru   rZ  )r8   r[   r   r{  rQ   r   r   r   rz    s   
zsymbol.__new__Fc                 C   sf   |  D ]\}}||u r|  S |r||jkr|  S ||v r#|  S q|du r*dS td||f )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   r[   r   re  )r8   r   choicesr[   Zresolve_symbol_namesrQ   choicer   r   r   parse_user_argument  s   zsymbol.parse_user_argumentr  r*   )r+   r,   r-   r.   r  r   r_  r`  r  rz  r  r  r   r   r   r   ru     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| |i |W S  t y   tdt dd   Y dS w )zXexecutes the given function, catches all exceptions and converts to
    a warning.

    z%s('%s') ignoredr   r   N)r`   r"   r   r   )r   r   r   r   r   r   warn_exception.  s
   r     c                 C   s<   zt | |krd| d|  W S | W S  ty   |  Y S w )Nz%s...r   )r   r   )r$   Zlen_r   r   r   ellipses_string9  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)rq  r  rz  ry  _hash)r8   r$   numr   Zinterpolatedr   rr  r   r   rz  N  s   z_hash_limit_string.__new__c                 C   s   | j S r   )r  r   r   r   r   __hash__V  s   z_hash_limit_string.__hash__c                 C   s   t | t |kS r   )ry  )r   otherr   r   r   __eq__Y  s   z_hash_limit_string.__eq__)r+   r,   r-   r.   rz  r  r  rs  r   r   rr  r   r  C  s
    
r  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   r  N)r  r  r"   r   r  )r  r   r   r   r   warn_limitedg  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|| i |W S    rd|  d S )Nr   )r   insert)r   r   Z	strong_fnZonce_fnrS   onceretry_on_exceptionr   r   gow  s   zonly_once.<locals>.gor   )rS   r  r  r   r  r   	only_onceq  s   r  z%sqlalchemy/([a-z_]+/){0,2}[a-z_]+\.pyzunit(?:2|test2?/)c                 C   s   d}t | d }||kr"|| | r"|d7 }||kr"|| | s||kr<|| | r<|d8 }||kr<|| | s-| ||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_suffixr;   endr   r   r   chop_traceback  s   r  c                 C   s$   d|  }t   }t|| |d S )Nz&def set(obj, value):    obj.%s = valuerH   )r  copyrq   )attrnamerl   rr   r   r   r   
attrsetter  s   

r  c                       ro  )EnsureKWArgTypezYApply translation of functions to accept \**kw arguments if they
    don't already.

    c           
         sr   | j }|r-|D ]%}t||}|r,|| }t|}|js,| | ||< }	t| ||	 qtt	| 
||| d S r   )Zensure_kwargr6   matchr   ra   r   
_wrap_w_kwr	  rq  r  r   )
r8   ZclsnamerO   ZclsdictZfn_regr   r   rS   rh   wrappedrr  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  r4  z(EnsureKWArgType._wrap_w_kw.<locals>.wrapr   )r   rS   r  r   r&  r   r    s   
zEnsureKWArgType._wrap_w_kw)r+   r,   r-   r.   r   r  rs  r   r   rr  r   r    s    r  c                 C   sh   t |dr
t| |S | }|jj|_t |dr|j|_t |jdr+|jjr+|jj|_|S |jr2|j|_|S )zAugment functools.update_wrapper() to work with objects with
    a ``__call__()`` method.

    :param fn:
      object with __call__ method

    r+   r,   r.   )r>   r   r   r+   r,   r   r.   )wrapperrS   _fr   r   r   wrap_callable  s   




r  c                 C   s   d| vr	|  dS d}g g}d}t| }||k r`| | }|dkrC|dkr>||d k r>| |d  dkr>|d d |d7 }n|dN }n|dkrQ|dkrQ|g  n|d | |d7 }||k s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']

    "rs   r   r   rt   c                 S   s   g | ]}d  |qS ) )r5   )r2   r   r   r   r   r     s    z'quoted_token_parser.<locals>.<listcomp>)rz   r   r?   )r$   r   r  idxlvcharr   r   r   quoted_token_parser  s&   
$

r  c                    s   t    fdd}|S )Nc                    s:   | j d ur| j p	d}|rt|fdd D }|| _ | S )Nr  c                    s   i | ]}| qS r   r   )r2   paramrM  r   r   
<dictcomp>  s    z8add_parameter_text.<locals>.decorate.<locals>.<dictcomp>)r.   inject_param_text)rS   r   paramsrN  r   r   ro     s
   z$add_parameter_text.<locals>.decorate)r   r   )r  rN  ro   r   r  r   add_parameter_text	  s   
r  c                 C   sJ   |  dd}t|dkr| S |\}}|ds |d t| S t| S )N
r   r0   )rz   r   r  textwrapdedent)rN  Z
split_text	firstline	remainingr   r   r   _dedent_docstring  s   

r  c                 C   s   t | pd} | d}t|dkr|d t|d}|d r(|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   )rJ  )r2   r  liner   r   r   r   +  s    z)inject_docstring_text.<locals>.<listcomp>)
r  rz   r   r?   r  r  r  r   minr5   )doctextZ
injecttextposlinesZinjectlinesZblanksZ
inject_posr   r   r   r{   "  s   


r{   c           
      C   s2  |   }g }d }|r|d}|d u rKtd|}|rJ|d}||v rJdt|d d }|rDtd|d }	|	rDdt|	d }|||  }nB| drd|d || |d d }n)|	 sz|| || |d d }n|
d	r|| ||d q|| |s
d|S )
Nr   z(\s+):param (?:\\\*\*?)?(.+?):r   r0   r   z(\s+)\Sz:param r  z::)
splitlinesr   r6   r  r   r   lstripr  r?   rstripr  r5   )
r  Zinject_paramsZdoclinesr  Z	to_injectr  r   r  indentm2r   r   r   r  4  sH   











&r  c                 C   s~   t | dkrdS t | dk}|r| dd n| dd | dd  } dd | D }|r0d|S d	d|dd |d f 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   rW   rt   c                 S   s,   g | ]}t |d krd|dd   n|qS )   z%s..N)r   )r2   r[   r   r   r   r   i  s   , z$repr_tuple_names.<locals>.<listcomp>r   z%s, ..., %s)r   r5   )ri   flagresr   r   r   repr_tuple_namesb  s   (
r  r   )FF)T)r   Nr   )NNr   N)NNNr*   )TN)r  )Xr.   	functoolsr   r   r]   rI   r  r6   r   r  r   r  r  r   r   r   r   r   r   r9   rB   rR   rU   rp   rd   r   r   r   r   r   r   rc   r   r   r   r   r   r   r   r  r  r  r  r(  r)  r2  r=  rL  rP  rR  rT  rW  r\  rd  rf  r  propertyrp  rt  rw  rQ  rx  r+   ru   r  r  r  r  	text_typer  r"   r  r  compileZ_SQLA_REZ_UNITTEST_REr  ry   NoneTyper  r  r  r  r  r  r{   r  r  r   r   r   r   <module>   s   1	
S*
+

6
S
H3
?
V
(

!G




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