a „oeÐ:ã@s.ddlZddlZddlZddlZddlZddlZddlZddlZddl m Z m Z e de de fd�Z dd„Zdd „Zd d „Ze ¡fe e e ge fe d œd d„Zdd„Zdd„Zdd„Zdd„Zdd„ZGdd„dƒZdd„Zdd„ddfd d!„Zd"d#„Zd$d%„Zd&d'„Zd(d)„Zd*d+„Zddd,œd-d.„Z dS)/éN)ÚCallableÚTypeVarÚ CallableT.)ÚboundcGsdd„}t ||¡S)a; Compose any number of unary functions into a single unary function. >>> import textwrap >>> expected = str.strip(textwrap.dedent(compose.__doc__)) >>> strip_and_dedent = compose(str.strip, textwrap.dedent) >>> strip_and_dedent(compose.__doc__) == expected True Compose also allows the innermost function to take arbitrary arguments. >>> round_three = lambda x: round(x, ndigits=3) >>> f = compose(round_three, int.__truediv__) >>> [f(3*x, x+1) for x in range(1,10)] [1.5, 2.0, 2.25, 2.4, 2.5, 2.571, 2.625, 2.667, 2.7] cs‡‡fdd„S)Ncsˆˆ|i|¤ŽƒS©N©©ÚargsÚkwargs©Úf1Úf2rúGC:\Program Files\Certbot\pkgs\pkg_resources\_vendor\jaraco\functools.pyÚ$óz.compose..compose_two..rr rr rÚ compose_two#szcompose..compose_two)Ú functoolsÚreduce)ZfuncsrrrrÚcomposesrcs‡‡‡fdd„}|S)z× Return a function that will call a named method on the target object with optional positional and keyword arguments. >>> lower = method_caller('lower') >>> lower('MyString') 'mystring' cst|ˆƒ}|ˆiˆ¤ŽSr)Úgetattr)ÚtargetÚfunc©r r Ú method_namerrÚ call_method4s z"method_caller..call_methodr)rr r rrrrÚ method_caller)s rcs*t ˆ¡‡‡fdd„ƒ‰‡fdd„ˆ_ˆS)ad Decorate func so it's only ever called the first time. This decorator can ensure that an expensive or non-idempotent function will not be expensive on subsequent calls and is idempotent. >>> add_three = once(lambda a: a+3) >>> add_three(3) 6 >>> add_three(9) 6 >>> add_three('12') 6 To reset the stored value, simply clear the property ``saved_result``. >>> del add_three.saved_result >>> add_three(9) 12 >>> add_three(8) 12 Or invoke 'reset()' on it. >>> add_three.reset() >>> add_three(-3) 0 >>> add_three(0) 0 cs tˆdƒsˆ|i|¤Žˆ_ˆjS©NÚ saved_result)Úhasattrrr©rÚwrapperrrr [s zonce..wrappercstˆƒ d¡Sr)ÚvarsÚ __delitem__r)r rrrarzonce..)rÚwrapsÚreset©rrrrÚonce;s r&)ÚmethodÚ cache_wrapperÚreturncs2ttttdœ‡‡fdd„ }dd„|_tˆˆƒp0|S)aV Wrap lru_cache to support storing the cache data in the object instances. Abstracts the common paradigm where the method explicitly saves an underscore-prefixed protected property on first call and returns that subsequently. >>> class MyClass: ... calls = 0 ... ... @method_cache ... def method(self, value): ... self.calls += 1 ... return value >>> a = MyClass() >>> a.method(3) 3 >>> for x in range(75): ... res = a.method(x) >>> a.calls 75 Note that the apparent behavior will be exactly like that of lru_cache except that the cache is stored on each instance, so values in one instance will not flush values from another, and when an instance is deleted, so are the cached values for that instance. >>> b = MyClass() >>> for x in range(35): ... res = b.method(x) >>> b.calls 35 >>> a.method(0) 0 >>> a.calls 75 Note that if method had been decorated with ``functools.lru_cache()``, a.calls would have been 76 (due to the cached value of 0 having been flushed by the 'b' instance). Clear the cache with ``.cache_clear()`` >>> a.method.cache_clear() Same for a method that hasn't yet been called. >>> c = MyClass() >>> c.method.cache_clear() Another cache wrapper may be supplied: >>> cache = functools.lru_cache(maxsize=2) >>> MyClass.method2 = method_cache(lambda self: 3, cache_wrapper=cache) >>> a = MyClass() >>> a.method2() 3 Caution - do not subsequently wrap the method with another decorator, such as ``@property``, which changes the semantics of the function. See also http://code.activestate.com/recipes/577452-a-memoize-decorator-for-instance-methods/ for another implementation and additional justification. )Úselfr r r)cs0t ˆ|¡}ˆ|ƒ}t|ˆj|ƒ||i|¤ŽSr)ÚtypesÚ MethodTypeÚsetattrÚ__name__)r*r r Z bound_methodZ cached_method©r(r'rrr ®s ÿzmethod_cache..wrappercSsdSrrrrrrr¸rzmethod_cache..)ÚobjectÚ cache_clearÚ_special_method_cache)r'r(r rr/rÚ method_cacheesI  ÿr3cs2ˆj}d}||vrdSd|‰‡‡‡fdd„}|S)a: Because Python treats special methods differently, it's not possible to use instance attributes to implement the cached methods. Instead, install the wrapper method under a different name and return a simple proxy to that wrapper. https://github.com/jaraco/jaraco.functools/issues/5 )Ú __getattr__Ú __getitem__NZ__cachedcsFˆt|ƒvr.t ˆ|¡}ˆ|ƒ}t|ˆ|ƒn t|ˆƒ}||i|¤ŽSr)r!r+r,r-r)r*r r rÚcache©r(r'Z wrapper_namerrÚproxyÑs    z$_special_method_cache..proxy)r.)r'r(ÚnameZ special_namesr8rr7rr2¿s  r2cs‡fdd„}|S)ab Decorate a function with a transform function that is invoked on results returned from the decorated function. >>> @apply(reversed) ... def get_numbers(start): ... "doc for get_numbers" ... return range(start, start+3) >>> list(get_numbers(4)) [6, 5, 4] >>> get_numbers.__doc__ 'doc for get_numbers' cst |¡tˆ|ƒƒSr)rr#rr%©Ú transformrrÚwrapìszapply..wrapr)r;r<rr:rÚapplyÝs r=cs‡fdd„}|S)a@ Decorate a function with an action function that is invoked on the results returned from the decorated function (for its side-effect), then return the original result. >>> @result_invoke(print) ... def add_two(a, b): ... return a + b >>> x = add_two(2, 3) 5 >>> x 5 cst ˆ¡‡‡fdd„ƒ}|S)Ncsˆ|i|¤Ž}ˆ|ƒ|Srr)r r Úresult)Úactionrrrr sz,result_invoke..wrap..wrapper©rr#r©r?r%rr<szresult_invoke..wrapr)r?r<rrArÚ result_invokeòs rBcOs||i|¤Ž|S)a— Call a function for its side effect after initialization. The benefit of using the decorator instead of simply invoking a function after defining it is that it makes explicit the author's intent for the function to be called immediately. Whereas if one simply calls the function immediately, it's less obvious if that was intentional or incidental. It also avoids repeating the name - the two actions, defining the function and calling it immediately are modeled separately, but linked by the decorator construct. The benefit of having a function construct (opposed to just invoking some behavior inline) is to serve as a scope in which the behavior occurs. It avoids polluting the global namespace with local variables, provides an anchor on which to attach documentation (docstring), keeps the behavior logically separated (instead of conceptually separated or not separated at all), and provides potential to re-use the behavior for testing or other purposes. This function is named as a pithy way to communicate, "call this function primarily for its side effect", or "while defining this function, also take it aside and call it". It exists because there's no Python construct for "define and call" (nor should there be, as decorators serve this need just fine). The behavior happens immediately and synchronously. >>> @invoke ... def func(): print("called") called >>> func() called Use functools.partial to pass parameters to the initial call >>> @functools.partial(invoke, name='bingo') ... def func(name): print("called with", name) called with bingo r)Úfr r rrrÚinvokes&rDcOst dt¡t|i|¤ŽS)z% Deprecated name for invoke. z$call_aside is deprecated, use invoke)ÚwarningsÚwarnÚDeprecationWarningrDrrrrÚ call_aside8s rHc@sBeZdZdZedƒfdd„Zdd„Zdd„Zd d „Zdd d „Z d S)Ú Throttlerz3 Rate-limit a function (or other callable) ZInfcCs(t|tƒr|j}||_||_| ¡dSr)Ú isinstancerIrÚmax_rater$)r*rrKrrrÚ__init__Es  zThrottler.__init__cCs d|_dS)Nr)Ú last_called)r*rrrr$LszThrottler.resetcOs| ¡|j|i|¤ŽSr)Ú_waitr)r*r r rrrÚ__call__OszThrottler.__call__cCs:t ¡|j}d|j|}t td|ƒ¡t ¡|_dS)z1ensure at least 1/max_rate seconds from last callérN)ÚtimerMrKÚsleepÚmax)r*ÚelapsedZ must_waitrrrrNSszThrottler._waitNcCst|jt |j|¡ƒSr)Ú first_invokerNrÚpartialr)r*ÚobjÚtyperrrÚ__get__ZszThrottler.__get__)N) r.Ú __module__Ú __qualname__Ú__doc__ÚfloatrLr$rOrNrYrrrrrI@s rIcs‡‡fdd„}|S)zÆ Return a function that when invoked will invoke func1 without any parameters (for its side-effect) and then invoke func2 with whatever parameters were passed, returning its result. csˆƒˆ|i|¤ŽSrrr©Úfunc1Úfunc2rrr eszfirst_invoke..wrapperr)r_r`r rr^rrU^srUcCsdSrrrrrrrlrrrc CsR|tdƒkrt ¡nt|ƒ}|D]*}z |ƒWS|yH|ƒYq 0q |ƒS)zÁ Given a callable func, trap the indicated exceptions for up to 'retries' times, invoking cleanup on the exception. On the final attempt, allow any exceptions to propagate. Úinf)r]Ú itertoolsÚcountÚrange)rZcleanupZretriesZtrapZattemptsZattemptrrrÚ retry_callls  recs‡‡fdd„}|S)a7 Decorator wrapper for retry_call. Accepts arguments to retry_call except func and then returns a decorator for the decorated function. Ex: >>> @retry(retries=3) ... def my_func(a, b): ... "this is my funk" ... print(a, b) >>> my_func.__doc__ 'this is my funk' cst ˆ¡‡‡‡fdd„ƒ}|S)Ncs.tjˆg|¢Ri|¤Ž}t|gˆ¢Riˆ¤ŽSr)rrVre)Zf_argsZf_kwargsr)rÚr_argsÚr_kwargsrrr �sz(retry..decorate..wrapperr@r©rfrgr%rÚdecorateŒszretry..decorater)rfrgrirrhrÚretry}srjcCs(t tt¡}ttj||ƒ}t |¡|ƒS)z² Convert a generator into a function that prints all yielded elements >>> @print_yielded ... def x(): ... yield 3; yield None >>> x() 3 None )rrVÚmapÚprintrZmore_itertoolsZconsumer#)rZ print_allZ print_resultsrrrÚ print_yielded—s rmcst ˆ¡‡fdd„ƒ}|S)z¥ Wrap func so it's not called if its first param is None >>> print_text = pass_none(print) >>> print_text('text') text >>> print_text(None) cs"|durˆ|g|¢Ri|¤ŽSdSrr)Zparamr r r%rrr ±szpass_none..wrapperr@rrr%rÚ pass_none§s rncs8t |¡}|j ¡}‡fdd„|Dƒ}tj|fi|¤ŽS)a€ Assign parameters from namespace where func solicits. >>> def func(x, y=3): ... print(x, y) >>> assigned = assign_params(func, dict(x=2, z=4)) >>> assigned() 2 3 The usual errors are raised if a function doesn't receive its required parameters: >>> assigned = assign_params(func, dict(y=3, z=4)) >>> assigned() Traceback (most recent call last): TypeError: func() ...argument... It even works on methods: >>> class Handler: ... def meth(self, arg): ... print(arg) >>> assign_params(Handler().meth, dict(arg='crystal', foo='clear'))() crystal csi|]}|ˆvr|ˆ|“qSrr)Ú.0Úk©Ú namespacerrÚ Õrz!assign_params..)ÚinspectZ signatureÚ parametersÚkeysrrV)rrrZsigÚparamsZcall_nsrrqrÚ assign_params¹s  rxcs(t dd¡‰t ˆ¡‡‡fdd„ƒ}|S)a& Wrap a method such that when it is called, the args and kwargs are saved on the method. >>> class MyClass: ... @save_method_args ... def method(self, a, b): ... print(a, b) >>> my_ob = MyClass() >>> my_ob.method(1, 2) 1 2 >>> my_ob._saved_method.args (1, 2) >>> my_ob._saved_method.kwargs {} >>> my_ob.method(a=3, b='foo') 3 foo >>> my_ob._saved_method.args () >>> my_ob._saved_method.kwargs == dict(a=3, b='foo') True The arguments are stored on the instance, allowing for different instance to save different args. >>> your_ob = MyClass() >>> your_ob.method({str('x'): 3}, b=[4]) {'x': 3} [4] >>> your_ob._saved_method.args ({'x': 3},) >>> my_ob._saved_method.args () Úargs_and_kwargsz args kwargscs6dˆj}ˆ||ƒ}t|||ƒˆ|g|¢Ri|¤ŽS)NZ_saved_)r.r-)r*r r Z attr_nameÚattr©ryr'rrr ýs   z!save_method_args..wrapper)Ú collectionsÚ namedtuplerr#)r'r rr{rÚsave_method_argsÙs" r~)ÚreplaceÚusecs‡‡‡fdd„}|S)a- Replace the indicated exceptions, if raised, with the indicated literal replacement or evaluated expression (if present). >>> safe_int = except_(ValueError)(int) >>> safe_int('five') >>> safe_int('5') 5 Specify a literal replacement with ``replace``. >>> safe_int_r = except_(ValueError, replace=0)(int) >>> safe_int_r('five') 0 Provide an expression to ``use`` to pass through particular parameters. >>> safe_int_pt = except_(ValueError, use='args[0]')(int) >>> safe_int_pt('five') 'five' cs t ˆ¡‡‡‡‡fdd„ƒ}|S)Nc sRzˆ|i|¤ŽWSˆyLztˆƒWYStyFˆYYS0Yn0dSr)ÚevalÚ TypeErrorr)Ú exceptionsrrr€rrr s  z*except_..decorate..wrapperr@r©rƒrr€r%rris zexcept_..decorater)rr€rƒrirr„rÚexcept_s r…)!rrQrtr|r+rbrEZ#pkg_resources.extern.more_itertoolsZ pkg_resourcesÚtypingrrr0rrrr&Ú lru_cacher3r2r=rBrDrHrIrUrerjrmrnrxr~r…rrrrÚsD.üÿû Z* .