Source code:Lib/functools.py
Thefunctools module is for higher-order functions: functions that act onor return other functions. In general, any callable object can be treated as afunction for the purposes of this module.
Thefunctools module defines the following functions:
Transform an old-style comparison function to a key function. Used withtools that accept key functions (such assorted(),min(),max(),heapq.nlargest(),heapq.nsmallest(),itertools.groupby()). This function is primarily used as a transitiontool for programs being converted from Python 2 which supported the use ofcomparison functions.
A comparison function is any callable that accept two arguments, compares them,and returns a negative number for less-than, zero for equality, or a positivenumber for greater-than. A key function is a callable that accepts oneargument and returns another value indicating the position in the desiredcollation sequence.
Example:
sorted(iterable,key=cmp_to_key(locale.strcoll))# locale-aware sort order
New in version 3.2.
Decorator to wrap a function with a memoizing callable that saves up to themaxsize most recent calls. It can save time when an expensive or I/O boundfunction is periodically called with the same arguments.
Since a dictionary is used to cache results, the positional and keywordarguments to the function must be hashable.
Ifmaxsize is set to None, the LRU feature is disabled and the cache cangrow without bound. The LRU feature performs best whenmaxsize is apower-of-two.
Iftyped is set to True, function arguments of different types will becached separately. For example,f(3) andf(3.0) will be treatedas distinct calls with distinct results.
To help measure the effectiveness of the cache and tune themaxsizeparameter, the wrapped function is instrumented with acache_info()function that returns anamed tuple showinghits,misses,maxsize andcurrsize. In a multi-threaded environment, the hitsand misses are approximate.
The decorator also provides acache_clear() function for clearing orinvalidating the cache.
The original underlying function is accessible through the__wrapped__ attribute. This is useful for introspection, forbypassing the cache, or for rewrapping the function with a different cache.
AnLRU (least recently used) cache worksbest when the most recent calls are the best predictors of upcoming calls (forexample, the most popular articles on a news server tend to change each day).The cache’s size limit assures that the cache does not grow without bound onlong-running processes such as web servers.
Example of an LRU cache for static web content:
@lru_cache(maxsize=32)defget_pep(num):'Retrieve text of a Python Enhancement Proposal'resource='http://www.python.org/dev/peps/pep-%04d/'%numtry:withurllib.request.urlopen(resource)ass:returns.read()excepturllib.error.HTTPError:return'Not Found'>>>fornin8,290,308,320,8,218,320,279,289,320,9991:...pep=get_pep(n)...print(n,len(pep))>>>get_pep.cache_info()CacheInfo(hits=3,misses=8,maxsize=32,currsize=8)
Example of efficiently computingFibonacci numbersusing a cache to implement adynamic programmingtechnique:
@lru_cache(maxsize=None)deffib(n):ifn<2:returnnreturnfib(n-1)+fib(n-2)>>>[fib(n)forninrange(16)][0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610]>>>fib.cache_info()CacheInfo(hits=28,misses=16,maxsize=None,currsize=16)
New in version 3.2.
Changed in version 3.3:Added thetyped option.
Given a class defining one or more rich comparison ordering methods, thisclass decorator supplies the rest. This simplifies the effort involvedin specifying all of the possible rich comparison operations:
The class must define one of__lt__(),__le__(),__gt__(), or__ge__().In addition, the class should supply an__eq__() method.
For example:
@total_orderingclassStudent:def__eq__(self,other):return((self.lastname.lower(),self.firstname.lower())==(other.lastname.lower(),other.firstname.lower()))def__lt__(self,other):return((self.lastname.lower(),self.firstname.lower())<(other.lastname.lower(),other.firstname.lower()))
New in version 3.2.
Return a newpartial object which when called will behave likefunccalled with the positional argumentsargs and keyword argumentskeywords. Ifmore arguments are supplied to the call, they are appended toargs. Ifadditional keyword arguments are supplied, they extend and overridekeywords.Roughly equivalent to:
defpartial(func,*args,**keywords):defnewfunc(*fargs,**fkeywords):newkeywords=keywords.copy()newkeywords.update(fkeywords)returnfunc(*(args+fargs),**newkeywords)newfunc.func=funcnewfunc.args=argsnewfunc.keywords=keywordsreturnnewfunc
Thepartial() is used for partial function application which “freezes”some portion of a function’s arguments and/or keywords resulting in a new objectwith a simplified signature. For example,partial() can be used to createa callable that behaves like theint() function where thebase argumentdefaults to two:
>>>fromfunctoolsimportpartial>>>basetwo=partial(int,base=2)>>>basetwo.__doc__='Convert base 2 string to an int.'>>>basetwo('10010')18
Applyfunction of two arguments cumulatively to the items ofsequence, fromleft to right, so as to reduce the sequence to a single value. For example,reduce(lambdax,y:x+y,[1,2,3,4,5]) calculates((((1+2)+3)+4)+5).The left argument,x, is the accumulated value and the right argument,y, isthe update value from thesequence. If the optionalinitializer is present,it is placed before the items of the sequence in the calculation, and serves asa default when the sequence is empty. Ifinitializer is not given andsequence contains only one item, the first item is returned.
Equivalent to:
defreduce(function,iterable,initializer=None):it=iter(iterable)ifinitializerisNone:value=next(it)else:value=initializerforelementinit:value=function(value,element)returnvalue
Update awrapper function to look like thewrapped function. The optionalarguments are tuples to specify which attributes of the original function areassigned directly to the matching attributes on the wrapper function and whichattributes of the wrapper function are updated with the corresponding attributesfrom the original function. The default values for these arguments are themodule level constantsWRAPPER_ASSIGNMENTS (which assigns to the wrapperfunction’s__name__,__module__,__annotations__ and__doc__, thedocumentation string) andWRAPPER_UPDATES (which updates the wrapperfunction’s__dict__, i.e. the instance dictionary).
To allow access to the original function for introspection and other purposes(e.g. bypassing a caching decorator such aslru_cache()), this functionautomatically adds a __wrapped__ attribute to the wrapper that refers tothe original function.
The main intended use for this function is indecorator functions whichwrap the decorated function and return the wrapper. If the wrapper function isnot updated, the metadata of the returned function will reflect the wrapperdefinition rather than the original function definition, which is typically lessthan helpful.
update_wrapper() may be used with callables other than functions. Anyattributes named inassigned orupdated that are missing from the objectbeing wrapped are ignored (i.e. this function will not attempt to set themon the wrapper function).AttributeError is still raised if thewrapper function itself is missing any attributes named inupdated.
New in version 3.2:Automatic addition of the__wrapped__ attribute.
New in version 3.2:Copying of the__annotations__ attribute by default.
Changed in version 3.2:Missing attributes no longer trigger anAttributeError.
This is a convenience function for invokingpartial(update_wrapper,wrapped=wrapped,assigned=assigned,updated=updated) as a function decoratorwhen defining a wrapper function. For example:
>>>fromfunctoolsimportwraps>>>defmy_decorator(f):...@wraps(f)...defwrapper(*args,**kwds):...print('Calling decorated function')...returnf(*args,**kwds)...returnwrapper...>>>@my_decorator...defexample():..."""Docstring"""...print('Called example function')...>>>example()Calling decorated functionCalled example function>>>example.__name__'example'>>>example.__doc__'Docstring'
Without the use of this decorator factory, the name of the example functionwould have been'wrapper', and the docstring of the originalexample()would have been lost.
partial objects are callable objects created bypartial(). Theyhave three read-only attributes:
A callable object or function. Calls to thepartial object will beforwarded tofunc with new arguments and keywords.
The leftmost positional arguments that will be prepended to the positionalarguments provided to apartial object call.
partial objects are likefunction objects in that they arecallable, weak referencable, and can have attributes. There are some importantdifferences. For instance, the__name__ and__doc__ attributesare not created automatically. Also,partial objects defined inclasses behave like static methods and do not transform into bound methodsduring instance attribute look-up.
10.1.itertools — Functions creating iterators for efficient looping
10.3.operator — Standard operators as functions
Enter search terms or a module, class or function name.