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 | |
| 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 Brandl | 2e7346a | 2010-07-31 18:09:23 +0000 | [diff] [blame] | 40 | .. 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 |
| 62 | most common upcoming calls. |
| 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 |
| 87 | when more recent calls are the best predictors of upcoming calls. |
| 88 | |
| 89 | .. versionadded:: 3.2 |
| 90 | |
Georg Brandl | 8a1caa2 | 2010-07-29 16:01:11 +0000 | [diff] [blame] | 91 | .. decorator:: total_ordering |
Raymond Hettinger | c50846a | 2010-04-05 18:56:31 +0000 | [diff] [blame] | 92 | |
| 93 | Given a class defining one or more rich comparison ordering methods, this |
Benjamin Peterson | 08bf91c | 2010-04-11 16:12:57 +0000 | [diff] [blame] | 94 | class decorator supplies the rest. This simplifies the effort involved |
Raymond Hettinger | c50846a | 2010-04-05 18:56:31 +0000 | [diff] [blame] | 95 | in specifying all of the possible rich comparison operations: |
| 96 | |
| 97 | The class must define one of :meth:`__lt__`, :meth:`__le__`, |
| 98 | :meth:`__gt__`, or :meth:`__ge__`. |
| 99 | In addition, the class should supply an :meth:`__eq__` method. |
| 100 | |
| 101 | For example:: |
| 102 | |
| 103 | @total_ordering |
| 104 | class Student: |
| 105 | def __eq__(self, other): |
| 106 | return ((self.lastname.lower(), self.firstname.lower()) == |
| 107 | (other.lastname.lower(), other.firstname.lower())) |
| 108 | def __lt__(self, other): |
| 109 | return ((self.lastname.lower(), self.firstname.lower()) < |
| 110 | (other.lastname.lower(), other.firstname.lower())) |
| 111 | |
| 112 | .. versionadded:: 3.2 |
| 113 | |
Georg Brandl | 036490d | 2009-05-17 13:00:36 +0000 | [diff] [blame] | 114 | .. function:: partial(func, *args, **keywords) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 115 | |
| 116 | Return a new :class:`partial` object which when called will behave like *func* |
| 117 | called with the positional arguments *args* and keyword arguments *keywords*. If |
| 118 | more arguments are supplied to the call, they are appended to *args*. If |
| 119 | additional keyword arguments are supplied, they extend and override *keywords*. |
| 120 | Roughly equivalent to:: |
| 121 | |
| 122 | def partial(func, *args, **keywords): |
| 123 | def newfunc(*fargs, **fkeywords): |
| 124 | newkeywords = keywords.copy() |
| 125 | newkeywords.update(fkeywords) |
| 126 | return func(*(args + fargs), **newkeywords) |
| 127 | newfunc.func = func |
| 128 | newfunc.args = args |
| 129 | newfunc.keywords = keywords |
| 130 | return newfunc |
| 131 | |
| 132 | The :func:`partial` is used for partial function application which "freezes" |
| 133 | some portion of a function's arguments and/or keywords resulting in a new object |
| 134 | with a simplified signature. For example, :func:`partial` can be used to create |
| 135 | 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] | 136 | defaults to two: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 137 | |
Christian Heimes | fe337bf | 2008-03-23 21:54:12 +0000 | [diff] [blame] | 138 | >>> from functools import partial |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 139 | >>> basetwo = partial(int, base=2) |
| 140 | >>> basetwo.__doc__ = 'Convert base 2 string to an int.' |
| 141 | >>> basetwo('10010') |
| 142 | 18 |
| 143 | |
| 144 | |
Georg Brandl | 58f9e4f | 2008-04-19 22:18:33 +0000 | [diff] [blame] | 145 | .. function:: reduce(function, iterable[, initializer]) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 146 | |
| 147 | Apply *function* of two arguments cumulatively to the items of *sequence*, from |
| 148 | left to right, so as to reduce the sequence to a single value. For example, |
| 149 | ``reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])`` calculates ``((((1+2)+3)+4)+5)``. |
| 150 | The left argument, *x*, is the accumulated value and the right argument, *y*, is |
| 151 | the update value from the *sequence*. If the optional *initializer* is present, |
| 152 | it is placed before the items of the sequence in the calculation, and serves as |
| 153 | a default when the sequence is empty. If *initializer* is not given and |
| 154 | *sequence* contains only one item, the first item is returned. |
| 155 | |
| 156 | |
Georg Brandl | 036490d | 2009-05-17 13:00:36 +0000 | [diff] [blame] | 157 | .. function:: update_wrapper(wrapper, wrapped, assigned=WRAPPER_ASSIGNMENTS, updated=WRAPPER_UPDATES) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 158 | |
| 159 | Update a *wrapper* function to look like the *wrapped* function. The optional |
| 160 | arguments are tuples to specify which attributes of the original function are |
| 161 | assigned directly to the matching attributes on the wrapper function and which |
| 162 | attributes of the wrapper function are updated with the corresponding attributes |
| 163 | from the original function. The default values for these arguments are the |
| 164 | module level constants *WRAPPER_ASSIGNMENTS* (which assigns to the wrapper |
| 165 | function's *__name__*, *__module__* and *__doc__*, the documentation string) and |
| 166 | *WRAPPER_UPDATES* (which updates the wrapper function's *__dict__*, i.e. the |
| 167 | instance dictionary). |
| 168 | |
Christian Heimes | d8654cf | 2007-12-02 15:22:16 +0000 | [diff] [blame] | 169 | The main intended use for this function is in :term:`decorator` functions which |
| 170 | wrap the decorated function and return the wrapper. If the wrapper function is |
| 171 | not updated, the metadata of the returned function will reflect the wrapper |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 172 | definition rather than the original function definition, which is typically less |
| 173 | than helpful. |
| 174 | |
| 175 | |
Georg Brandl | 8a1caa2 | 2010-07-29 16:01:11 +0000 | [diff] [blame] | 176 | .. decorator:: wraps(wrapped, assigned=WRAPPER_ASSIGNMENTS, updated=WRAPPER_UPDATES) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 177 | |
| 178 | This is a convenience function for invoking ``partial(update_wrapper, |
| 179 | wrapped=wrapped, assigned=assigned, updated=updated)`` as a function decorator |
Christian Heimes | fe337bf | 2008-03-23 21:54:12 +0000 | [diff] [blame] | 180 | when defining a wrapper function. For example: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 181 | |
Christian Heimes | fe337bf | 2008-03-23 21:54:12 +0000 | [diff] [blame] | 182 | >>> from functools import wraps |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 183 | >>> def my_decorator(f): |
| 184 | ... @wraps(f) |
| 185 | ... def wrapper(*args, **kwds): |
Georg Brandl | 6911e3c | 2007-09-04 07:15:32 +0000 | [diff] [blame] | 186 | ... print('Calling decorated function') |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 187 | ... return f(*args, **kwds) |
| 188 | ... return wrapper |
| 189 | ... |
| 190 | >>> @my_decorator |
| 191 | ... def example(): |
| 192 | ... """Docstring""" |
Georg Brandl | 6911e3c | 2007-09-04 07:15:32 +0000 | [diff] [blame] | 193 | ... print('Called example function') |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 194 | ... |
| 195 | >>> example() |
| 196 | Calling decorated function |
| 197 | Called example function |
| 198 | >>> example.__name__ |
| 199 | 'example' |
| 200 | >>> example.__doc__ |
| 201 | 'Docstring' |
| 202 | |
| 203 | Without the use of this decorator factory, the name of the example function |
| 204 | would have been ``'wrapper'``, and the docstring of the original :func:`example` |
| 205 | would have been lost. |
| 206 | |
| 207 | |
| 208 | .. _partial-objects: |
| 209 | |
| 210 | :class:`partial` Objects |
| 211 | ------------------------ |
| 212 | |
| 213 | :class:`partial` objects are callable objects created by :func:`partial`. They |
| 214 | have three read-only attributes: |
| 215 | |
| 216 | |
| 217 | .. attribute:: partial.func |
| 218 | |
| 219 | A callable object or function. Calls to the :class:`partial` object will be |
| 220 | forwarded to :attr:`func` with new arguments and keywords. |
| 221 | |
| 222 | |
| 223 | .. attribute:: partial.args |
| 224 | |
| 225 | The leftmost positional arguments that will be prepended to the positional |
| 226 | arguments provided to a :class:`partial` object call. |
| 227 | |
| 228 | |
| 229 | .. attribute:: partial.keywords |
| 230 | |
| 231 | The keyword arguments that will be supplied when the :class:`partial` object is |
| 232 | called. |
| 233 | |
| 234 | :class:`partial` objects are like :class:`function` objects in that they are |
| 235 | callable, weak referencable, and can have attributes. There are some important |
| 236 | differences. For instance, the :attr:`__name__` and :attr:`__doc__` attributes |
| 237 | are not created automatically. Also, :class:`partial` objects defined in |
| 238 | classes behave like static methods and do not transform into bound methods |
| 239 | during instance attribute look-up. |
| 240 | |