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