
    .Ph                        d 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m	Z	 ddlm
Z
 	 ddlmZ  ed	          Zn# e$ r  e            ZY nw xY wdddd
i i ed d d d efdZd+dZd Zd,dZd-dZd Z G d dej                  Z G d dej                  ZeZd.dZd/dZd/dZd0dZd/d Zd! Z G d" d#          Z  G d$ d%e!          Z" G d& d'e!          Z#d(e$fd)Z%d* Z&dS )1zPython's built-in :mod:`functools` module builds several useful
utilities on top of Python's first-class function
support. ``funcutils`` generally stays in the same vein, adding to and
correcting Python's standard metaprogramming facilities.
    N)formatannotation)FunctionType
MethodType)total_ordering   )make_sentinel
NO_DEFAULT)var_name c                     d| z   S )N*r   names    Q/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/boltons/funcutils.py<lambda>r   <   s
    3:     c                     d| z   S )Nz**r   r   s    r   r   r   =   s
     r   c                 &    dt          |           z   S N=)reprvalues    r   r   r   >   s    #U"3 r   c                     d| z   S )Nz -> r   )texts    r   r   r   ?   s
    6D= r   c                    fd}g }|rt          |           t          |          z
  }t          |           D ]D\  }} ||          }|r||k    r| |
|||z
                     z   }|                    |           E|(|                     | ||                               n|r|                    d           |r?|D ]<} ||          }|r||v r| |
||                   z  }|                    |           =|'|                     |	 ||                               dd                    |          z   dz   }dv r| | d                             z  }|S )a  Copy formatargspec from python 3.7 standard library.
    Python 3 has deprecated formatargspec and requested that Signature
    be used instead, however this requires a full reimplementation
    of formatargspec() in terms of creating Parameter objects and such.
    Instead of introducing all the object-creation overhead and having
    to reinvent from scratch, just copy their compatibility routine.
    c                 T     |           }| v r|d |                    z   z  }|S )Nz: r   )argresultannotationsr   	formatargs     r   formatargandannotationz5inspect_formatargspec.<locals>.formatargandannotationI   s@    3+d--k#.>????Fr   Nr   (, )return)len	enumerateappendjoin)argsvarargsvarkwdefaults
kwonlyargskwonlydefaultsr    r!   formatvarargsformatvarkwformatvalueformatreturnsr   r"   specsfirstdefaultir   spec	kwonlyargr   s         ``    `        r   inspect_formatargspecr:   8   s   "      
 E 14yy3x==0D//  3%%c** 	B\))++hq</?&@AAADT]]#9#9'#B#BCCDDDD 	LL # 	 	I)))44D ?)~"="=N9$=>>>LL[[!7!7!>!>??@@@499U###c)F;-- 0 0X1F G GHHHMr   c                    t          | t                    rt          j        |          } i i }}t	          |           D ]}|r ||          r	 t          | |          }n# t          $ r Y .w xY w	 |j        }n# t          $ r Y Gw xY w|| j	        k    rWt          |t                    r|||<   rt          |          r|||<   ||fS )zReturns two maps of (*types*, *funcs*) from *mod*, optionally
    ignoring based on the :class:`bool` return value of the *ignore*
    callable. *mod* can be a string name of a module in
    :data:`sys.modules` or the module instance itself.
    )
isinstancestrsysmodulesdirgetattr	Exception
__module__AttributeError__name__typecallable)modignoretypesfuncs	attr_nameattrattr_mod_names          r   get_module_callablesrO   i   s    #s k#r5EXX $ $	 	ffY'' 		3	**DD 	 	 	H		 OMM 	 	 	H	CL((dD!! 	$#E)d^^ 	$#E)%<s$   A
A*)A*.A66
BBc                 ^    t           j                            d | j        D                       S )a#  Takes a type and returns an iterator over all class variables
    throughout the type hierarchy (respecting the MRO).

    >>> sorted(set([k for k, v in mro_items(int) if not k.startswith('__') and 'bytes' not in k and not callable(v)]))
    ['denominator', 'imag', 'numerator', 'real']
    c              3   H   K   | ]}|j                                         V  d S N)__dict__items).0cts     r   	<genexpr>zmro_items.<locals>.<genexpr>   sL       )E )E-/ *,):):)<)< )E )E )E )E )E )Er   )	itertoolschainfrom_iterable__mro__)type_objs    r   	mro_itemsr]      sE     ?(( )E )E3;3C)E )E )E E E Er   Fc                 |    i }t          |           D ])}	 t          | |          ||<   # t          $ r |r Y &w xY w|S )zReturn a dictionary of attribute names to values for a given
    object. Unlike ``obj.__dict__``, this function returns all
    attributes on the object, including ones on parent classes.
    )r@   rA   rB   )obj	raise_excretks       r   dir_dictrc      sm     CXX  	S!__CFF 	 	 	  	 Js   )99Tc                    t          | j        | j        | j        t	          | dd          t	          | dd                    }t          | d          r| j        |_        |r|j                            | j                   |S )a  Returns a shallow copy of the function, including code object,
    globals, closure, etc.

    >>> func = lambda: func
    >>> func() is func
    True
    >>> func_copy = copy_function(func)
    >>> func_copy() is func
    True
    >>> func_copy is not func
    True

    Args:
        orig (function): The function to be copied. Must be a
            function, not just any method or callable.
        copy_dict (bool): Also copy any attributes set on the function
            instance. Defaults to ``True``.
    __defaults__N__closure__)r   argdefsclosure__kwdefaults__)	r   __code____globals__rE   rA   hasattrri   rS   update)orig	copy_dictra   s      r   copy_functionrp      s    & t}' M&t^TBB&t]DAA	C C CC
 t%&& 1!0 +DM***Jr   c                     d }d }d }t          | d          s|| _        t          | d          s|| _        t          | d          s|| _        | S )aj  Class decorator, similar to :func:`functools.total_ordering`,
    except it is used to define `partial orderings`_ (i.e., it is
    possible that *x* is neither greater than, equal to, or less than
    *y*). It assumes the presence of the ``__le__()`` and ``__ge__()``
    method, but nothing else. It will not override any existing
    additional comparison methods.

    .. _partial orderings: https://en.wikipedia.org/wiki/Partially_ordered_set

    >>> @partial_ordering
    ... class MySet(set):
    ...     def __le__(self, other):
    ...         return self.issubset(other)
    ...     def __ge__(self, other):
    ...         return self.issuperset(other)
    ...
    >>> a = MySet([1,2,3])
    >>> b = MySet([1,2])
    >>> c = MySet([1,2,4])
    >>> b < a
    True
    >>> b > a
    False
    >>> b < c
    True
    >>> a < c
    False
    >>> c > a
    False
    c                     | |k    o| |k     S rR   r   selfothers     r   __lt__z partial_ordering.<locals>.__lt__       DEM$G$%-6GGr   c                     | |k    o| |k     S rR   r   rs   s     r   __gt__z partial_ordering.<locals>.__gt__   rw   r   c                     | |k    o| |k    S rR   r   rs   s     r   __eq__z partial_ordering.<locals>.__eq__   s    DEM$CdemCr   rv   ry   r{   )rl   rv   ry   r{   )clsrv   ry   r{   s       r   partial_orderingr}      sg    > HGGGGGCCC3!!63:3!!63:3!!63:Jr   c                   D    e Zd ZdZed             Zed             Zd ZdS )InstancePartiala  :class:`functools.partial` is a huge convenience for anyone
    working with Python's great first-class functions. It allows
    developers to curry arguments and incrementally create simpler
    callables for a variety of use cases.

    Unfortunately there's one big gap in its usefulness:
    methods. Partials just don't get bound as methods and
    automatically handed a reference to ``self``. The
    ``InstancePartial`` type remedies this by inheriting from
    :class:`functools.partial` and implementing the necessary
    descriptor protocol. There are no other differences in
    implementation or usage. :class:`CachedInstancePartial`, below,
    has the same ability, but is slightly more efficient.

    c                     | j         S rR   __partialmethod__rt   s    r   _partialmethodzInstancePartial._partialmethod        %%r   c                 J    t          j        | j        g| j        R i | j        S rR   	functoolspartialmethodfuncr+   keywordsr   s    r   r   z!InstancePartial.__partialmethod__   )    &tyN49NNNNNNr   c                 "    t          | |          S rR   )r   )rt   r_   obj_types      r   __get__zInstancePartial.__get__  s    $$$$r   N)rE   rC   __qualname____doc__propertyr   r   r   r   r   r   r   r      sf          & & X& O O XO% % % % %r   r   c                   J    e Zd ZdZed             Zed             Zd Zd ZdS )CachedInstancePartiala  The ``CachedInstancePartial`` is virtually the same as
    :class:`InstancePartial`, adding support for method-usage to
    :class:`functools.partial`, except that upon first access, it
    caches the bound method on the associated object, speeding it up
    for future accesses, and bringing the method call overhead to
    about the same as non-``partial`` methods.

    See the :class:`InstancePartial` docstring for more details.
    c                     | j         S rR   r   r   s    r   r   z$CachedInstancePartial._partialmethod  r   r   c                 J    t          j        | j        g| j        R i | j        S rR   r   r   s    r   r   z'CachedInstancePartial.__partialmethod__  r   r   c                     || _         d S rR   )rE   )rt   r   r   s      r   __set_name__z"CachedInstancePartial.__set_name__  s    r   c                    t          | dd           | _        | j        j        | _        | j        j        | _        | j        }|t          | |          S 	 |j        |         S # t          $ r t          | |          x|j        |<   }|cY S w xY w)NrE   )rA   rE   r   r   rC   r   rS   KeyError)rt   r_   r   r   ra   s        r   r   zCachedInstancePartial.__get__  s      j$77y().};dC(((	 <%% 	 	 	'1$'<'<<CLJJJ	s   A   &B	B	N)	rE   rC   r   r   r   r   r   r   r   r   r   r   r   r   	  su          & & X& O O XO      r   r    c                    |                     dt                    |r7t          dd                    |                                          z            pi d                    fd|D                       }t          t                    rfdt                    D             }n}d                    fd|D                       }|}|r|r|dz  }||z  }|  d| dS )	an  Given a name, positional arguments, and keyword arguments, format
    a basic Python-style function call.

    >>> print(format_invocation('func', args=(1, 2), kwargs={'c': 3}))
    func(1, 2, c=3)
    >>> print(format_invocation('a_func', args=(1,)))
    a_func(1)
    >>> print(format_invocation('kw_func', kwargs=[('a', 1), ('b', 2)]))
    kw_func(a=1, b=2)

    r   zunexpected keyword args: %rr$   c                 &    g | ]} |          S r   r   )rU   a_reprs     r   
<listcomp>z%format_invocation.<locals>.<listcomp>F  s!    ///Qa///r   c                 $    g | ]}||         fS r   r   )rU   rb   kwargss     r   r   z%format_invocation.<locals>.<listcomp>H  s!    >>>!6!9~>>>r   c                 6    g | ]\  }}| d  |           S r   r   )rU   rb   vr   s      r   r   z%format_invocation.<locals>.<listcomp>K  s3    CCCtq!A**a**CCCr   r#   r%   )popr   	TypeErrorr*   keysr<   dictsorted)	r   r+   r   kwa_textkwarg_itemskw_textall_args_textr   s	     `     @r   format_invocationr   6  s    FF64  E	 N5		"''))8L8LLMMM\rFYY////$///00F&$ >>>>vf~~>>>iiCCCC{CCCDDGM  WM%%]%%%%r   c                 r    t                     j        }|pg }pg t                      g }}|z   D ]1}||v r|                    |           |                    |           2d t                    sJ  fd|D             }	 fd|D             }
fd|
D             }
t          ||	|
          S )a  Render an expression-style repr of an object, based on attribute
    names, which are assumed to line up with arguments to an initializer.

    >>> class Flag(object):
    ...    def __init__(self, length, width, depth=None):
    ...        self.length = length
    ...        self.width = width
    ...        self.depth = depth
    ...

    That's our Flag object, here are some example reprs for it:

    >>> flag = Flag(5, 10)
    >>> print(format_exp_repr(flag, ['length', 'width'], [], ['depth']))
    Flag(5, 10)
    >>> flag2 = Flag(5, 15, 2)
    >>> print(format_exp_repr(flag2, ['length'], ['width', 'depth']))
    Flag(5, width=15, depth=2)

    By picking the pos_names, req_names, opt_names, and opt_key, you
    can fine-tune how you want the repr to look.

    Args:
       obj (object): The object whose type name will be used and
          attributes will be checked
       pos_names (list): Required list of attribute names which will be
          rendered as positional arguments in the output repr.
       req_names (list): List of attribute names which will always
          appear in the keyword arguments in the output repr. Defaults to None.
       opt_names (list): List of attribute names which may appear in
          the keyword arguments in the output repr, provided they pass
          the *opt_key* check. Defaults to None.
       opt_key (callable): A function or callable which checks whether
          an opt_name should be in the repr. Defaults to a
          ``None``-check.

    Nc                 
    | d u S rR   r   r   s    r   r   z!format_exp_repr.<locals>.<lambda>  
    AI r   c                 2    g | ]}t          |d           S rR   rA   rU   r   r_   s     r   r   z#format_exp_repr.<locals>.<listcomp>  s%    ;;;GCt$$;;;r   c                 6    g | ]}|t          |d           fS rR   r   r   s     r   r   z#format_exp_repr.<locals>.<listcomp>  s*    GGGTwsD$//0GGGr   c                 <    g | ]\  }}|v r |          ||fS r   r   rU   r   valopt_key	opt_namess      r   r   z#format_exp_repr.<locals>.<listcomp>  sB     = = =	c	))ggcll) s)))r   )rF   rE   setaddr)   rG   r   )r_   	pos_names	req_namesr   r   cn
uniq_names	all_namesr   r+   kw_itemss   `  ``      r   format_exp_reprr   U  s   L 
c	BRIRIEE2	JI%  :t%%G;;;;;;;DGGGGYGGGH= = = = =X = = =H Rx000r   c                      j         j        }|pg }pg t                      g }}|z   D ]1}||v r|                    |           |                    |           2d t                    sJ  fd|D             }fd|D             }	|	sdt                     z  g}	d                    |d                    |	                    }
|
S )a  Format a non-expression-style repr

    Some object reprs look like object instantiation, e.g., App(r=[], mw=[]).

    This makes sense for smaller, lower-level objects whose state
    roundtrips. But a lot of objects contain values that don't
    roundtrip, like types and functions.

    For those objects, there is the non-expression style repr, which
    mimic's Python's default style to make a repr like so:

    >>> class Flag(object):
    ...    def __init__(self, length, width, depth=None):
    ...        self.length = length
    ...        self.width = width
    ...        self.depth = depth
    ...
    >>> flag = Flag(5, 10)
    >>> print(format_nonexp_repr(flag, ['length', 'width'], ['depth']))
    <Flag length=5 width=10>

    If no attributes are specified or set, utilizes the id, not unlike Python's
    built-in behavior.

    >>> print(format_nonexp_repr(flag))
    <Flag id=...>
    Nc                 
    | d u S rR   r   r   s    r   r   z$format_nonexp_repr.<locals>.<lambda>  r   r   c                 6    g | ]}|t          |d           fS rR   r   r   s     r   r   z&format_nonexp_repr.<locals>.<listcomp>  s*    DDD$dGCt,,-DDDr   c                 B    g | ]\  }}|v r |          | d |S r   r   r   s      r   r   z&format_nonexp_repr.<locals>.<listcomp>  sL     ; ; ;ID#i''GGCLL' '''r   zid=%sz<{} {}> )		__class__rE   r   r   r)   rG   idformatr*   )r_   r   r   r   r   r   r   r   rT   labelsra   s   ` ``       r   format_nonexp_reprr     s"   8 
	BRIRIEE2	JI%  :t%%GDDDD)DDDE; ; ; ; ; ; ; ;F %BsGG#$


2sxx//
0
0CJr   c                 0    t          t          f| d||d|S )aV  Decorator factory to apply update_wrapper() to a wrapper function.

    Modeled after built-in :func:`functools.wraps`. Returns a decorator
    that invokes update_wrapper() with the decorated function as the wrapper
    argument and the arguments to wraps() as the remaining arguments.
    Default arguments are as for update_wrapper(). This is a convenience
    function to simplify applying partial() to update_wrapper().

    Same example as in update_wrapper's doc but with wraps:

        >>> from boltons.funcutils import wraps
        >>>
        >>> def print_return(func):
        ...     @wraps(func)
        ...     def wrapper(*args, **kwargs):
        ...         ret = func(*args, **kwargs)
        ...         print(ret)
        ...         return ret
        ...     return wrapper
        ...
        >>> @print_return
        ... def example():
        ...     '''docstring'''
        ...     return 'example return value'
        >>>
        >>> val = example()
        example return value
        >>> example.__name__
        'example'
        >>> example.__doc__
        'docstring'
    N)r   
build_frominjectedexpected)partialupdate_wrapper)r   r   r   r   s       r   wrapsr     s4    B > ?$x? ?;=? ? ?r   c                    |g }n(t          |t                    r|g}nt          |          }t          |          }t          |t          t
          f          r!t          dt          |dd                    |                    dd          }|                    dd          }|                    dd          }	|r$t          d	|	                                z            t          | t          j                  r|| j        u r|p| }t                              |p|          }
|D ]2}	 |
                    |           # t           $ r |r	|
j        Y . w xY w|D ]\  }}|
                    ||           |
j        rd
|
                                z  |
_        nd|
                                z  |
_        t-          | |          }|
                    ||          }|	rt1          |d          r	|j        d= n	|	s||_        |S )a
  Modeled after the built-in :func:`functools.update_wrapper`,
    this function is used to make your wrapper function reflect the
    wrapped function's:

      * Name
      * Documentation
      * Module
      * Signature

    The built-in :func:`functools.update_wrapper` copies the first three, but
    does not copy the signature. This version of ``update_wrapper`` can copy
    the inner function's signature exactly, allowing seamless usage
    and :mod:`introspection <inspect>`. Usage is identical to the
    built-in version::

        >>> from boltons.funcutils import update_wrapper
        >>>
        >>> def print_return(func):
        ...     def wrapper(*args, **kwargs):
        ...         ret = func(*args, **kwargs)
        ...         print(ret)
        ...         return ret
        ...     return update_wrapper(wrapper, func)
        ...
        >>> @print_return
        ... def example():
        ...     '''docstring'''
        ...     return 'example return value'
        >>>
        >>> val = example()
        example return value
        >>> example.__name__
        'example'
        >>> example.__doc__
        'docstring'

    In addition, the boltons version of update_wrapper supports
    modifying the outer signature. By passing a list of
    *injected* argument names, those arguments will be removed from
    the outer wrapper's signature, allowing your decorator to provide
    arguments that aren't passed in.

    Args:

        wrapper (function) : The callable to which the attributes of
            *func* are to be copied.
        func (function): The callable whose attributes are to be copied.
        injected (list): An optional list of argument names which
            should not appear in the new wrapper's signature.
        expected (list): An optional list of argument names (or (name,
            default) pairs) representing new arguments introduced by
            the wrapper (the opposite of *injected*). See
            :meth:`FunctionBuilder.add_arg()` for more details.
        build_from (function): The callable from which the new wrapper
            is built. Defaults to *func*, unless *wrapper* is partial object
            built from *func*, in which case it defaults to *wrapper*.
            Useful in some specific cases where *wrapper* and *func* have the
            same arguments but differ on which are keyword-only and positional-only.
        update_dict (bool): Whether to copy other, non-standard
            attributes of *func* over to the wrapper. Defaults to True.
        inject_to_varkw (bool): Ignore missing arguments when a
            ``**kwargs``-type catch-all is present. Defaults to True.
        hide_wrapped (bool): Remove reference to the wrapped function(s)
            in the updated function.

    In opposition to the built-in :func:`functools.update_wrapper` bolton's
    version returns a copy of the function and does not modify anything in place.
    For more in-depth wrapping of functions, see the
    :class:`FunctionBuilder` type, on which update_wrapper was built.
    Nz~wraps does not support wrapping classmethods and staticmethods, change the order of wrapping to wrap the underlying function: __func__update_dictTinject_to_varkwhide_wrappedFunexpected kwargs: %rzreturn await _call(%s)zreturn _call(%s))_call_func)	with_dict__wrapped__)r<   r=   list_parse_wraps_expectedclassmethodstaticmethodr   rA   r   r   r   r   r   FunctionBuilder	from_func
remove_argMissingArgumentr-   add_argis_asyncget_invocation_strbodyr   get_funcrl   rS   r   )wrapperr   r   r   r   r   expected_itemsr   r   r   fbr   defaultexecdictfully_wrappeds                  r   r   r     sS   N 	Hc	"	" ":>>*844N$l344 >i #4T:::= > > 	>
 &&--Kff.55O66.%00L	 =/"''));<<<'9,-- +$',2F2F*7
		"	":#5	6	6B  	MM# 	 	 	 28#7	
 ' ! !W


3    	{ ?*R-B-B-D-DD$r'<'<'>'>>'...HKKKK@@M )}== )"=11 )$(!s   *E  EEc                    | g } nt          | t                    r
| t          fg} g }	 t          |           }n(# t          $ r}t          d| d|d          d }~ww xY w|D ]}t          |t                    r!	 | |         }nB# t          $ r
 t          }Y n/w xY w	 |\  }}n$# t          t
          f$ r t          d          w xY wt          |t                    st          d|          |                    ||f           |S )Nz"expected" takes string name, sequence of string names, iterable of (name, default) pairs, or a mapping of  {name: default}, not z (got: r%   z"expected" takes string name, sequence of string names, iterable of (name, default) pairs, or a mapping of  {name: default}, not %rz-all "expected" argnames must be strings, not )r<   r=   r	   iterr   
ValueErrorr)   )r   r   expected_itereargnamer   s         r   r   r   l  s   
 	Hc	"	" ,z*+NOX O O OjAI111N O O 	OO ! 2 2gs## 	=%"7+ % % %$%=#* z* = = =  "< = = == '3'' 	ZXWXXYYYw01111s3   8 
AAA:BBBB!!!Cc            	       .   e Zd ZdZed d d eeedZed             Ze	ed d d	 d
 ed dZ
e
                    e            ej                    Zd ZddZ ej        dej                  Zd Zed             ZddZd ZddZedfdZd Zd ZdS )r   a  The FunctionBuilder type provides an interface for programmatically
    creating new functions, either based on existing functions or from
    scratch.

    Values are passed in at construction or set as attributes on the
    instance. For creating a new function based of an existing one,
    see the :meth:`~FunctionBuilder.from_func` classmethod. At any
    point, :meth:`~FunctionBuilder.get_func` can be called to get a
    newly compiled function, based on the values configured.

    >>> fb = FunctionBuilder('return_five', doc='returns the integer 5',
    ...                      body='return 5')
    >>> f = fb.get_func()
    >>> f()
    5
    >>> fb.varkw = 'kw'
    >>> f_kw = fb.get_func()
    >>> f_kw(ignored_arg='ignored_val')
    5

    Note that function signatures themselves changed quite a bit in
    Python 3, so several arguments are only applicable to
    FunctionBuilder in Python 3. Except for *name*, all arguments to
    the constructor are keyword arguments.

    Args:
        name (str): Name of the function.
        doc (str): `Docstring`_ for the function, defaults to empty.
        module (str): Name of the module from which this function was
            imported. Defaults to None.
        body (str): String version of the code representing the body
            of the function. Defaults to ``'pass'``, which will result
            in a function which does nothing and returns ``None``.
        args (list): List of argument names, defaults to empty list,
            denoting no arguments.
        varargs (str): Name of the catch-all variable for positional
            arguments. E.g., "args" if the resultant function is to have
            ``*args`` in the signature. Defaults to None.
        varkw (str): Name of the catch-all variable for keyword
            arguments. E.g., "kwargs" if the resultant function is to have
            ``**kwargs`` in the signature. Defaults to None.
        defaults (tuple): A tuple containing default argument values for
            those arguments that have defaults.
        kwonlyargs (list): Argument names which are only valid as
            keyword arguments. **Python 3 only.**
        kwonlydefaults (dict): A mapping, same as normal *defaults*,
            but only for the *kwonlyargs*. **Python 3 only.**
        annotations (dict): Mapping of type hints and so
            forth. **Python 3 only.**
        filename (str): The filename that will appear in
            tracebacks. Defaults to "boltons.funcutils.FunctionBuilder".
        indent (int): Number of spaces with which to indent the
            function *body*. Values less than 1 will result in an error.
        dict (dict): Any other attributes which should be added to the
            functions compiled with this FunctionBuilder.

    All of these arguments are also made available as attributes which
    can be mutated as necessary.

    .. _Docstring: https://en.wikipedia.org/wiki/Docstring#Python

    c                      d S rR   r   r   r   r   r   zFunctionBuilder.<lambda>  s    D r   c                      d S rR   r   r   r   r   r   zFunctionBuilder.<lambda>  s    $ r   c                      d S rR   r   r   r   r   r   zFunctionBuilder.<lambda>  s    T r   )r+   r,   r-   r.   r/   r0   r    c                 R    t          j        |          fd| j        D             S )Nc                 2    i | ]}|t          |          S r   r   )rU   rM   argspecs     r   
<dictcomp>z4FunctionBuilder._argspec_to_dict.<locals>.<dictcomp>  s5     7 7 7 ggt,, 7 7 7r   )inspectgetfullargspec_argspec_defaults)r|   fr  s     @r   _argspec_to_dictz FunctionBuilder._argspec_to_dict  sA    (++7 7 7 7 # 57 7 7 	7r   c                      dS )NFr   r   r   r   r   zFunctionBuilder.<lambda>  s    U r   c                      d S rR   r   r   r   r   r   zFunctionBuilder.<lambda>  s    4 r   c                      dS )Npassr   r   r   r   r   zFunctionBuilder.<lambda>  s     r   c                      dS )N   r   r   r   r   r   zFunctionBuilder.<lambda>  s    1 r   c                      dS )Nz!boltons.funcutils.FunctionBuilderr   r   r   r   r   zFunctionBuilder.<lambda>  s    %H r   )docr   r   moduler   indentr    filenamec                    || _         | j                                        D ]8\  }}|                    |d           }|
 |            }t	          | ||           9|r$t          d|                                z            d S )Nr   )r   	_defaultsrT   r   setattrr   r   )rt   r   r   r   default_factoryr   s         r   __init__zFunctionBuilder.__init__  s    	"&."6"6"8"8 	" 	"A&&D//C{%o''D!S!!!! 	A3bggii?@@@r   Tc           	      l    |r| j         }ni }t          | j        | j        | j        g | j        i |          S )zReturn function signature as a string.

        with_annotations is ignored on Python 2.  On Python 3 signature
        will omit annotations if it is set to False.
        )r    r:   r+   r,   r-   r/   )rt   with_annotationsr    s      r   get_sig_strzFunctionBuilder.get_sig_str  sI      	*KKK$TY%)\%)Z%'%)_%'%02 2 	2r   z
    \*     # a star
    \s*    # followed by any amount of whitespace
    ,      # followed by a comma
    \s*    # followed by any amount of whitespace
    c           	          d }i }| j         rd | j         D             }d |d<   t          | j        | j        | j        g ||i fi |}| j                            d|          }|dd         S )Nc                     i | ]}||S r   r   )rU   r   s     r   r  z6FunctionBuilder.get_invocation_str.<locals>.<dictcomp>  s*     < < <$'   < < <r   c                     d| z   S r   r   r   s    r   r   z4FunctionBuilder.get_invocation_str.<locals>.<lambda>  s
    cEk r   r3   r   r   )r/   r:   r+   r,   r-   _KWONLY_MARKERsub)rt   kwonly_pairs
formatterssigs       r   r   z"FunctionBuilder.get_invocation_str  s    
? 	B< <+/?< < <L(A(AJ}%#DI$(L$(J$&$0$0$&2 2 '12 2 !%%b#..1R4yr   c           	      :   t          |          st          d|          t          |t          j                  rY|j        j        |j        j        t          |j        dd          t          |j        di           t          |j        di           d}n?|j        |j        t          |dd          t          |di           t          |di           d}|	                    | 
                    |                     t          j        |          rd|d<    | d	i |S )
zCreate a new FunctionBuilder instance based on an existing
        function. The original function will not be stored or
        modified.
        zexpected callable object, not rC   N__annotations__rS   )r   r  r  r    r   Tr   r   )rG   r   r<   r   r   r   rE   r   rA   rm   r  r  iscoroutinefunction)r|   r   r   s      r   r   zFunctionBuilder.from_func*  s*    ~~ 	GETEEFFFdI-.. 	="i0!Y. '	< F F%,TY8I2%N%N%diR@@	B BFF #m!\ 'lD A A%,T3Db%I%I%dJ;;	= =F 	c**400111&t,, 	&!%F:s}}V}}r   Nc                 l   |pi }| j         p| j        }d}|dz  }| j        rd|z   }t          | j         d| j        z            }| j                            dd                              dd          }|                    ||                     d	          | j	        |
          }| 
                    ||           ||         }| j        |_        | j	        |_        | j        |_        | j        |_        | j        |_        |r|j                            | j                   | j        |_        |r||_        |S )a  Compile and return a new function based on the current values of
        the FunctionBuilder.

        Args:
            execdict (dict): The dictionary representing the scope in
                which the compilation should take place. Defaults to an empty
                dict.
            add_source (bool): Whether to add the source used to a
                special ``__source__`` attribute on the resulting
                function. Defaults to True.
            with_dict (bool): Add any custom attributes, if
                applicable. Defaults to True.

        To see an example of usage, see the implementation of
        :func:`~boltons.funcutils.wraps`.
        zdef {name}{sig_str}:z
{body}zasync r   <_>F)r  )r   sig_strr  r   )r   _default_bodyr   _indentr  r   replacer   r  r  _compilerE   r   r.   re   r0   ri   r    r%  rS   rm   r   r  rC   
__source__)	rt   r   
add_sourcer   r   tmplr   srcr   s	            r   r   zFunctionBuilder.get_funcI  s?   " >ry.D.%
= 	#d?Dty#"344y  c**223<<kktT-=-=u-=-U-U"hT  3 3c8$$$~	x M"1#/ 	,M  ++++  	"!DOr   c                    t          t          t          t          t          | j                  t          | j        pg                                                   }t          | dd          }|r|                    |           |S )z`Get a dictionary of function arguments with defaults and the
        respective values.
        r0   N)r   reversedr   zipr+   r.   rA   rm   )rt   ra   r0   s      r   get_defaults_dictz!FunctionBuilder.get_defaults_dict{  s     8DXdi%8%8%-dm.Ar%B%B"D "D E E F F G G '7>> 	'JJ~&&&
r   Fc                     t          | j                  t          t          | dd                    z   }|r/|                                 t          fd|D                       }|S )Nr/   r   c                     g | ]}|v|	S r   r   )rU   andefaults_dicts     r   r   z1FunctionBuilder.get_arg_names.<locals>.<listcomp>  s#    QQQb=9P9Pr9P9P9Pr   )tupler+   rA   r7  )rt   only_required	arg_namesr;  s      @r   get_arg_nameszFunctionBuilder.get_arg_names  sm    $)$$uWT<-L-L'M'MM	 	S 2244MQQQQIQQQRRIr   c                 j   || j         v rt          d|d| j         d          || j        v rt          d|d| j         d          |s9| j                             |           |t
          ur| j        pd|fz   | _        dS dS | j                            |           |t
          ur|| j        |<   dS dS )zAdd an argument with optional *default* (defaults to
        ``funcutils.NO_DEFAULT``). Pass *kwonly=True* to add a
        keyword-only argument
        arg z already in func z	 arg listz kwonly arg listr   N)r+   ExistingArgumentr   r/   r)   r	   r.   r0   )rt   arg_namer   kwonlys       r   r   zFunctionBuilder.add_arg  s    
 ty  "#[(#[#[ty#[#[#[\\\t&&"#b(#b#bty#b#b#bccc 	8IX&&&j((!%!4"
 B )( O""8,,,j((07#H--- )(r   c           
         | j         }|                                 	 |                    |                               |d           t	          fd|D                       | _        n# t          $ ru 	 | j                            |           | j                            |d           n;# t          t          f$ r' t          d|d| j        d|          }||_        |w xY wY nw xY wdS )a8  Remove an argument from this FunctionBuilder's argument list. The
        resulting function will have one less argument per call to
        this function.

        Args:
            arg_name (str): The name of the argument to remove.

        Raises a :exc:`ValueError` if the argument is not present.

        Nc                 (    g | ]}|v |         S r   r   )rU   r   d_dicts     r   r   z.FunctionBuilder.remove_arg.<locals>.<listcomp>  s"    "J"J"Ja6kk6!9kkkr   rA  z not found in z argument list: )r+   r7  remover   r<  r.   r   r/   r0   rD   r   r   rC  )rt   rC  r+   excrG  s       @r   r   zFunctionBuilder.remove_arg  s0    y''))	LKK!!! JJx&&&!"J"J"J"Jd"J"J"JKKDMM  
	8 
	8 
	8	8&&x000 #''$7777 #J/   %o/7xxDD'J K K'	 87
	8 	s)   A* *
C)5B+C)+8C##C)(C)c                     d| j         t          | j                  fz  }	 t          ||d          }t	          ||           n# t
          $ r  w xY w|S )Nz<%s-%d>single)r  next_compile_countcompileexecrB   )rt   r3  r   r  codes        r   r/  zFunctionBuilder._compile  sn    }d4+>&?&?AB	3(33Dx     	 	 		s   !A AT)NTTF)rE   rC   r   r   r   r   r  r   r  r=   r  rm   rX   countrM  r  r  rerN  VERBOSEr  r   r   r   r7  r?  r	   r   r   r/  r   r   r   r   r     s       = =~ "&$0L".,%1\'++/(,. . 7 7 [7
 *]'<'$9 $HHJ JI &'''$Y_&&N
 
 
2 2 2 2&  RZ !
 
 N  &   [<0 0 0 0d	 	 	    )35 8 8 8 8$  >	 	 	 	 	r   r   c                       e Zd ZdS )r   NrE   rC   r   r   r   r   r   r             Dr   r   c                       e Zd ZdS )rB  NrW  r   r   r   rB  rB    rX  r   rB  
c                 r    fd|                                  D             }|                    |          S )z based on boltons.strutils.indentc                 4    g | ]} |          r|z   n|S r   r   )rU   linekeymargins     r   r   z_indent.<locals>.<listcomp>  s>     5 5 5 ),D		;v}}t 5 5 5r   )
splitlinesr*   )r   r_  newliner^  indented_liness    ` ` r   r-  r-    sM    5 5 5 5 5"&//"3"35 5 5N<<'''r   c                      dS )a  
    Simple function that should be used when no effect is desired.
    An alternative to checking for  an optional function type parameter.

    e.g.
    def decorate(func, pre_func=None, post_func=None):
        if pre_func:
            pre_func()
        func()
        if post_func:
            post_func()

    vs

    def decorate(func, pre_func=noop, post_func=noop):
        pre_func()
        func()
        post_func()
    Nr   )r+   r   s     r   nooprd    s	    ( 4r   rR   rR  rQ  )r   r   N)NNN)NN)'r   r>   rT  r  r   rX   r   rJ   r   r   r   	typeutilsr   r	   ImportErrorobjectr=   r:   rO   r]   rc   rp   r}   r   r   r   r   r   r   r   r   r   r   r   r   rB  boolr-  rd  r   r   r   <module>ri     s  >  


 				          $ $ $ $ $ $ * * * * * * * * 7 6 6 6 6 6((((((555JJ   JJJ
 $bb--,,3300). . . .b   :	E 	E 	E       >' ' 'T% % % % %i' % % %<' ' ' ' 'I- ' ' 'T  & & & &>:1 :1 :1 :1z0 0 0 0r"? "? "? "?Jy y y yx% % %Ps s s s s s s sl		 	 	 	 	j 	 	 		 	 	 	 	z 	 	 	 #'D ( ( ( (    s   ? AA