3 \rz+@sdZddddddddd d d g Zyd d lmZWnek rBYnXd dlmZd dlmZd dl m Z d dl m Z d dl mZyd dlmZWn"ek rGdddZYnXdZZd[ZeefddZeefddZefddZefd d!Zefd"d#Zefd$d%Zefd&d'Zefd(d)Zefd*d+Zefd,d-Zefd.d/Zefd0d1Zefd2d3Z efd4d5Z!d6efd7efd8efgd8efd9efd6efgd9efd8efd7efgd7efd6e fd9e!fgd:Z"d;dZ#dd d Z%yd d?lm%Z%Wnek r*YnXGd@d d e&Z'edAdBdCdDdEgZ(GdFdGdGe)Z*e&fe+e,e-e.dHhe/e.e0fdIdJZ1d\dMdZ2dNdOZ3yd dPlm3Z3Wnek rYnXdQdRZ4d]dSdTZ5dUdVZ6dWdXZ7dYd Z8dHS)^zEfunctools.py - Tools for working with functions and callable objects update_wrapperwrapsWRAPPER_ASSIGNMENTSWRAPPER_UPDATEStotal_ordering cmp_to_key lru_cachereducepartial partialmethodsingledispatch)r)get_cache_token) namedtuple)MappingProxyType)WeakKeyDictionary)recursive_repr)RLockc@s eZdZdZddZddZdS)rz/Dummy reentrant lock for builds without threadscCsdS)N)selfrr!/usr/lib64/python3.6/functools.py __enter__szRLock.__enter__cCsdS)Nr)rexctypeexcinstexctbrrr__exit__szRLock.__exit__N)__name__ __module__ __qualname____doc__rrrrrrrsrrrrr__annotations____dict__c Csnx<|D]4}yt||}Wntk r,YqXt|||qWx$|D]}t||jt||iqDW||_|S)aUpdate a wrapper function to look like the wrapped function wrapper is the function to be updated wrapped is the original function assigned is a tuple naming the attributes assigned directly from the wrapped function to the wrapper function (defaults to functools.WRAPPER_ASSIGNMENTS) updated is a tuple naming the attributes of the wrapper that are updated with the corresponding attribute from the wrapped function (defaults to functools.WRAPPER_UPDATES) )getattrAttributeErrorsetattrupdate __wrapped__)wrapperwrappedassignedupdatedattrvaluerrrr,s  cCstt|||dS)aDecorator factory to apply update_wrapper() to a wrapper function 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(). )r'r(r))r r)r'r(r)rrrrJs cCs$|j|}||kr|S| o"||kS)zIReturn a > b. Computed by @total_ordering from (not a < b) and (a != b).)__lt__)rotherNotImplemented op_resultrrr _gt_from_ltbs r0cCs|j|}|p||kS)zEReturn a <= b. Computed by @total_ordering from (a < b) or (a == b).)r,)rr-r.r/rrr _le_from_ltis r1cCs|j|}||kr|S| S)z=Return a >= b. Computed by @total_ordering from (not a < b).)r,)rr-r.r/rrr _ge_from_ltns r2cCs$|j|}||kr|S| p"||kS)zJReturn a >= b. Computed by @total_ordering from (not a <= b) or (a == b).)__le__)rr-r.r/rrr _ge_from_leus r4cCs"|j|}||kr|S|o ||kS)zFReturn a < b. Computed by @total_ordering from (a <= b) and (a != b).)r3)rr-r.r/rrr _lt_from_le|s r5cCs|j|}||kr|S| S)z=Return a > b. Computed by @total_ordering from (not a <= b).)r3)rr-r.r/rrr _gt_from_les r6cCs$|j|}||kr|S| o"||kS)zIReturn a < b. Computed by @total_ordering from (not a > b) and (a != b).)__gt__)rr-r.r/rrr _lt_from_gts r8cCs|j|}|p||kS)zEReturn a >= b. Computed by @total_ordering from (a > b) or (a == b).)r7)rr-r.r/rrr _ge_from_gts r9cCs|j|}||kr|S| S)z=Return a <= b. Computed by @total_ordering from (not a > b).)r7)rr-r.r/rrr _le_from_gts r:cCs$|j|}||kr|S| p"||kS)zJReturn a <= b. Computed by @total_ordering from (not a >= b) or (a == b).)__ge__)rr-r.r/rrr _le_from_ges r<cCs"|j|}||kr|S|o ||kS)zFReturn a > b. Computed by @total_ordering from (a >= b) and (a != b).)r;)rr-r.r/rrr _gt_from_ges r=cCs|j|}||kr|S| S)z=Return a < b. Computed by @total_ordering from (not a >= b).)r;)rr-r.r/rrr _lt_from_ges r>r7r3r;r,)r,r3r7r;csZfddtD}|stdt|}x.t|D]"\}}||kr0||_t||q0WS)z6Class decorator that fills in missing ordering methodscs(g|] }t|dtt|dk r|qS)N)r!object).0op)clsrr sz"total_ordering..z6must define at least one ordering operation: < > <= >=)_convert ValueErrormaxrr#)rBrootsrootopnameopfuncr)rBrrscsGfdddt}|S)z,Convert a cmp= function into a key= functioncsZeZdZdgZddZfddZfddZfdd Zfd d Zfd d Z dZ dS)zcmp_to_key..KobjcSs ||_dS)N)rK)rrKrrr__init__szcmp_to_key..K.__init__cs|j|jdkS)Nr )rK)rr-)mycmprrr,szcmp_to_key..K.__lt__cs|j|jdkS)Nr )rK)rr-)rMrrr7szcmp_to_key..K.__gt__cs|j|jdkS)Nr )rK)rr-)rMrr__eq__szcmp_to_key..K.__eq__cs|j|jdkS)Nr )rK)rr-)rMrrr3szcmp_to_key..K.__le__cs|j|jdkS)Nr )rK)rr-)rMrrr;szcmp_to_key..K.__ge__N) rrr __slots__rLr,r7rNr3r;__hash__r)rMrrKs     rQ)r?)rMrQr)rMrrs)rcsJeZdZdZdZfddZd d Zed d Zd dZ ddZ Z S)r zSNew function with partial application of the given arguments and keywords. funcargskeywordsr __weakref__cs|s tdt|dkr td|^}}}t|s:tdt|}t|drv|j|}|jj}|j||}~|j }t t |j |}||_ ||_||_|S)Nz1descriptor '__new__' of partial needs an argumentz*type 'partial' takes at least one argumentz#the first argument must be callablerR) TypeErrorlencallabletuplehasattrrSrTcopyr$rRsuperr __new__)rSrTrBrRZtmpkwr) __class__rrr^s(      zpartial.__new__cOs:|s td|^}}|jj}|j||j|j||S)Nz2descriptor '__call__' of partial needs an argument)rWrTr\r$rRrS)rSrTrZ newkeywordsrrr__call__s   zpartial.__call__cCst|j}t|jg}|jdd|jD|jdd|jjDt|jdkrld|ddj |dS|ddj |dS) Ncss|]}t|VqdS)N)repr)r@xrrr sz#partial.__repr__..css |]\}}|d|VqdS)=Nr)r@kvrrrrcs functoolsz functools.(z, )) typerrarRextendrSrTitemsrjoin)rqualnamerSrrr__repr__s  zpartial.__repr__cCs*t||jf|j|j|jpd|jp$dffS)N)rjrRrSrTr )rrrr __reduce__#szpartial.__reduce__cCst|tstdt|dkr0tdt||\}}}}t| szt|t sz|dk rft|t sz|dk rt|t rtdt|}|dkri}nt|tk rt|}|dkri}||_||_||_ ||_ dS)Nz(argument to __setstate__ must be a tuplezexpected 4 items in state, got zinvalid partial state) isinstancerZrWrXrYdictrjr rRrSrT)rstaterRrSkwds namespacerrr __setstate__'s(    zpartial.__setstate__)rRrSrTr rU) rrrrrOr^r`rrorprw __classcell__rr)r_rr s  )r c@s<eZdZdZddZddZddZdd Zed d Z d S) r zMethod descriptor with partial application of the given arguments and keywords. Supports wrapping existing descriptors and handles non-descriptor callables as instance methods. cOsrt| r$t|d r$tdj|t|tr\|j|_|j||_|jj |_|jj |n||_||_||_dS)N__get__z${!r} is not callable or a descriptor) rYr[rWformatrrr rRrSrTr\r$)rrRrSrTrrrrLMs   zpartialmethod.__init__cCsNdjtt|j}djdd|jjD}d}|j|jj|jj |j ||dS)Nz, css|]\}}dj||VqdS)z{}={!r}N)rz)r@rerfrrrrccsz)partialmethod.__repr__..z*{module}.{cls}({func}, {args}, {keywords}))modulerBrRrSrT) rmmaprarSrTrlrzr_rrrR)rrSrT format_stringrrrroas  zpartialmethod.__repr__csfdd}j|_|_|S)Ncs<jj}|j||^}}|fjt|}j||S)N)rTr\r$rSrZrR)rSrT call_keywords cls_or_selfrest call_args)rrr_methodms   z3partialmethod._make_unbound_method.._method)__isabstractmethod___partialmethod)rrr)rr_make_unbound_methodls z"partialmethod._make_unbound_methodc Cst|jdd}d}|dk rd|||}||jk rdt|f|j|j}y |j|_Wntk rbYnX|dkr||jj||}|S)Nry) r!rRr rSrT__self__r"rry)rrKrBgetresultnew_funcrrrryws   zpartialmethod.__get__cCst|jddS)NrF)r!rR)rrrrrsz"partialmethod.__isabstractmethod__N) rrrrrLrorrypropertyrrrrrr Es    CacheInfohitsmissesmaxsizecurrsizec@s(eZdZdZdZefddZddZdS) _HashedSeqz This class guarantees that hash() will be called no more than once per element. This is important because the lru_cache() will hash the key multiple times on a cache miss. hashvaluecCs||dd<|||_dS)N)r)rtuphashrrrrLs z_HashedSeq.__init__cCs|jS)N)r)rrrrrPsz_HashedSeq.__hash__N)rrrrrOrrLrPrrrrrs rNc s|}|r*||7}x|jD] } || 7}qW|rl||fdd|D7}|r||fdd|jD7}n$||dkr|d|kr|dSt|S)aMake a cache key from optionally typed positional and keyword arguments The key is constructed in a way that is flat as possible rather than as a nested structure that would take more memory. If there is only a single argument and its data type is known to cache its hash value, then that argument is returned without a wrapper. This saves space and improves lookup speed. c3s|]}|VqdS)Nr)r@rf)rjrrrcsz_make_key..c3s|]}|VqdS)Nr)r@rf)rjrrrcsr )rlvaluesr) rSrutypedkwd_mark fasttypesrZrjrXkeyitemr)rjr _make_keys  rFcs.dk rtt rtdfdd}|S)aLeast-recently-used cache decorator. If *maxsize* is set to None, the LRU features are disabled and the cache can grow without bound. If *typed* is True, arguments of different types will be cached separately. For example, f(3.0) and f(3) will be treated as distinct calls with distinct results. Arguments to the cached function must be hashable. View the cache statistics named tuple (hits, misses, maxsize, currsize) with f.cache_info(). Clear the cache and statistics with f.cache_clear(). Access the underlying function with f.__wrapped__. See: http://en.wikipedia.org/wiki/Cache_algorithms#Least_Recently_Used Nz)Expected maxsize to be an integer or Nonecst|t}t||S)N)_lru_cache_wrapper _CacheInfor) user_functionr&)rrrrdecorating_functionsz&lru_cache..decorating_function)rrintrW)rrrr)rrrrscstt d\id djjt gddgdd< dkrh fdd}nN dkr fdd}n* fd d} fd d } fd d }||_||_|S)Nr rrVFcs||}d7|S)Nrr)rSrur)rrrrr&s z#_lru_cache_wrapper..wrappercsH||}|}|k r*d7|S||}||<d7|S)Nrr)rSrurr)cache cache_getrmake_keyrsentinelrrrrr&s   c s2 ||} f|}|dk rr|\}}}}||<||< }||< <||< |<d7|SWdQRX||} |krnr } || <|| <|  } } d < <| =| |<n6 }| ||g}||< <|< k d7 WdQRX|S)Nrr) rSrurlinkZ link_prevZ link_nextZ_keyrZlastZoldrootZoldkeyZ oldresult)KEYNEXTPREVRESULTrr cache_lenfullrlockrrrrHrrrrr&sB      c s SQRXdS)zReport cache statisticsNrr)rrrrrrrr cache_infoGsz&_lru_cache_wrapper..cache_infoc s<.jddgdd<ddWdQRXdS)z$Clear the cache and cache statisticsNr F)clearr)rrrrrrHrr cache_clearLs z'_lru_cache_wrapper..cache_clear)r rrVr)r?rr__len__rrr)rrrrr&rrr)rrrrrrrrrrrrrrrHrrrrrs* *9 r)rcCsg}xdd|D}|s|Sx:|D]2}|d}x$|D]}||ddkr4d}Pq4WPq"W|dkrhtd|j|x|D]}|d|krx|d=qxWqWdS)zMerges MROs in *sequences* to a single MRO using the C3 algorithm. Adapted from http://www.python.org/download/releases/2.3/mro/. cSsg|] }|r|qSrr)r@srrrrCksz_c3_merge..r rNzInconsistent hierarchy) RuntimeErrorappend) sequencesrs1 candidates2seqrrr _c3_mergecs$     rc s&x8tt|jD]"\}tdrt|j|}PqWd}rFtngt|jd|}g}t|j|d}x:D]2t|rxtfdd|jD rx|jqxWx|D]j qWfdd|D}fdd|D}fd d|D} t |gg||| |g|g|gS) aComputes the method resolution order using extended C3 linearization. If no *abcs* are given, the algorithm works exactly like the built-in C3 linearization used for method resolution. If given, *abcs* is a list of abstract base classes that should be inserted into the resulting MRO. Unrelated ABCs are ignored and don't end up in the result. The algorithm inserts ABCs where their functionality is introduced, i.e. issubclass(cls, abc) returns True for the class itself but returns False for all its direct base classes. Implicit ABCs for a given class (either registered or inferred from the presence of a special method like __len__) are inserted directly after the last ABC explicitly listed in the MRO of said class. If two implicit ABCs end up next to each other in the resulting MRO, their ordering depends on the order of types in *abcs*. __abstractmethods__r Nc3s|]}t|VqdS)N) issubclass)r@b)baserrrcsz_c3_mro..csg|]}t|dqS))abcs)_c3_mro)r@r)rrrrCsz_c3_mro..csg|]}t|dqS))r)r)r@r)rrrrCscsg|]}t|dqS))r)r)r@r)rrrrCs) enumeratereversed __bases__r[rXlistranyrremover) rBriboundaryexplicit_basesabstract_bases other_basesexplicit_c3_mrosabstract_c3_mros other_c3_mrosr)rrrr~s(    rcstjfddfddDfddfddDtg}xD]}g}x<|jD]0}|krlt|rl|jfdd|jDqlW|s|j|qZ|jtd d x,|D]$}x|D]}||kr|j|qWqWqZWt|d S) zCalculates the method resolution order for a given class *cls*. Includes relevant abstract base classes (with their respective bases) from the *types* iterable. Uses a modified C3 linearization algorithm. cs|kot|dot|S)N__mro__)r[r)typ)basesrBrr is_relatedsz _compose_mro..is_relatedcsg|]}|r|qSrr)r@n)rrrrCsz _compose_mro..cs(x"D]}||kr||jkrdSqWdS)NTF)r)rr-)typesrris_strict_bases z$_compose_mro..is_strict_basecsg|]}|s|qSrr)r@r)rrrrCscsg|]}|kr|qSrr)r@r)type_setrrrCsT)rreverse)r)setr__subclasses__rrsortrXr)rBrmrorfoundsubsubclsr)rrBrrrrr _compose_mros*      rcCsxt||j}d}xZ|D]R}|dk r^||kr\||jkr\||jkr\t|| r\tdj||P||kr|}qW|j|S)a^Returns the best matching implementation from *registry* for type *cls*. Where there is no registered implementation for a specific type, its method resolution order is used to find a more generic implementation. Note: if *registry* does not contain an implementation for the base *object* type, this function may return None. NzAmbiguous dispatch: {} or {})rkeysrrrrzr)rBregistryrmatchtrrr _find_impls     rcsitdfddd fdd fdd}t|dd |t<|_|_t|_j|_t |||S) alSingle-dispatch generic function decorator. Transforms a function into a generic function, which can have different behaviours depending upon the type of its first argument. The decorated function acts as the default implementation, and additional implementations can be registered using the register() attribute of the generic function. Ncs|dk r"t}|kr"j|y |}WnHtk rvy |}Wntk rht|}YnX||<YnX|S)zgeneric_func.dispatch(cls) -> Runs the dispatch algorithm to return the best available implementation for the given *cls* registered on *generic_func*. N)r rKeyErrorr)rB current_tokenimpl) cache_tokendispatch_cacherrrdispatchs  z singledispatch..dispatchcsB|dkrfddS|<dkr6tdr6tj|S)zgeneric_func.register(cls, func) -> func Registers a new implementation for the given *cls* on a *generic_func*. Ncs |S)Nr)f)rBregisterrrsz2singledispatch..register..r)r[r r)rBrR)rrrr)rBrrsz singledispatch..registercs&|std|dj||S)Nz( requires at least 1 positional argumentr )rWr_)rSkw)rfuncnamerrr&"szsingledispatch..wrapperrzsingledispatch function)N) rr!r?rrrrr _clear_cacher)rRr&r)rrrrrrrr s    )rrrrr)r )rF)N)9r__all__ _functoolsr ImportErrorabcr collectionsrrrweakrefrreprlibr_threadrrrrrr.r0r1r2r4r5r6r8r9r:r<r=r>rDrrr r?r rrrrstr frozensetrjrZrXrrrrrrrr rrrrs                      NN %t -)