Georg Brandl | 6c89a79 | 2012-01-25 22:36:25 +0100 | [diff] [blame] | 1 | :mod:`functools` --- Higher-order functions and operations on callable objects |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 2 | ============================================================================== |
| 3 | |
| 4 | .. module:: functools |
Georg Brandl | 6c89a79 | 2012-01-25 22:36:25 +0100 | [diff] [blame] | 5 | :synopsis: Higher-order functions and operations on callable objects. |
Terry Jan Reedy | fa089b9 | 2016-06-11 15:02:54 -0400 | [diff] [blame] | 6 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 7 | .. moduleauthor:: Peter Harris <scav@blueyonder.co.uk> |
| 8 | .. moduleauthor:: Raymond Hettinger <python@rcn.com> |
| 9 | .. moduleauthor:: Nick Coghlan <ncoghlan@gmail.com> |
Łukasz Langa | 6f69251 | 2013-06-05 12:20:24 +0200 | [diff] [blame] | 10 | .. moduleauthor:: Łukasz Langa <lukasz@langa.pl> |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 11 | .. sectionauthor:: Peter Harris <scav@blueyonder.co.uk> |
| 12 | |
Raymond Hettinger | 05ce079 | 2011-01-10 21:16:07 +0000 | [diff] [blame] | 13 | **Source code:** :source:`Lib/functools.py` |
| 14 | |
| 15 | -------------- |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 16 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 17 | The :mod:`functools` module is for higher-order functions: functions that act on |
| 18 | or return other functions. In general, any callable object can be treated as a |
| 19 | function for the purposes of this module. |
| 20 | |
Thomas Wouters | ed03b41 | 2007-08-28 21:37:11 +0000 | [diff] [blame] | 21 | The :mod:`functools` module defines the following functions: |
| 22 | |
Carl Meyer | d658dea | 2018-08-28 01:11:56 -0600 | [diff] [blame] | 23 | .. decorator:: cached_property(func) |
| 24 | |
| 25 | Transform a method of a class into a property whose value is computed once |
| 26 | and then cached as a normal attribute for the life of the instance. Similar |
| 27 | to :func:`property`, with the addition of caching. Useful for expensive |
| 28 | computed properties of instances that are otherwise effectively immutable. |
| 29 | |
| 30 | Example:: |
| 31 | |
| 32 | class DataSet: |
| 33 | def __init__(self, sequence_of_numbers): |
| 34 | self._data = sequence_of_numbers |
| 35 | |
| 36 | @cached_property |
| 37 | def stdev(self): |
| 38 | return statistics.stdev(self._data) |
| 39 | |
| 40 | @cached_property |
| 41 | def variance(self): |
| 42 | return statistics.variance(self._data) |
| 43 | |
| 44 | .. versionadded:: 3.8 |
| 45 | |
| 46 | .. note:: |
| 47 | |
| 48 | This decorator requires that the ``__dict__`` attribute on each instance |
| 49 | be a mutable mapping. This means it will not work with some types, such as |
| 50 | metaclasses (since the ``__dict__`` attributes on type instances are |
| 51 | read-only proxies for the class namespace), and those that specify |
| 52 | ``__slots__`` without including ``__dict__`` as one of the defined slots |
| 53 | (as such classes don't provide a ``__dict__`` attribute at all). |
| 54 | |
| 55 | |
Éric Araujo | b10089e | 2010-11-18 14:22:08 +0000 | [diff] [blame] | 56 | .. function:: cmp_to_key(func) |
Raymond Hettinger | c50846a | 2010-04-05 18:56:31 +0000 | [diff] [blame] | 57 | |
Raymond Hettinger | 86e9b6b | 2014-11-09 17:20:56 -0800 | [diff] [blame] | 58 | Transform an old-style comparison function to a :term:`key function`. Used |
| 59 | with tools that accept key functions (such as :func:`sorted`, :func:`min`, |
Benjamin Peterson | cca6531 | 2010-08-09 02:13:10 +0000 | [diff] [blame] | 60 | :func:`max`, :func:`heapq.nlargest`, :func:`heapq.nsmallest`, |
| 61 | :func:`itertools.groupby`). This function is primarily used as a transition |
Ezio Melotti | 9ecb6be | 2012-01-16 08:28:54 +0200 | [diff] [blame] | 62 | tool for programs being converted from Python 2 which supported the use of |
Benjamin Peterson | cca6531 | 2010-08-09 02:13:10 +0000 | [diff] [blame] | 63 | comparison functions. |
Raymond Hettinger | c50846a | 2010-04-05 18:56:31 +0000 | [diff] [blame] | 64 | |
Georg Brandl | 6c89a79 | 2012-01-25 22:36:25 +0100 | [diff] [blame] | 65 | A comparison function is any callable that accept two arguments, compares them, |
Benjamin Peterson | cca6531 | 2010-08-09 02:13:10 +0000 | [diff] [blame] | 66 | and returns a negative number for less-than, zero for equality, or a positive |
| 67 | number for greater-than. A key function is a callable that accepts one |
Raymond Hettinger | 86e9b6b | 2014-11-09 17:20:56 -0800 | [diff] [blame] | 68 | argument and returns another value to be used as the sort key. |
Raymond Hettinger | c50846a | 2010-04-05 18:56:31 +0000 | [diff] [blame] | 69 | |
Benjamin Peterson | cca6531 | 2010-08-09 02:13:10 +0000 | [diff] [blame] | 70 | Example:: |
Raymond Hettinger | c50846a | 2010-04-05 18:56:31 +0000 | [diff] [blame] | 71 | |
Benjamin Peterson | cca6531 | 2010-08-09 02:13:10 +0000 | [diff] [blame] | 72 | sorted(iterable, key=cmp_to_key(locale.strcoll)) # locale-aware sort order |
Raymond Hettinger | c50846a | 2010-04-05 18:56:31 +0000 | [diff] [blame] | 73 | |
Raymond Hettinger | 86e9b6b | 2014-11-09 17:20:56 -0800 | [diff] [blame] | 74 | For sorting examples and a brief sorting tutorial, see :ref:`sortinghowto`. |
| 75 | |
Raymond Hettinger | c50846a | 2010-04-05 18:56:31 +0000 | [diff] [blame] | 76 | .. versionadded:: 3.2 |
| 77 | |
Georg Brandl | 67b21b7 | 2010-08-17 15:07:14 +0000 | [diff] [blame] | 78 | |
Raymond Hettinger | 010ce32 | 2012-05-19 21:20:48 -0700 | [diff] [blame] | 79 | .. decorator:: lru_cache(maxsize=128, typed=False) |
Georg Brandl | 2e7346a | 2010-07-31 18:09:23 +0000 | [diff] [blame] | 80 | |
| 81 | Decorator to wrap a function with a memoizing callable that saves up to the |
| 82 | *maxsize* most recent calls. It can save time when an expensive or I/O bound |
| 83 | function is periodically called with the same arguments. |
| 84 | |
Raymond Hettinger | 7496b41 | 2010-11-30 19:15:45 +0000 | [diff] [blame] | 85 | Since a dictionary is used to cache results, the positional and keyword |
| 86 | arguments to the function must be hashable. |
Georg Brandl | 2e7346a | 2010-07-31 18:09:23 +0000 | [diff] [blame] | 87 | |
Raymond Hettinger | 902bcd9 | 2018-09-14 00:53:20 -0700 | [diff] [blame] | 88 | Distinct argument patterns may be considered to be distinct calls with |
| 89 | separate cache entries. For example, `f(a=1, b=2)` and `f(b=2, a=1)` |
| 90 | differ in their keyword argument order and may have two separate cache |
| 91 | entries. |
| 92 | |
Serhiy Storchaka | ecf41da | 2016-10-19 16:29:26 +0300 | [diff] [blame] | 93 | If *maxsize* is set to ``None``, the LRU feature is disabled and the cache can |
Raymond Hettinger | 7d74eff | 2012-06-04 00:32:15 -0700 | [diff] [blame] | 94 | grow without bound. The LRU feature performs best when *maxsize* is a |
| 95 | power-of-two. |
Raymond Hettinger | c79fb0e | 2010-12-01 03:45:41 +0000 | [diff] [blame] | 96 | |
Serhiy Storchaka | 4adf01c | 2016-10-19 18:30:05 +0300 | [diff] [blame] | 97 | If *typed* is set to true, function arguments of different types will be |
Raymond Hettinger | cd9fdfd | 2011-10-20 08:57:45 -0700 | [diff] [blame] | 98 | cached separately. For example, ``f(3)`` and ``f(3.0)`` will be treated |
| 99 | as distinct calls with distinct results. |
| 100 | |
Raymond Hettinger | 7496b41 | 2010-11-30 19:15:45 +0000 | [diff] [blame] | 101 | To help measure the effectiveness of the cache and tune the *maxsize* |
| 102 | parameter, the wrapped function is instrumented with a :func:`cache_info` |
| 103 | function that returns a :term:`named tuple` showing *hits*, *misses*, |
Raymond Hettinger | c79fb0e | 2010-12-01 03:45:41 +0000 | [diff] [blame] | 104 | *maxsize* and *currsize*. In a multi-threaded environment, the hits |
| 105 | and misses are approximate. |
Nick Coghlan | 234515a | 2010-11-30 06:19:46 +0000 | [diff] [blame] | 106 | |
Raymond Hettinger | 7496b41 | 2010-11-30 19:15:45 +0000 | [diff] [blame] | 107 | The decorator also provides a :func:`cache_clear` function for clearing or |
| 108 | invalidating the cache. |
Georg Brandl | 2e7346a | 2010-07-31 18:09:23 +0000 | [diff] [blame] | 109 | |
Raymond Hettinger | 3fccfcb | 2010-08-17 19:19:29 +0000 | [diff] [blame] | 110 | The original underlying function is accessible through the |
Raymond Hettinger | 7496b41 | 2010-11-30 19:15:45 +0000 | [diff] [blame] | 111 | :attr:`__wrapped__` attribute. This is useful for introspection, for |
| 112 | bypassing the cache, or for rewrapping the function with a different cache. |
Nick Coghlan | 9887683 | 2010-08-17 06:17:18 +0000 | [diff] [blame] | 113 | |
Raymond Hettinger | cc03858 | 2010-11-30 20:02:57 +0000 | [diff] [blame] | 114 | An `LRU (least recently used) cache |
Georg Brandl | 5d94134 | 2016-02-26 19:37:12 +0100 | [diff] [blame] | 115 | <https://en.wikipedia.org/wiki/Cache_algorithms#Examples>`_ works |
Raymond Hettinger | cd9fdfd | 2011-10-20 08:57:45 -0700 | [diff] [blame] | 116 | best when the most recent calls are the best predictors of upcoming calls (for |
| 117 | example, the most popular articles on a news server tend to change each day). |
Raymond Hettinger | 7496b41 | 2010-11-30 19:15:45 +0000 | [diff] [blame] | 118 | The cache's size limit assures that the cache does not grow without bound on |
| 119 | long-running processes such as web servers. |
| 120 | |
Raymond Hettinger | f0e0f20 | 2018-11-25 16:24:52 -0800 | [diff] [blame^] | 121 | In general, the LRU cache should only be used when you want to reuse |
| 122 | previously computed values. Accordingly, it doesn't make sense to cache |
| 123 | functions with side-effects, functions that need to create distinct mutable |
| 124 | objects on each call, or impure functions such as time() or random(). |
| 125 | |
Raymond Hettinger | cc03858 | 2010-11-30 20:02:57 +0000 | [diff] [blame] | 126 | Example of an LRU cache for static web content:: |
Raymond Hettinger | 7496b41 | 2010-11-30 19:15:45 +0000 | [diff] [blame] | 127 | |
Raymond Hettinger | 17328e4 | 2013-04-06 20:27:33 -0700 | [diff] [blame] | 128 | @lru_cache(maxsize=32) |
Raymond Hettinger | 7496b41 | 2010-11-30 19:15:45 +0000 | [diff] [blame] | 129 | def get_pep(num): |
| 130 | 'Retrieve text of a Python Enhancement Proposal' |
| 131 | resource = 'http://www.python.org/dev/peps/pep-%04d/' % num |
| 132 | try: |
| 133 | with urllib.request.urlopen(resource) as s: |
| 134 | return s.read() |
| 135 | except urllib.error.HTTPError: |
| 136 | return 'Not Found' |
| 137 | |
| 138 | >>> for n in 8, 290, 308, 320, 8, 218, 320, 279, 289, 320, 9991: |
| 139 | ... pep = get_pep(n) |
| 140 | ... print(n, len(pep)) |
| 141 | |
Raymond Hettinger | 17328e4 | 2013-04-06 20:27:33 -0700 | [diff] [blame] | 142 | >>> get_pep.cache_info() |
| 143 | CacheInfo(hits=3, misses=8, maxsize=32, currsize=8) |
Georg Brandl | 2e7346a | 2010-07-31 18:09:23 +0000 | [diff] [blame] | 144 | |
Raymond Hettinger | c79fb0e | 2010-12-01 03:45:41 +0000 | [diff] [blame] | 145 | Example of efficiently computing |
Georg Brandl | 5d94134 | 2016-02-26 19:37:12 +0100 | [diff] [blame] | 146 | `Fibonacci numbers <https://en.wikipedia.org/wiki/Fibonacci_number>`_ |
Raymond Hettinger | c79fb0e | 2010-12-01 03:45:41 +0000 | [diff] [blame] | 147 | using a cache to implement a |
Georg Brandl | 5d94134 | 2016-02-26 19:37:12 +0100 | [diff] [blame] | 148 | `dynamic programming <https://en.wikipedia.org/wiki/Dynamic_programming>`_ |
Raymond Hettinger | c79fb0e | 2010-12-01 03:45:41 +0000 | [diff] [blame] | 149 | technique:: |
| 150 | |
| 151 | @lru_cache(maxsize=None) |
| 152 | def fib(n): |
| 153 | if n < 2: |
| 154 | return n |
| 155 | return fib(n-1) + fib(n-2) |
| 156 | |
Raymond Hettinger | 17328e4 | 2013-04-06 20:27:33 -0700 | [diff] [blame] | 157 | >>> [fib(n) for n in range(16)] |
Raymond Hettinger | c79fb0e | 2010-12-01 03:45:41 +0000 | [diff] [blame] | 158 | [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610] |
| 159 | |
Raymond Hettinger | 17328e4 | 2013-04-06 20:27:33 -0700 | [diff] [blame] | 160 | >>> fib.cache_info() |
Raymond Hettinger | c79fb0e | 2010-12-01 03:45:41 +0000 | [diff] [blame] | 161 | CacheInfo(hits=28, misses=16, maxsize=None, currsize=16) |
| 162 | |
Georg Brandl | 2e7346a | 2010-07-31 18:09:23 +0000 | [diff] [blame] | 163 | .. versionadded:: 3.2 |
| 164 | |
Raymond Hettinger | cd9fdfd | 2011-10-20 08:57:45 -0700 | [diff] [blame] | 165 | .. versionchanged:: 3.3 |
| 166 | Added the *typed* option. |
| 167 | |
Georg Brandl | 8a1caa2 | 2010-07-29 16:01:11 +0000 | [diff] [blame] | 168 | .. decorator:: total_ordering |
Raymond Hettinger | c50846a | 2010-04-05 18:56:31 +0000 | [diff] [blame] | 169 | |
| 170 | Given a class defining one or more rich comparison ordering methods, this |
Benjamin Peterson | 08bf91c | 2010-04-11 16:12:57 +0000 | [diff] [blame] | 171 | class decorator supplies the rest. This simplifies the effort involved |
Raymond Hettinger | c50846a | 2010-04-05 18:56:31 +0000 | [diff] [blame] | 172 | in specifying all of the possible rich comparison operations: |
| 173 | |
| 174 | The class must define one of :meth:`__lt__`, :meth:`__le__`, |
| 175 | :meth:`__gt__`, or :meth:`__ge__`. |
| 176 | In addition, the class should supply an :meth:`__eq__` method. |
| 177 | |
| 178 | For example:: |
| 179 | |
| 180 | @total_ordering |
| 181 | class Student: |
Nick Coghlan | f05d981 | 2013-10-02 00:02:03 +1000 | [diff] [blame] | 182 | def _is_valid_operand(self, other): |
| 183 | return (hasattr(other, "lastname") and |
| 184 | hasattr(other, "firstname")) |
Raymond Hettinger | c50846a | 2010-04-05 18:56:31 +0000 | [diff] [blame] | 185 | def __eq__(self, other): |
Nick Coghlan | f05d981 | 2013-10-02 00:02:03 +1000 | [diff] [blame] | 186 | if not self._is_valid_operand(other): |
| 187 | return NotImplemented |
Raymond Hettinger | c50846a | 2010-04-05 18:56:31 +0000 | [diff] [blame] | 188 | return ((self.lastname.lower(), self.firstname.lower()) == |
| 189 | (other.lastname.lower(), other.firstname.lower())) |
| 190 | def __lt__(self, other): |
Nick Coghlan | f05d981 | 2013-10-02 00:02:03 +1000 | [diff] [blame] | 191 | if not self._is_valid_operand(other): |
| 192 | return NotImplemented |
Raymond Hettinger | c50846a | 2010-04-05 18:56:31 +0000 | [diff] [blame] | 193 | return ((self.lastname.lower(), self.firstname.lower()) < |
| 194 | (other.lastname.lower(), other.firstname.lower())) |
| 195 | |
Nick Coghlan | f05d981 | 2013-10-02 00:02:03 +1000 | [diff] [blame] | 196 | .. note:: |
| 197 | |
| 198 | While this decorator makes it easy to create well behaved totally |
| 199 | ordered types, it *does* come at the cost of slower execution and |
| 200 | more complex stack traces for the derived comparison methods. If |
| 201 | performance benchmarking indicates this is a bottleneck for a given |
| 202 | application, implementing all six rich comparison methods instead is |
| 203 | likely to provide an easy speed boost. |
| 204 | |
Raymond Hettinger | c50846a | 2010-04-05 18:56:31 +0000 | [diff] [blame] | 205 | .. versionadded:: 3.2 |
| 206 | |
Nick Coghlan | f05d981 | 2013-10-02 00:02:03 +1000 | [diff] [blame] | 207 | .. versionchanged:: 3.4 |
| 208 | Returning NotImplemented from the underlying comparison function for |
| 209 | unrecognised types is now supported. |
Georg Brandl | 67b21b7 | 2010-08-17 15:07:14 +0000 | [diff] [blame] | 210 | |
Georg Brandl | 036490d | 2009-05-17 13:00:36 +0000 | [diff] [blame] | 211 | .. function:: partial(func, *args, **keywords) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 212 | |
Andrei Petre | 83a0765 | 2018-10-22 23:11:20 -0700 | [diff] [blame] | 213 | Return a new :ref:`partial object<partial-objects>` which when called |
| 214 | will behave like *func* called with the positional arguments *args* |
| 215 | and keyword arguments *keywords*. If more arguments are supplied to the |
| 216 | call, they are appended to *args*. If additional keyword arguments are |
| 217 | supplied, they extend and override *keywords*. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 218 | Roughly equivalent to:: |
| 219 | |
| 220 | def partial(func, *args, **keywords): |
| 221 | def newfunc(*fargs, **fkeywords): |
Sergey Fedoseev | b981fec | 2018-10-20 02:42:07 +0500 | [diff] [blame] | 222 | newkeywords = {**keywords, **fkeywords} |
Martin Panter | 0c0da48 | 2016-06-12 01:46:50 +0000 | [diff] [blame] | 223 | return func(*args, *fargs, **newkeywords) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 224 | newfunc.func = func |
| 225 | newfunc.args = args |
| 226 | newfunc.keywords = keywords |
| 227 | return newfunc |
| 228 | |
| 229 | The :func:`partial` is used for partial function application which "freezes" |
| 230 | some portion of a function's arguments and/or keywords resulting in a new object |
| 231 | with a simplified signature. For example, :func:`partial` can be used to create |
| 232 | 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] | 233 | defaults to two: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 234 | |
Christian Heimes | fe337bf | 2008-03-23 21:54:12 +0000 | [diff] [blame] | 235 | >>> from functools import partial |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 236 | >>> basetwo = partial(int, base=2) |
| 237 | >>> basetwo.__doc__ = 'Convert base 2 string to an int.' |
| 238 | >>> basetwo('10010') |
| 239 | 18 |
| 240 | |
| 241 | |
Nick Coghlan | f4cb48a | 2013-11-03 16:41:46 +1000 | [diff] [blame] | 242 | .. class:: partialmethod(func, *args, **keywords) |
| 243 | |
| 244 | Return a new :class:`partialmethod` descriptor which behaves |
| 245 | like :class:`partial` except that it is designed to be used as a method |
| 246 | definition rather than being directly callable. |
| 247 | |
| 248 | *func* must be a :term:`descriptor` or a callable (objects which are both, |
| 249 | like normal functions, are handled as descriptors). |
| 250 | |
| 251 | When *func* is a descriptor (such as a normal Python function, |
| 252 | :func:`classmethod`, :func:`staticmethod`, :func:`abstractmethod` or |
| 253 | another instance of :class:`partialmethod`), calls to ``__get__`` are |
| 254 | delegated to the underlying descriptor, and an appropriate |
Andrei Petre | 83a0765 | 2018-10-22 23:11:20 -0700 | [diff] [blame] | 255 | :ref:`partial object<partial-objects>` returned as the result. |
Nick Coghlan | f4cb48a | 2013-11-03 16:41:46 +1000 | [diff] [blame] | 256 | |
| 257 | When *func* is a non-descriptor callable, an appropriate bound method is |
| 258 | created dynamically. This behaves like a normal Python function when |
| 259 | used as a method: the *self* argument will be inserted as the first |
| 260 | positional argument, even before the *args* and *keywords* supplied to |
| 261 | the :class:`partialmethod` constructor. |
| 262 | |
| 263 | Example:: |
| 264 | |
| 265 | >>> class Cell(object): |
Benjamin Peterson | 3a43403 | 2014-03-30 15:07:09 -0400 | [diff] [blame] | 266 | ... def __init__(self): |
| 267 | ... self._alive = False |
Nick Coghlan | f4cb48a | 2013-11-03 16:41:46 +1000 | [diff] [blame] | 268 | ... @property |
| 269 | ... def alive(self): |
| 270 | ... return self._alive |
| 271 | ... def set_state(self, state): |
| 272 | ... self._alive = bool(state) |
Nick Coghlan | 3daaf5f | 2013-11-04 23:32:16 +1000 | [diff] [blame] | 273 | ... set_alive = partialmethod(set_state, True) |
| 274 | ... set_dead = partialmethod(set_state, False) |
Nick Coghlan | f4cb48a | 2013-11-03 16:41:46 +1000 | [diff] [blame] | 275 | ... |
| 276 | >>> c = Cell() |
| 277 | >>> c.alive |
| 278 | False |
| 279 | >>> c.set_alive() |
| 280 | >>> c.alive |
| 281 | True |
| 282 | |
| 283 | .. versionadded:: 3.4 |
| 284 | |
| 285 | |
Georg Brandl | 58f9e4f | 2008-04-19 22:18:33 +0000 | [diff] [blame] | 286 | .. function:: reduce(function, iterable[, initializer]) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 287 | |
Brendan Jurd | 9df1002 | 2018-10-01 16:52:10 +1000 | [diff] [blame] | 288 | Apply *function* of two arguments cumulatively to the items of *iterable*, from |
| 289 | left to right, so as to reduce the iterable to a single value. For example, |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 290 | ``reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])`` calculates ``((((1+2)+3)+4)+5)``. |
| 291 | The left argument, *x*, is the accumulated value and the right argument, *y*, is |
Brendan Jurd | 9df1002 | 2018-10-01 16:52:10 +1000 | [diff] [blame] | 292 | the update value from the *iterable*. If the optional *initializer* is present, |
| 293 | it is placed before the items of the iterable in the calculation, and serves as |
| 294 | a default when the iterable is empty. If *initializer* is not given and |
| 295 | *iterable* contains only one item, the first item is returned. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 296 | |
Raymond Hettinger | 558dcf3 | 2014-12-16 18:16:57 -0800 | [diff] [blame] | 297 | Roughly equivalent to:: |
Raymond Hettinger | 6480168 | 2013-10-12 16:04:17 -0700 | [diff] [blame] | 298 | |
| 299 | def reduce(function, iterable, initializer=None): |
| 300 | it = iter(iterable) |
| 301 | if initializer is None: |
| 302 | value = next(it) |
| 303 | else: |
| 304 | value = initializer |
| 305 | for element in it: |
| 306 | value = function(value, element) |
| 307 | return value |
| 308 | |
Gerrit Holl | bd81cbd | 2018-07-04 23:26:32 +0100 | [diff] [blame] | 309 | See :func:`itertools.accumulate` for an iterator that yields all intermediate |
| 310 | values. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 311 | |
Daisuke Miyakawa | 0e61e67 | 2017-10-12 23:39:43 +0900 | [diff] [blame] | 312 | .. decorator:: singledispatch |
Łukasz Langa | 6f69251 | 2013-06-05 12:20:24 +0200 | [diff] [blame] | 313 | |
Daisuke Miyakawa | 0e61e67 | 2017-10-12 23:39:43 +0900 | [diff] [blame] | 314 | Transform a function into a :term:`single-dispatch <single |
Łukasz Langa | fdcf2b7 | 2013-06-07 22:54:03 +0200 | [diff] [blame] | 315 | dispatch>` :term:`generic function`. |
Łukasz Langa | 6f69251 | 2013-06-05 12:20:24 +0200 | [diff] [blame] | 316 | |
| 317 | To define a generic function, decorate it with the ``@singledispatch`` |
| 318 | decorator. Note that the dispatch happens on the type of the first argument, |
| 319 | create your function accordingly:: |
| 320 | |
| 321 | >>> from functools import singledispatch |
| 322 | >>> @singledispatch |
| 323 | ... def fun(arg, verbose=False): |
| 324 | ... if verbose: |
| 325 | ... print("Let me just say,", end=" ") |
| 326 | ... print(arg) |
| 327 | |
| 328 | To add overloaded implementations to the function, use the :func:`register` |
Łukasz Langa | e569753 | 2017-12-11 13:56:31 -0800 | [diff] [blame] | 329 | attribute of the generic function. It is a decorator. For functions |
| 330 | annotated with types, the decorator will infer the type of the first |
| 331 | argument automatically:: |
Łukasz Langa | 6f69251 | 2013-06-05 12:20:24 +0200 | [diff] [blame] | 332 | |
Łukasz Langa | e569753 | 2017-12-11 13:56:31 -0800 | [diff] [blame] | 333 | >>> @fun.register |
| 334 | ... def _(arg: int, verbose=False): |
Łukasz Langa | 6f69251 | 2013-06-05 12:20:24 +0200 | [diff] [blame] | 335 | ... if verbose: |
| 336 | ... print("Strength in numbers, eh?", end=" ") |
| 337 | ... print(arg) |
| 338 | ... |
Łukasz Langa | e569753 | 2017-12-11 13:56:31 -0800 | [diff] [blame] | 339 | >>> @fun.register |
| 340 | ... def _(arg: list, verbose=False): |
Łukasz Langa | 6f69251 | 2013-06-05 12:20:24 +0200 | [diff] [blame] | 341 | ... if verbose: |
| 342 | ... print("Enumerate this:") |
| 343 | ... for i, elem in enumerate(arg): |
| 344 | ... print(i, elem) |
| 345 | |
Łukasz Langa | e569753 | 2017-12-11 13:56:31 -0800 | [diff] [blame] | 346 | For code which doesn't use type annotations, the appropriate type |
| 347 | argument can be passed explicitly to the decorator itself:: |
| 348 | |
| 349 | >>> @fun.register(complex) |
| 350 | ... def _(arg, verbose=False): |
| 351 | ... if verbose: |
| 352 | ... print("Better than complicated.", end=" ") |
| 353 | ... print(arg.real, arg.imag) |
| 354 | ... |
| 355 | |
| 356 | |
Łukasz Langa | 6f69251 | 2013-06-05 12:20:24 +0200 | [diff] [blame] | 357 | To enable registering lambdas and pre-existing functions, the |
| 358 | :func:`register` attribute can be used in a functional form:: |
| 359 | |
| 360 | >>> def nothing(arg, verbose=False): |
| 361 | ... print("Nothing.") |
| 362 | ... |
| 363 | >>> fun.register(type(None), nothing) |
| 364 | |
| 365 | The :func:`register` attribute returns the undecorated function which |
| 366 | enables decorator stacking, pickling, as well as creating unit tests for |
| 367 | each variant independently:: |
| 368 | |
| 369 | >>> @fun.register(float) |
| 370 | ... @fun.register(Decimal) |
| 371 | ... def fun_num(arg, verbose=False): |
| 372 | ... if verbose: |
| 373 | ... print("Half of your number:", end=" ") |
| 374 | ... print(arg / 2) |
| 375 | ... |
| 376 | >>> fun_num is fun |
| 377 | False |
| 378 | |
| 379 | When called, the generic function dispatches on the type of the first |
| 380 | argument:: |
| 381 | |
| 382 | >>> fun("Hello, world.") |
| 383 | Hello, world. |
| 384 | >>> fun("test.", verbose=True) |
| 385 | Let me just say, test. |
| 386 | >>> fun(42, verbose=True) |
| 387 | Strength in numbers, eh? 42 |
| 388 | >>> fun(['spam', 'spam', 'eggs', 'spam'], verbose=True) |
| 389 | Enumerate this: |
| 390 | 0 spam |
| 391 | 1 spam |
| 392 | 2 eggs |
| 393 | 3 spam |
| 394 | >>> fun(None) |
| 395 | Nothing. |
| 396 | >>> fun(1.23) |
| 397 | 0.615 |
| 398 | |
| 399 | Where there is no registered implementation for a specific type, its |
| 400 | method resolution order is used to find a more generic implementation. |
| 401 | The original function decorated with ``@singledispatch`` is registered |
| 402 | for the base ``object`` type, which means it is used if no better |
| 403 | implementation is found. |
| 404 | |
| 405 | To check which implementation will the generic function choose for |
| 406 | a given type, use the ``dispatch()`` attribute:: |
| 407 | |
| 408 | >>> fun.dispatch(float) |
| 409 | <function fun_num at 0x1035a2840> |
| 410 | >>> fun.dispatch(dict) # note: default implementation |
| 411 | <function fun at 0x103fe0000> |
| 412 | |
| 413 | To access all registered implementations, use the read-only ``registry`` |
| 414 | attribute:: |
| 415 | |
| 416 | >>> fun.registry.keys() |
| 417 | dict_keys([<class 'NoneType'>, <class 'int'>, <class 'object'>, |
| 418 | <class 'decimal.Decimal'>, <class 'list'>, |
| 419 | <class 'float'>]) |
| 420 | >>> fun.registry[float] |
| 421 | <function fun_num at 0x1035a2840> |
| 422 | >>> fun.registry[object] |
| 423 | <function fun at 0x103fe0000> |
| 424 | |
| 425 | .. versionadded:: 3.4 |
| 426 | |
Łukasz Langa | e569753 | 2017-12-11 13:56:31 -0800 | [diff] [blame] | 427 | .. versionchanged:: 3.7 |
| 428 | The :func:`register` attribute supports using type annotations. |
| 429 | |
Łukasz Langa | 6f69251 | 2013-06-05 12:20:24 +0200 | [diff] [blame] | 430 | |
Ethan Smith | c651275 | 2018-05-26 16:38:33 -0400 | [diff] [blame] | 431 | .. class:: singledispatchmethod(func) |
| 432 | |
| 433 | Transform a method into a :term:`single-dispatch <single |
| 434 | dispatch>` :term:`generic function`. |
| 435 | |
| 436 | To define a generic method, decorate it with the ``@singledispatchmethod`` |
| 437 | decorator. Note that the dispatch happens on the type of the first non-self |
| 438 | or non-cls argument, create your function accordingly:: |
| 439 | |
| 440 | class Negator: |
| 441 | @singledispatchmethod |
| 442 | def neg(self, arg): |
| 443 | raise NotImplementedError("Cannot negate a") |
| 444 | |
| 445 | @neg.register |
| 446 | def _(self, arg: int): |
| 447 | return -arg |
| 448 | |
| 449 | @neg.register |
| 450 | def _(self, arg: bool): |
| 451 | return not arg |
| 452 | |
| 453 | ``@singledispatchmethod`` supports nesting with other decorators such as |
| 454 | ``@classmethod``. Note that to allow for ``dispatcher.register``, |
| 455 | ``singledispatchmethod`` must be the *outer most* decorator. Here is the |
| 456 | ``Negator`` class with the ``neg`` methods being class bound:: |
| 457 | |
| 458 | class Negator: |
| 459 | @singledispatchmethod |
| 460 | @classmethod |
| 461 | def neg(cls, arg): |
| 462 | raise NotImplementedError("Cannot negate a") |
| 463 | |
| 464 | @neg.register |
| 465 | @classmethod |
| 466 | def _(cls, arg: int): |
| 467 | return -arg |
| 468 | |
| 469 | @neg.register |
| 470 | @classmethod |
| 471 | def _(cls, arg: bool): |
| 472 | return not arg |
| 473 | |
| 474 | The same pattern can be used for other similar decorators: ``staticmethod``, |
| 475 | ``abstractmethod``, and others. |
| 476 | |
Georg Brandl | 036490d | 2009-05-17 13:00:36 +0000 | [diff] [blame] | 477 | .. function:: update_wrapper(wrapper, wrapped, assigned=WRAPPER_ASSIGNMENTS, updated=WRAPPER_UPDATES) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 478 | |
| 479 | Update a *wrapper* function to look like the *wrapped* function. The optional |
| 480 | arguments are tuples to specify which attributes of the original function are |
| 481 | assigned directly to the matching attributes on the wrapper function and which |
| 482 | attributes of the wrapper function are updated with the corresponding attributes |
| 483 | from the original function. The default values for these arguments are the |
Berker Peksag | 472233e | 2016-04-18 21:20:50 +0300 | [diff] [blame] | 484 | module level constants ``WRAPPER_ASSIGNMENTS`` (which assigns to the wrapper |
| 485 | function's ``__module__``, ``__name__``, ``__qualname__``, ``__annotations__`` |
| 486 | and ``__doc__``, the documentation string) and ``WRAPPER_UPDATES`` (which |
| 487 | updates the wrapper function's ``__dict__``, i.e. the instance dictionary). |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 488 | |
Nick Coghlan | 9887683 | 2010-08-17 06:17:18 +0000 | [diff] [blame] | 489 | To allow access to the original function for introspection and other purposes |
| 490 | (e.g. bypassing a caching decorator such as :func:`lru_cache`), this function |
Nick Coghlan | 24c05bc | 2013-07-15 21:13:08 +1000 | [diff] [blame] | 491 | automatically adds a ``__wrapped__`` attribute to the wrapper that refers to |
| 492 | the function being wrapped. |
Nick Coghlan | 9887683 | 2010-08-17 06:17:18 +0000 | [diff] [blame] | 493 | |
Christian Heimes | d8654cf | 2007-12-02 15:22:16 +0000 | [diff] [blame] | 494 | The main intended use for this function is in :term:`decorator` functions which |
| 495 | wrap the decorated function and return the wrapper. If the wrapper function is |
| 496 | not updated, the metadata of the returned function will reflect the wrapper |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 497 | definition rather than the original function definition, which is typically less |
| 498 | than helpful. |
| 499 | |
Nick Coghlan | 9887683 | 2010-08-17 06:17:18 +0000 | [diff] [blame] | 500 | :func:`update_wrapper` may be used with callables other than functions. Any |
| 501 | attributes named in *assigned* or *updated* that are missing from the object |
| 502 | being wrapped are ignored (i.e. this function will not attempt to set them |
| 503 | on the wrapper function). :exc:`AttributeError` is still raised if the |
| 504 | wrapper function itself is missing any attributes named in *updated*. |
| 505 | |
| 506 | .. versionadded:: 3.2 |
Georg Brandl | 9e25701 | 2010-08-17 14:11:59 +0000 | [diff] [blame] | 507 | Automatic addition of the ``__wrapped__`` attribute. |
Nick Coghlan | 9887683 | 2010-08-17 06:17:18 +0000 | [diff] [blame] | 508 | |
| 509 | .. versionadded:: 3.2 |
Georg Brandl | 9e25701 | 2010-08-17 14:11:59 +0000 | [diff] [blame] | 510 | Copying of the ``__annotations__`` attribute by default. |
Nick Coghlan | 9887683 | 2010-08-17 06:17:18 +0000 | [diff] [blame] | 511 | |
| 512 | .. versionchanged:: 3.2 |
Georg Brandl | 9e25701 | 2010-08-17 14:11:59 +0000 | [diff] [blame] | 513 | Missing attributes no longer trigger an :exc:`AttributeError`. |
| 514 | |
Nick Coghlan | 24c05bc | 2013-07-15 21:13:08 +1000 | [diff] [blame] | 515 | .. versionchanged:: 3.4 |
| 516 | The ``__wrapped__`` attribute now always refers to the wrapped |
| 517 | function, even if that function defined a ``__wrapped__`` attribute. |
| 518 | (see :issue:`17482`) |
| 519 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 520 | |
Georg Brandl | 8a1caa2 | 2010-07-29 16:01:11 +0000 | [diff] [blame] | 521 | .. decorator:: wraps(wrapped, assigned=WRAPPER_ASSIGNMENTS, updated=WRAPPER_UPDATES) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 522 | |
Ezio Melotti | 67f6d5f | 2014-08-05 08:14:28 +0300 | [diff] [blame] | 523 | This is a convenience function for invoking :func:`update_wrapper` as a |
| 524 | function decorator when defining a wrapper function. It is equivalent to |
| 525 | ``partial(update_wrapper, wrapped=wrapped, assigned=assigned, updated=updated)``. |
| 526 | For example:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 527 | |
Christian Heimes | fe337bf | 2008-03-23 21:54:12 +0000 | [diff] [blame] | 528 | >>> from functools import wraps |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 529 | >>> def my_decorator(f): |
| 530 | ... @wraps(f) |
| 531 | ... def wrapper(*args, **kwds): |
Georg Brandl | 6911e3c | 2007-09-04 07:15:32 +0000 | [diff] [blame] | 532 | ... print('Calling decorated function') |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 533 | ... return f(*args, **kwds) |
| 534 | ... return wrapper |
| 535 | ... |
| 536 | >>> @my_decorator |
| 537 | ... def example(): |
| 538 | ... """Docstring""" |
Georg Brandl | 6911e3c | 2007-09-04 07:15:32 +0000 | [diff] [blame] | 539 | ... print('Called example function') |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 540 | ... |
| 541 | >>> example() |
| 542 | Calling decorated function |
| 543 | Called example function |
| 544 | >>> example.__name__ |
| 545 | 'example' |
| 546 | >>> example.__doc__ |
| 547 | 'Docstring' |
| 548 | |
| 549 | Without the use of this decorator factory, the name of the example function |
| 550 | would have been ``'wrapper'``, and the docstring of the original :func:`example` |
| 551 | would have been lost. |
| 552 | |
| 553 | |
| 554 | .. _partial-objects: |
| 555 | |
| 556 | :class:`partial` Objects |
| 557 | ------------------------ |
| 558 | |
| 559 | :class:`partial` objects are callable objects created by :func:`partial`. They |
| 560 | have three read-only attributes: |
| 561 | |
| 562 | |
| 563 | .. attribute:: partial.func |
| 564 | |
| 565 | A callable object or function. Calls to the :class:`partial` object will be |
| 566 | forwarded to :attr:`func` with new arguments and keywords. |
| 567 | |
| 568 | |
| 569 | .. attribute:: partial.args |
| 570 | |
| 571 | The leftmost positional arguments that will be prepended to the positional |
| 572 | arguments provided to a :class:`partial` object call. |
| 573 | |
| 574 | |
| 575 | .. attribute:: partial.keywords |
| 576 | |
| 577 | The keyword arguments that will be supplied when the :class:`partial` object is |
| 578 | called. |
| 579 | |
| 580 | :class:`partial` objects are like :class:`function` objects in that they are |
| 581 | callable, weak referencable, and can have attributes. There are some important |
Martin Panter | bae5d81 | 2016-06-18 03:57:31 +0000 | [diff] [blame] | 582 | differences. For instance, the :attr:`~definition.__name__` and :attr:`__doc__` attributes |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 583 | are not created automatically. Also, :class:`partial` objects defined in |
| 584 | classes behave like static methods and do not transform into bound methods |
| 585 | during instance attribute look-up. |