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