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 | |
Éric Araujo | 6e6cb8e | 2010-11-16 19:13:50 +0000 | [diff] [blame] | 16 | .. seealso:: |
| 17 | |
| 18 | Latest version of the :source:`functools Python source code |
| 19 | <Lib/functools.py>` |
| 20 | |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 21 | The :mod:`functools` module defines the following functions: |
| 22 | |
Éric Araujo | b10089e | 2010-11-18 14:22:08 +0000 | [diff] [blame] | 23 | .. function:: cmp_to_key(func) |
Raymond Hettinger | c50846a | 2010-04-05 18:56:31 +0000 | [diff] [blame] | 24 | |
Benjamin Peterson | cca6531 | 2010-08-09 02:13:10 +0000 | [diff] [blame] | 25 | Transform an old-style comparison function to a key-function. Used with |
| 26 | tools that accept key functions (such as :func:`sorted`, :func:`min`, |
| 27 | :func:`max`, :func:`heapq.nlargest`, :func:`heapq.nsmallest`, |
| 28 | :func:`itertools.groupby`). This function is primarily used as a transition |
| 29 | tool for programs being converted from Py2.x which supported the use of |
| 30 | comparison functions. |
Raymond Hettinger | c50846a | 2010-04-05 18:56:31 +0000 | [diff] [blame] | 31 | |
Benjamin Peterson | cca6531 | 2010-08-09 02:13:10 +0000 | [diff] [blame] | 32 | A compare function is any callable that accept two arguments, compares them, |
| 33 | and returns a negative number for less-than, zero for equality, or a positive |
| 34 | number for greater-than. A key function is a callable that accepts one |
| 35 | argument and returns another value that indicates the position in the desired |
| 36 | collation sequence. |
Raymond Hettinger | c50846a | 2010-04-05 18:56:31 +0000 | [diff] [blame] | 37 | |
Benjamin Peterson | cca6531 | 2010-08-09 02:13:10 +0000 | [diff] [blame] | 38 | Example:: |
Raymond Hettinger | c50846a | 2010-04-05 18:56:31 +0000 | [diff] [blame] | 39 | |
Benjamin Peterson | cca6531 | 2010-08-09 02:13:10 +0000 | [diff] [blame] | 40 | sorted(iterable, key=cmp_to_key(locale.strcoll)) # locale-aware sort order |
Raymond Hettinger | c50846a | 2010-04-05 18:56:31 +0000 | [diff] [blame] | 41 | |
| 42 | .. versionadded:: 3.2 |
| 43 | |
Georg Brandl | 67b21b7 | 2010-08-17 15:07:14 +0000 | [diff] [blame] | 44 | |
Raymond Hettinger | 7496b41 | 2010-11-30 19:15:45 +0000 | [diff] [blame] | 45 | .. decorator:: lru_cache(maxsize=100) |
Georg Brandl | 2e7346a | 2010-07-31 18:09:23 +0000 | [diff] [blame] | 46 | |
| 47 | Decorator to wrap a function with a memoizing callable that saves up to the |
| 48 | *maxsize* most recent calls. It can save time when an expensive or I/O bound |
| 49 | function is periodically called with the same arguments. |
| 50 | |
Raymond Hettinger | 7496b41 | 2010-11-30 19:15:45 +0000 | [diff] [blame] | 51 | Since a dictionary is used to cache results, the positional and keyword |
| 52 | arguments to the function must be hashable. |
Georg Brandl | 2e7346a | 2010-07-31 18:09:23 +0000 | [diff] [blame] | 53 | |
Raymond Hettinger | 7496b41 | 2010-11-30 19:15:45 +0000 | [diff] [blame] | 54 | To help measure the effectiveness of the cache and tune the *maxsize* |
| 55 | parameter, the wrapped function is instrumented with a :func:`cache_info` |
| 56 | function that returns a :term:`named tuple` showing *hits*, *misses*, |
| 57 | *maxsize* and *currsize*. |
Nick Coghlan | 234515a | 2010-11-30 06:19:46 +0000 | [diff] [blame] | 58 | |
Raymond Hettinger | 7496b41 | 2010-11-30 19:15:45 +0000 | [diff] [blame] | 59 | The decorator also provides a :func:`cache_clear` function for clearing or |
| 60 | invalidating the cache. |
Georg Brandl | 2e7346a | 2010-07-31 18:09:23 +0000 | [diff] [blame] | 61 | |
Raymond Hettinger | 3fccfcb | 2010-08-17 19:19:29 +0000 | [diff] [blame] | 62 | The original underlying function is accessible through the |
Raymond Hettinger | 7496b41 | 2010-11-30 19:15:45 +0000 | [diff] [blame] | 63 | :attr:`__wrapped__` attribute. This is useful for introspection, for |
| 64 | bypassing the cache, or for rewrapping the function with a different cache. |
Nick Coghlan | 9887683 | 2010-08-17 06:17:18 +0000 | [diff] [blame] | 65 | |
Raymond Hettinger | cc03858 | 2010-11-30 20:02:57 +0000 | [diff] [blame] | 66 | An `LRU (least recently used) cache |
Raymond Hettinger | 7496b41 | 2010-11-30 19:15:45 +0000 | [diff] [blame] | 67 | <http://en.wikipedia.org/wiki/Cache_algorithms#Least_Recently_Used>`_ works |
| 68 | best when more recent calls are the best predictors of upcoming calls (for |
| 69 | example, the most popular articles on a news server tend to change daily). |
| 70 | The cache's size limit assures that the cache does not grow without bound on |
| 71 | long-running processes such as web servers. |
| 72 | |
Raymond Hettinger | cc03858 | 2010-11-30 20:02:57 +0000 | [diff] [blame] | 73 | Example of an LRU cache for static web content:: |
Raymond Hettinger | 7496b41 | 2010-11-30 19:15:45 +0000 | [diff] [blame] | 74 | |
Raymond Hettinger | cc03858 | 2010-11-30 20:02:57 +0000 | [diff] [blame] | 75 | @lru_cache(maxsize=20) |
Raymond Hettinger | 7496b41 | 2010-11-30 19:15:45 +0000 | [diff] [blame] | 76 | def get_pep(num): |
| 77 | 'Retrieve text of a Python Enhancement Proposal' |
| 78 | resource = 'http://www.python.org/dev/peps/pep-%04d/' % num |
| 79 | try: |
| 80 | with urllib.request.urlopen(resource) as s: |
| 81 | return s.read() |
| 82 | except urllib.error.HTTPError: |
| 83 | return 'Not Found' |
| 84 | |
| 85 | >>> for n in 8, 290, 308, 320, 8, 218, 320, 279, 289, 320, 9991: |
| 86 | ... pep = get_pep(n) |
| 87 | ... print(n, len(pep)) |
| 88 | |
| 89 | >>> print(get_pep.cache_info()) |
| 90 | CacheInfo(hits=3, misses=8, maxsize=20, currsize=8) |
Georg Brandl | 2e7346a | 2010-07-31 18:09:23 +0000 | [diff] [blame] | 91 | |
| 92 | .. versionadded:: 3.2 |
| 93 | |
Raymond Hettinger | 00f2f97 | 2010-12-01 00:47:56 +0000 | [diff] [blame^] | 94 | .. seealso:: |
| 95 | |
| 96 | Recipe for a `plain cache without the LRU feature |
| 97 | <http://code.activestate.com/recipes/577479-simple-caching-decorator/>`_. |
Georg Brandl | 67b21b7 | 2010-08-17 15:07:14 +0000 | [diff] [blame] | 98 | |
Georg Brandl | 8a1caa2 | 2010-07-29 16:01:11 +0000 | [diff] [blame] | 99 | .. decorator:: total_ordering |
Raymond Hettinger | c50846a | 2010-04-05 18:56:31 +0000 | [diff] [blame] | 100 | |
| 101 | Given a class defining one or more rich comparison ordering methods, this |
Benjamin Peterson | 08bf91c | 2010-04-11 16:12:57 +0000 | [diff] [blame] | 102 | class decorator supplies the rest. This simplifies the effort involved |
Raymond Hettinger | c50846a | 2010-04-05 18:56:31 +0000 | [diff] [blame] | 103 | in specifying all of the possible rich comparison operations: |
| 104 | |
| 105 | The class must define one of :meth:`__lt__`, :meth:`__le__`, |
| 106 | :meth:`__gt__`, or :meth:`__ge__`. |
| 107 | In addition, the class should supply an :meth:`__eq__` method. |
| 108 | |
| 109 | For example:: |
| 110 | |
| 111 | @total_ordering |
| 112 | class Student: |
| 113 | def __eq__(self, other): |
| 114 | return ((self.lastname.lower(), self.firstname.lower()) == |
| 115 | (other.lastname.lower(), other.firstname.lower())) |
| 116 | def __lt__(self, other): |
| 117 | return ((self.lastname.lower(), self.firstname.lower()) < |
| 118 | (other.lastname.lower(), other.firstname.lower())) |
| 119 | |
| 120 | .. versionadded:: 3.2 |
| 121 | |
Georg Brandl | 67b21b7 | 2010-08-17 15:07:14 +0000 | [diff] [blame] | 122 | |
Georg Brandl | 036490d | 2009-05-17 13:00:36 +0000 | [diff] [blame] | 123 | .. function:: partial(func, *args, **keywords) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 124 | |
| 125 | Return a new :class:`partial` object which when called will behave like *func* |
| 126 | called with the positional arguments *args* and keyword arguments *keywords*. If |
| 127 | more arguments are supplied to the call, they are appended to *args*. If |
| 128 | additional keyword arguments are supplied, they extend and override *keywords*. |
| 129 | Roughly equivalent to:: |
| 130 | |
| 131 | def partial(func, *args, **keywords): |
| 132 | def newfunc(*fargs, **fkeywords): |
| 133 | newkeywords = keywords.copy() |
| 134 | newkeywords.update(fkeywords) |
| 135 | return func(*(args + fargs), **newkeywords) |
| 136 | newfunc.func = func |
| 137 | newfunc.args = args |
| 138 | newfunc.keywords = keywords |
| 139 | return newfunc |
| 140 | |
| 141 | The :func:`partial` is used for partial function application which "freezes" |
| 142 | some portion of a function's arguments and/or keywords resulting in a new object |
| 143 | with a simplified signature. For example, :func:`partial` can be used to create |
| 144 | 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] | 145 | defaults to two: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 146 | |
Christian Heimes | fe337bf | 2008-03-23 21:54:12 +0000 | [diff] [blame] | 147 | >>> from functools import partial |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 148 | >>> basetwo = partial(int, base=2) |
| 149 | >>> basetwo.__doc__ = 'Convert base 2 string to an int.' |
| 150 | >>> basetwo('10010') |
| 151 | 18 |
| 152 | |
| 153 | |
Georg Brandl | 58f9e4f | 2008-04-19 22:18:33 +0000 | [diff] [blame] | 154 | .. function:: reduce(function, iterable[, initializer]) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 155 | |
| 156 | Apply *function* of two arguments cumulatively to the items of *sequence*, from |
| 157 | left to right, so as to reduce the sequence to a single value. For example, |
| 158 | ``reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])`` calculates ``((((1+2)+3)+4)+5)``. |
| 159 | The left argument, *x*, is the accumulated value and the right argument, *y*, is |
| 160 | the update value from the *sequence*. If the optional *initializer* is present, |
| 161 | it is placed before the items of the sequence in the calculation, and serves as |
| 162 | a default when the sequence is empty. If *initializer* is not given and |
| 163 | *sequence* contains only one item, the first item is returned. |
| 164 | |
| 165 | |
Georg Brandl | 036490d | 2009-05-17 13:00:36 +0000 | [diff] [blame] | 166 | .. function:: update_wrapper(wrapper, wrapped, assigned=WRAPPER_ASSIGNMENTS, updated=WRAPPER_UPDATES) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 167 | |
| 168 | Update a *wrapper* function to look like the *wrapped* function. The optional |
| 169 | arguments are tuples to specify which attributes of the original function are |
| 170 | assigned directly to the matching attributes on the wrapper function and which |
| 171 | attributes of the wrapper function are updated with the corresponding attributes |
| 172 | from the original function. The default values for these arguments are the |
| 173 | module level constants *WRAPPER_ASSIGNMENTS* (which assigns to the wrapper |
Antoine Pitrou | 560f764 | 2010-08-04 18:28:02 +0000 | [diff] [blame] | 174 | function's *__name__*, *__module__*, *__annotations__* and *__doc__*, the |
| 175 | documentation string) and *WRAPPER_UPDATES* (which updates the wrapper |
| 176 | function's *__dict__*, i.e. the instance dictionary). |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 177 | |
Nick Coghlan | 9887683 | 2010-08-17 06:17:18 +0000 | [diff] [blame] | 178 | To allow access to the original function for introspection and other purposes |
| 179 | (e.g. bypassing a caching decorator such as :func:`lru_cache`), this function |
Éric Araujo | c6ecb01 | 2010-11-06 06:33:03 +0000 | [diff] [blame] | 180 | automatically adds a __wrapped__ attribute to the wrapper that refers to |
Nick Coghlan | 9887683 | 2010-08-17 06:17:18 +0000 | [diff] [blame] | 181 | the original function. |
| 182 | |
Christian Heimes | d8654cf | 2007-12-02 15:22:16 +0000 | [diff] [blame] | 183 | The main intended use for this function is in :term:`decorator` functions which |
| 184 | wrap the decorated function and return the wrapper. If the wrapper function is |
| 185 | not updated, the metadata of the returned function will reflect the wrapper |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 186 | definition rather than the original function definition, which is typically less |
| 187 | than helpful. |
| 188 | |
Nick Coghlan | 9887683 | 2010-08-17 06:17:18 +0000 | [diff] [blame] | 189 | :func:`update_wrapper` may be used with callables other than functions. Any |
| 190 | attributes named in *assigned* or *updated* that are missing from the object |
| 191 | being wrapped are ignored (i.e. this function will not attempt to set them |
| 192 | on the wrapper function). :exc:`AttributeError` is still raised if the |
| 193 | wrapper function itself is missing any attributes named in *updated*. |
| 194 | |
| 195 | .. versionadded:: 3.2 |
Georg Brandl | 9e25701 | 2010-08-17 14:11:59 +0000 | [diff] [blame] | 196 | Automatic addition of the ``__wrapped__`` attribute. |
Nick Coghlan | 9887683 | 2010-08-17 06:17:18 +0000 | [diff] [blame] | 197 | |
| 198 | .. versionadded:: 3.2 |
Georg Brandl | 9e25701 | 2010-08-17 14:11:59 +0000 | [diff] [blame] | 199 | Copying of the ``__annotations__`` attribute by default. |
Nick Coghlan | 9887683 | 2010-08-17 06:17:18 +0000 | [diff] [blame] | 200 | |
| 201 | .. versionchanged:: 3.2 |
Georg Brandl | 9e25701 | 2010-08-17 14:11:59 +0000 | [diff] [blame] | 202 | Missing attributes no longer trigger an :exc:`AttributeError`. |
| 203 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 204 | |
Georg Brandl | 8a1caa2 | 2010-07-29 16:01:11 +0000 | [diff] [blame] | 205 | .. decorator:: wraps(wrapped, assigned=WRAPPER_ASSIGNMENTS, updated=WRAPPER_UPDATES) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 206 | |
| 207 | This is a convenience function for invoking ``partial(update_wrapper, |
| 208 | wrapped=wrapped, assigned=assigned, updated=updated)`` as a function decorator |
Christian Heimes | fe337bf | 2008-03-23 21:54:12 +0000 | [diff] [blame] | 209 | when defining a wrapper function. For example: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 210 | |
Christian Heimes | fe337bf | 2008-03-23 21:54:12 +0000 | [diff] [blame] | 211 | >>> from functools import wraps |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 212 | >>> def my_decorator(f): |
| 213 | ... @wraps(f) |
| 214 | ... def wrapper(*args, **kwds): |
Georg Brandl | 6911e3c | 2007-09-04 07:15:32 +0000 | [diff] [blame] | 215 | ... print('Calling decorated function') |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 216 | ... return f(*args, **kwds) |
| 217 | ... return wrapper |
| 218 | ... |
| 219 | >>> @my_decorator |
| 220 | ... def example(): |
| 221 | ... """Docstring""" |
Georg Brandl | 6911e3c | 2007-09-04 07:15:32 +0000 | [diff] [blame] | 222 | ... print('Called example function') |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 223 | ... |
| 224 | >>> example() |
| 225 | Calling decorated function |
| 226 | Called example function |
| 227 | >>> example.__name__ |
| 228 | 'example' |
| 229 | >>> example.__doc__ |
| 230 | 'Docstring' |
| 231 | |
| 232 | Without the use of this decorator factory, the name of the example function |
| 233 | would have been ``'wrapper'``, and the docstring of the original :func:`example` |
| 234 | would have been lost. |
| 235 | |
| 236 | |
| 237 | .. _partial-objects: |
| 238 | |
| 239 | :class:`partial` Objects |
| 240 | ------------------------ |
| 241 | |
| 242 | :class:`partial` objects are callable objects created by :func:`partial`. They |
| 243 | have three read-only attributes: |
| 244 | |
| 245 | |
| 246 | .. attribute:: partial.func |
| 247 | |
| 248 | A callable object or function. Calls to the :class:`partial` object will be |
| 249 | forwarded to :attr:`func` with new arguments and keywords. |
| 250 | |
| 251 | |
| 252 | .. attribute:: partial.args |
| 253 | |
| 254 | The leftmost positional arguments that will be prepended to the positional |
| 255 | arguments provided to a :class:`partial` object call. |
| 256 | |
| 257 | |
| 258 | .. attribute:: partial.keywords |
| 259 | |
| 260 | The keyword arguments that will be supplied when the :class:`partial` object is |
| 261 | called. |
| 262 | |
| 263 | :class:`partial` objects are like :class:`function` objects in that they are |
| 264 | callable, weak referencable, and can have attributes. There are some important |
| 265 | differences. For instance, the :attr:`__name__` and :attr:`__doc__` attributes |
| 266 | are not created automatically. Also, :class:`partial` objects defined in |
| 267 | classes behave like static methods and do not transform into bound methods |
| 268 | during instance attribute look-up. |
| 269 | |