blob: c6f5870745d3279b37c7ebaa3b96fb412c586401 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001:mod:`functools` --- Higher order functions and operations on callable objects
2==============================================================================
3
4.. module:: functools
5 :synopsis: Higher order functions and operations on callable objects.
6.. moduleauthor:: Peter Harris <scav@blueyonder.co.uk>
7.. moduleauthor:: Raymond Hettinger <python@rcn.com>
8.. moduleauthor:: Nick Coghlan <ncoghlan@gmail.com>
9.. sectionauthor:: Peter Harris <scav@blueyonder.co.uk>
10
11
Georg Brandl116aa622007-08-15 14:28:22 +000012The :mod:`functools` module is for higher-order functions: functions that act on
13or return other functions. In general, any callable object can be treated as a
14function for the purposes of this module.
15
Thomas Woutersed03b412007-08-28 21:37:11 +000016The :mod:`functools` module defines the following functions:
17
Raymond Hettingerc50846a2010-04-05 18:56:31 +000018.. function:: cmp_to_key(func)
19
20 Transform an old-style comparison function to a key-function. Used with
21 tools that accept key functions (such as :func:`sorted`, :func:`min`,
22 :func:`max`, :func:`heapq.nlargest`, :func:`heapq.nsmallest`,
23 :func:`itertools.groupby`).
24 This function is primarily used as a transition tool for programs
25 being converted from Py2.x which supported the use of comparison
26 functions.
27
28 A compare function is any callable that accept two arguments, compares
29 them, and returns a negative number for less-than, zero for equality,
30 or a positive number for greater-than. A key function is a callable
31 that accepts one argument and returns another value that indicates
32 the position in the desired collation sequence.
33
34 Example::
35
36 sorted(iterable, key=cmp_to_key(locale.strcoll)) # locale-aware sort order
37
38 .. versionadded:: 3.2
39
Georg Brandl2e7346a2010-07-31 18:09:23 +000040.. decorator:: lfu_cache(maxsize)
41
42 Decorator to wrap a function with a memoizing callable that saves up to the
43 *maxsize* most frequent calls. It can save time when an expensive or I/O
44 bound function is periodically called with the same arguments.
45
46 The *maxsize* parameter defaults to 100. Since a dictionary is used to cache
47 results, the positional and keyword arguments to the function must be
48 hashable.
49
50 The wrapped function is instrumented with two attributes, :attr:`hits`
51 and :attr:`misses` which count the number of successful or unsuccessful
52 cache lookups. These statistics are helpful for tuning the *maxsize*
53 parameter and for measuring the cache's effectiveness.
54
55 The wrapped function also has a :attr:`clear` attribute which can be
56 called (with no arguments) to clear the cache.
57
58 A `LFU (least frequently used) cache
59 <http://en.wikipedia.org/wiki/Cache_algorithms#Least-Frequently_Used>`_
60 is indicated when the pattern of calls does not change over time, when
61 more the most common calls already seen are the best predictors of the
Raymond Hettingerc8dc62d2010-08-02 00:59:14 +000062 most common upcoming calls (for example, a phonelist of popular
63 help-lines may have access patterns that persist over time).
Georg Brandl2e7346a2010-07-31 18:09:23 +000064
65 .. versionadded:: 3.2
66
67.. decorator:: lru_cache(maxsize)
68
69 Decorator to wrap a function with a memoizing callable that saves up to the
70 *maxsize* most recent calls. It can save time when an expensive or I/O bound
71 function is periodically called with the same arguments.
72
73 The *maxsize* parameter defaults to 100. Since a dictionary is used to cache
74 results, the positional and keyword arguments to the function must be
75 hashable.
76
77 The wrapped function is instrumented with two attributes, :attr:`hits`
78 and :attr:`misses` which count the number of successful or unsuccessful
79 cache lookups. These statistics are helpful for tuning the *maxsize*
80 parameter and for measuring the cache's effectiveness.
81
82 The wrapped function also has a :attr:`clear` attribute which can be
83 called (with no arguments) to clear the cache.
84
85 A `LRU (least recently used) cache
86 <http://en.wikipedia.org/wiki/Cache_algorithms#Least_Recently_Used>`_
87 is indicated when the pattern of calls changes over time, such as
Raymond Hettingerc8dc62d2010-08-02 00:59:14 +000088 when more recent calls are the best predictors of upcoming calls
89 (for example, the most popular articles on a news server tend to
90 change every day).
Georg Brandl2e7346a2010-07-31 18:09:23 +000091
92 .. versionadded:: 3.2
93
Georg Brandl8a1caa22010-07-29 16:01:11 +000094.. decorator:: total_ordering
Raymond Hettingerc50846a2010-04-05 18:56:31 +000095
96 Given a class defining one or more rich comparison ordering methods, this
Benjamin Peterson08bf91c2010-04-11 16:12:57 +000097 class decorator supplies the rest. This simplifies the effort involved
Raymond Hettingerc50846a2010-04-05 18:56:31 +000098 in specifying all of the possible rich comparison operations:
99
100 The class must define one of :meth:`__lt__`, :meth:`__le__`,
101 :meth:`__gt__`, or :meth:`__ge__`.
102 In addition, the class should supply an :meth:`__eq__` method.
103
104 For example::
105
106 @total_ordering
107 class Student:
108 def __eq__(self, other):
109 return ((self.lastname.lower(), self.firstname.lower()) ==
110 (other.lastname.lower(), other.firstname.lower()))
111 def __lt__(self, other):
112 return ((self.lastname.lower(), self.firstname.lower()) <
113 (other.lastname.lower(), other.firstname.lower()))
114
115 .. versionadded:: 3.2
116
Georg Brandl036490d2009-05-17 13:00:36 +0000117.. function:: partial(func, *args, **keywords)
Georg Brandl116aa622007-08-15 14:28:22 +0000118
119 Return a new :class:`partial` object which when called will behave like *func*
120 called with the positional arguments *args* and keyword arguments *keywords*. If
121 more arguments are supplied to the call, they are appended to *args*. If
122 additional keyword arguments are supplied, they extend and override *keywords*.
123 Roughly equivalent to::
124
125 def partial(func, *args, **keywords):
126 def newfunc(*fargs, **fkeywords):
127 newkeywords = keywords.copy()
128 newkeywords.update(fkeywords)
129 return func(*(args + fargs), **newkeywords)
130 newfunc.func = func
131 newfunc.args = args
132 newfunc.keywords = keywords
133 return newfunc
134
135 The :func:`partial` is used for partial function application which "freezes"
136 some portion of a function's arguments and/or keywords resulting in a new object
137 with a simplified signature. For example, :func:`partial` can be used to create
138 a callable that behaves like the :func:`int` function where the *base* argument
Christian Heimesfe337bf2008-03-23 21:54:12 +0000139 defaults to two:
Georg Brandl116aa622007-08-15 14:28:22 +0000140
Christian Heimesfe337bf2008-03-23 21:54:12 +0000141 >>> from functools import partial
Georg Brandl116aa622007-08-15 14:28:22 +0000142 >>> basetwo = partial(int, base=2)
143 >>> basetwo.__doc__ = 'Convert base 2 string to an int.'
144 >>> basetwo('10010')
145 18
146
147
Georg Brandl58f9e4f2008-04-19 22:18:33 +0000148.. function:: reduce(function, iterable[, initializer])
Georg Brandl116aa622007-08-15 14:28:22 +0000149
150 Apply *function* of two arguments cumulatively to the items of *sequence*, from
151 left to right, so as to reduce the sequence to a single value. For example,
152 ``reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])`` calculates ``((((1+2)+3)+4)+5)``.
153 The left argument, *x*, is the accumulated value and the right argument, *y*, is
154 the update value from the *sequence*. If the optional *initializer* is present,
155 it is placed before the items of the sequence in the calculation, and serves as
156 a default when the sequence is empty. If *initializer* is not given and
157 *sequence* contains only one item, the first item is returned.
158
159
Georg Brandl036490d2009-05-17 13:00:36 +0000160.. function:: update_wrapper(wrapper, wrapped, assigned=WRAPPER_ASSIGNMENTS, updated=WRAPPER_UPDATES)
Georg Brandl116aa622007-08-15 14:28:22 +0000161
162 Update a *wrapper* function to look like the *wrapped* function. The optional
163 arguments are tuples to specify which attributes of the original function are
164 assigned directly to the matching attributes on the wrapper function and which
165 attributes of the wrapper function are updated with the corresponding attributes
166 from the original function. The default values for these arguments are the
167 module level constants *WRAPPER_ASSIGNMENTS* (which assigns to the wrapper
168 function's *__name__*, *__module__* and *__doc__*, the documentation string) and
169 *WRAPPER_UPDATES* (which updates the wrapper function's *__dict__*, i.e. the
170 instance dictionary).
171
Christian Heimesd8654cf2007-12-02 15:22:16 +0000172 The main intended use for this function is in :term:`decorator` functions which
173 wrap the decorated function and return the wrapper. If the wrapper function is
174 not updated, the metadata of the returned function will reflect the wrapper
Georg Brandl116aa622007-08-15 14:28:22 +0000175 definition rather than the original function definition, which is typically less
176 than helpful.
177
178
Georg Brandl8a1caa22010-07-29 16:01:11 +0000179.. decorator:: wraps(wrapped, assigned=WRAPPER_ASSIGNMENTS, updated=WRAPPER_UPDATES)
Georg Brandl116aa622007-08-15 14:28:22 +0000180
181 This is a convenience function for invoking ``partial(update_wrapper,
182 wrapped=wrapped, assigned=assigned, updated=updated)`` as a function decorator
Christian Heimesfe337bf2008-03-23 21:54:12 +0000183 when defining a wrapper function. For example:
Georg Brandl116aa622007-08-15 14:28:22 +0000184
Christian Heimesfe337bf2008-03-23 21:54:12 +0000185 >>> from functools import wraps
Georg Brandl116aa622007-08-15 14:28:22 +0000186 >>> def my_decorator(f):
187 ... @wraps(f)
188 ... def wrapper(*args, **kwds):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000189 ... print('Calling decorated function')
Georg Brandl116aa622007-08-15 14:28:22 +0000190 ... return f(*args, **kwds)
191 ... return wrapper
192 ...
193 >>> @my_decorator
194 ... def example():
195 ... """Docstring"""
Georg Brandl6911e3c2007-09-04 07:15:32 +0000196 ... print('Called example function')
Georg Brandl116aa622007-08-15 14:28:22 +0000197 ...
198 >>> example()
199 Calling decorated function
200 Called example function
201 >>> example.__name__
202 'example'
203 >>> example.__doc__
204 'Docstring'
205
206 Without the use of this decorator factory, the name of the example function
207 would have been ``'wrapper'``, and the docstring of the original :func:`example`
208 would have been lost.
209
210
211.. _partial-objects:
212
213:class:`partial` Objects
214------------------------
215
216:class:`partial` objects are callable objects created by :func:`partial`. They
217have three read-only attributes:
218
219
220.. attribute:: partial.func
221
222 A callable object or function. Calls to the :class:`partial` object will be
223 forwarded to :attr:`func` with new arguments and keywords.
224
225
226.. attribute:: partial.args
227
228 The leftmost positional arguments that will be prepended to the positional
229 arguments provided to a :class:`partial` object call.
230
231
232.. attribute:: partial.keywords
233
234 The keyword arguments that will be supplied when the :class:`partial` object is
235 called.
236
237:class:`partial` objects are like :class:`function` objects in that they are
238callable, weak referencable, and can have attributes. There are some important
239differences. For instance, the :attr:`__name__` and :attr:`__doc__` attributes
240are not created automatically. Also, :class:`partial` objects defined in
241classes behave like static methods and do not transform into bound methods
242during instance attribute look-up.
243