blob: f5c6608e1d465c6d75b4a0512affada7b364db3d [file] [log] [blame]
Georg Brandl6c89a792012-01-25 22:36:25 +01001:mod:`functools` --- Higher-order functions and operations on callable objects
Georg Brandl116aa622007-08-15 14:28:22 +00002==============================================================================
3
4.. module:: functools
Georg Brandl6c89a792012-01-25 22:36:25 +01005 :synopsis: Higher-order functions and operations on callable objects.
Georg Brandl116aa622007-08-15 14:28:22 +00006.. 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
Raymond Hettinger05ce0792011-01-10 21:16:07 +000011**Source code:** :source:`Lib/functools.py`
12
13--------------
Georg Brandl116aa622007-08-15 14:28:22 +000014
Georg Brandl116aa622007-08-15 14:28:22 +000015The :mod:`functools` module is for higher-order functions: functions that act on
16or return other functions. In general, any callable object can be treated as a
17function for the purposes of this module.
18
Thomas Woutersed03b412007-08-28 21:37:11 +000019The :mod:`functools` module defines the following functions:
20
Éric Araujob10089e2010-11-18 14:22:08 +000021.. function:: cmp_to_key(func)
Raymond Hettingerc50846a2010-04-05 18:56:31 +000022
Georg Brandl3b65fd72012-01-23 20:19:33 +010023 Transform an old-style comparison function to a key function. Used with
Benjamin Petersoncca65312010-08-09 02:13:10 +000024 tools that accept key functions (such as :func:`sorted`, :func:`min`,
25 :func:`max`, :func:`heapq.nlargest`, :func:`heapq.nsmallest`,
26 :func:`itertools.groupby`). This function is primarily used as a transition
Ezio Melotti9ecb6be2012-01-16 08:28:54 +020027 tool for programs being converted from Python 2 which supported the use of
Benjamin Petersoncca65312010-08-09 02:13:10 +000028 comparison functions.
Raymond Hettingerc50846a2010-04-05 18:56:31 +000029
Georg Brandl6c89a792012-01-25 22:36:25 +010030 A comparison function is any callable that accept two arguments, compares them,
Benjamin Petersoncca65312010-08-09 02:13:10 +000031 and returns a negative number for less-than, zero for equality, or a positive
32 number for greater-than. A key function is a callable that accepts one
Raymond Hettingerc79fb0e2010-12-01 03:45:41 +000033 argument and returns another value indicating the position in the desired
Benjamin Petersoncca65312010-08-09 02:13:10 +000034 collation sequence.
Raymond Hettingerc50846a2010-04-05 18:56:31 +000035
Benjamin Petersoncca65312010-08-09 02:13:10 +000036 Example::
Raymond Hettingerc50846a2010-04-05 18:56:31 +000037
Benjamin Petersoncca65312010-08-09 02:13:10 +000038 sorted(iterable, key=cmp_to_key(locale.strcoll)) # locale-aware sort order
Raymond Hettingerc50846a2010-04-05 18:56:31 +000039
40 .. versionadded:: 3.2
41
Georg Brandl67b21b72010-08-17 15:07:14 +000042
Raymond Hettinger010ce322012-05-19 21:20:48 -070043.. decorator:: lru_cache(maxsize=128, typed=False)
Georg Brandl2e7346a2010-07-31 18:09:23 +000044
45 Decorator to wrap a function with a memoizing callable that saves up to the
46 *maxsize* most recent calls. It can save time when an expensive or I/O bound
47 function is periodically called with the same arguments.
48
Raymond Hettinger7496b412010-11-30 19:15:45 +000049 Since a dictionary is used to cache results, the positional and keyword
50 arguments to the function must be hashable.
Georg Brandl2e7346a2010-07-31 18:09:23 +000051
Raymond Hettinger7d74eff2012-06-04 00:32:15 -070052 If *maxsize* is set to None, the LRU feature is disabled and the cache can
53 grow without bound. The LRU feature performs best when *maxsize* is a
54 power-of-two.
Raymond Hettingerc79fb0e2010-12-01 03:45:41 +000055
Raymond Hettingercd9fdfd2011-10-20 08:57:45 -070056 If *typed* is set to True, function arguments of different types will be
57 cached separately. For example, ``f(3)`` and ``f(3.0)`` will be treated
58 as distinct calls with distinct results.
59
Raymond Hettinger7496b412010-11-30 19:15:45 +000060 To help measure the effectiveness of the cache and tune the *maxsize*
61 parameter, the wrapped function is instrumented with a :func:`cache_info`
62 function that returns a :term:`named tuple` showing *hits*, *misses*,
Raymond Hettingerc79fb0e2010-12-01 03:45:41 +000063 *maxsize* and *currsize*. In a multi-threaded environment, the hits
64 and misses are approximate.
Nick Coghlan234515a2010-11-30 06:19:46 +000065
Raymond Hettinger7496b412010-11-30 19:15:45 +000066 The decorator also provides a :func:`cache_clear` function for clearing or
67 invalidating the cache.
Georg Brandl2e7346a2010-07-31 18:09:23 +000068
Raymond Hettinger3fccfcb2010-08-17 19:19:29 +000069 The original underlying function is accessible through the
Raymond Hettinger7496b412010-11-30 19:15:45 +000070 :attr:`__wrapped__` attribute. This is useful for introspection, for
71 bypassing the cache, or for rewrapping the function with a different cache.
Nick Coghlan98876832010-08-17 06:17:18 +000072
Raymond Hettingercc038582010-11-30 20:02:57 +000073 An `LRU (least recently used) cache
Raymond Hettinger7496b412010-11-30 19:15:45 +000074 <http://en.wikipedia.org/wiki/Cache_algorithms#Least_Recently_Used>`_ works
Raymond Hettingercd9fdfd2011-10-20 08:57:45 -070075 best when the most recent calls are the best predictors of upcoming calls (for
76 example, the most popular articles on a news server tend to change each day).
Raymond Hettinger7496b412010-11-30 19:15:45 +000077 The cache's size limit assures that the cache does not grow without bound on
78 long-running processes such as web servers.
79
Raymond Hettingercc038582010-11-30 20:02:57 +000080 Example of an LRU cache for static web content::
Raymond Hettinger7496b412010-11-30 19:15:45 +000081
Raymond Hettingercc038582010-11-30 20:02:57 +000082 @lru_cache(maxsize=20)
Raymond Hettinger7496b412010-11-30 19:15:45 +000083 def get_pep(num):
84 'Retrieve text of a Python Enhancement Proposal'
85 resource = 'http://www.python.org/dev/peps/pep-%04d/' % num
86 try:
87 with urllib.request.urlopen(resource) as s:
88 return s.read()
89 except urllib.error.HTTPError:
90 return 'Not Found'
91
92 >>> for n in 8, 290, 308, 320, 8, 218, 320, 279, 289, 320, 9991:
93 ... pep = get_pep(n)
94 ... print(n, len(pep))
95
96 >>> print(get_pep.cache_info())
97 CacheInfo(hits=3, misses=8, maxsize=20, currsize=8)
Georg Brandl2e7346a2010-07-31 18:09:23 +000098
Raymond Hettingerc79fb0e2010-12-01 03:45:41 +000099 Example of efficiently computing
100 `Fibonacci numbers <http://en.wikipedia.org/wiki/Fibonacci_number>`_
101 using a cache to implement a
102 `dynamic programming <http://en.wikipedia.org/wiki/Dynamic_programming>`_
103 technique::
104
105 @lru_cache(maxsize=None)
106 def fib(n):
107 if n < 2:
108 return n
109 return fib(n-1) + fib(n-2)
110
111 >>> print([fib(n) for n in range(16)])
112 [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610]
113
114 >>> print(fib.cache_info())
115 CacheInfo(hits=28, misses=16, maxsize=None, currsize=16)
116
Georg Brandl2e7346a2010-07-31 18:09:23 +0000117 .. versionadded:: 3.2
118
Raymond Hettingercd9fdfd2011-10-20 08:57:45 -0700119 .. versionchanged:: 3.3
120 Added the *typed* option.
121
Georg Brandl8a1caa22010-07-29 16:01:11 +0000122.. decorator:: total_ordering
Raymond Hettingerc50846a2010-04-05 18:56:31 +0000123
124 Given a class defining one or more rich comparison ordering methods, this
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000125 class decorator supplies the rest. This simplifies the effort involved
Raymond Hettingerc50846a2010-04-05 18:56:31 +0000126 in specifying all of the possible rich comparison operations:
127
128 The class must define one of :meth:`__lt__`, :meth:`__le__`,
129 :meth:`__gt__`, or :meth:`__ge__`.
130 In addition, the class should supply an :meth:`__eq__` method.
131
132 For example::
133
134 @total_ordering
135 class Student:
136 def __eq__(self, other):
137 return ((self.lastname.lower(), self.firstname.lower()) ==
138 (other.lastname.lower(), other.firstname.lower()))
139 def __lt__(self, other):
140 return ((self.lastname.lower(), self.firstname.lower()) <
141 (other.lastname.lower(), other.firstname.lower()))
142
143 .. versionadded:: 3.2
144
Georg Brandl67b21b72010-08-17 15:07:14 +0000145
Georg Brandl036490d2009-05-17 13:00:36 +0000146.. function:: partial(func, *args, **keywords)
Georg Brandl116aa622007-08-15 14:28:22 +0000147
148 Return a new :class:`partial` object which when called will behave like *func*
149 called with the positional arguments *args* and keyword arguments *keywords*. If
150 more arguments are supplied to the call, they are appended to *args*. If
151 additional keyword arguments are supplied, they extend and override *keywords*.
152 Roughly equivalent to::
153
154 def partial(func, *args, **keywords):
155 def newfunc(*fargs, **fkeywords):
156 newkeywords = keywords.copy()
157 newkeywords.update(fkeywords)
158 return func(*(args + fargs), **newkeywords)
159 newfunc.func = func
160 newfunc.args = args
161 newfunc.keywords = keywords
162 return newfunc
163
164 The :func:`partial` is used for partial function application which "freezes"
165 some portion of a function's arguments and/or keywords resulting in a new object
166 with a simplified signature. For example, :func:`partial` can be used to create
167 a callable that behaves like the :func:`int` function where the *base* argument
Christian Heimesfe337bf2008-03-23 21:54:12 +0000168 defaults to two:
Georg Brandl116aa622007-08-15 14:28:22 +0000169
Christian Heimesfe337bf2008-03-23 21:54:12 +0000170 >>> from functools import partial
Georg Brandl116aa622007-08-15 14:28:22 +0000171 >>> basetwo = partial(int, base=2)
172 >>> basetwo.__doc__ = 'Convert base 2 string to an int.'
173 >>> basetwo('10010')
174 18
175
176
Georg Brandl58f9e4f2008-04-19 22:18:33 +0000177.. function:: reduce(function, iterable[, initializer])
Georg Brandl116aa622007-08-15 14:28:22 +0000178
179 Apply *function* of two arguments cumulatively to the items of *sequence*, from
180 left to right, so as to reduce the sequence to a single value. For example,
181 ``reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])`` calculates ``((((1+2)+3)+4)+5)``.
182 The left argument, *x*, is the accumulated value and the right argument, *y*, is
183 the update value from the *sequence*. If the optional *initializer* is present,
184 it is placed before the items of the sequence in the calculation, and serves as
185 a default when the sequence is empty. If *initializer* is not given and
186 *sequence* contains only one item, the first item is returned.
187
188
Georg Brandl036490d2009-05-17 13:00:36 +0000189.. function:: update_wrapper(wrapper, wrapped, assigned=WRAPPER_ASSIGNMENTS, updated=WRAPPER_UPDATES)
Georg Brandl116aa622007-08-15 14:28:22 +0000190
191 Update a *wrapper* function to look like the *wrapped* function. The optional
192 arguments are tuples to specify which attributes of the original function are
193 assigned directly to the matching attributes on the wrapper function and which
194 attributes of the wrapper function are updated with the corresponding attributes
195 from the original function. The default values for these arguments are the
196 module level constants *WRAPPER_ASSIGNMENTS* (which assigns to the wrapper
Antoine Pitrou560f7642010-08-04 18:28:02 +0000197 function's *__name__*, *__module__*, *__annotations__* and *__doc__*, the
198 documentation string) and *WRAPPER_UPDATES* (which updates the wrapper
199 function's *__dict__*, i.e. the instance dictionary).
Georg Brandl116aa622007-08-15 14:28:22 +0000200
Nick Coghlan98876832010-08-17 06:17:18 +0000201 To allow access to the original function for introspection and other purposes
202 (e.g. bypassing a caching decorator such as :func:`lru_cache`), this function
Éric Araujoc6ecb012010-11-06 06:33:03 +0000203 automatically adds a __wrapped__ attribute to the wrapper that refers to
Nick Coghlan98876832010-08-17 06:17:18 +0000204 the original function.
205
Christian Heimesd8654cf2007-12-02 15:22:16 +0000206 The main intended use for this function is in :term:`decorator` functions which
207 wrap the decorated function and return the wrapper. If the wrapper function is
208 not updated, the metadata of the returned function will reflect the wrapper
Georg Brandl116aa622007-08-15 14:28:22 +0000209 definition rather than the original function definition, which is typically less
210 than helpful.
211
Nick Coghlan98876832010-08-17 06:17:18 +0000212 :func:`update_wrapper` may be used with callables other than functions. Any
213 attributes named in *assigned* or *updated* that are missing from the object
214 being wrapped are ignored (i.e. this function will not attempt to set them
215 on the wrapper function). :exc:`AttributeError` is still raised if the
216 wrapper function itself is missing any attributes named in *updated*.
217
218 .. versionadded:: 3.2
Georg Brandl9e257012010-08-17 14:11:59 +0000219 Automatic addition of the ``__wrapped__`` attribute.
Nick Coghlan98876832010-08-17 06:17:18 +0000220
221 .. versionadded:: 3.2
Georg Brandl9e257012010-08-17 14:11:59 +0000222 Copying of the ``__annotations__`` attribute by default.
Nick Coghlan98876832010-08-17 06:17:18 +0000223
224 .. versionchanged:: 3.2
Georg Brandl9e257012010-08-17 14:11:59 +0000225 Missing attributes no longer trigger an :exc:`AttributeError`.
226
Georg Brandl116aa622007-08-15 14:28:22 +0000227
Georg Brandl8a1caa22010-07-29 16:01:11 +0000228.. decorator:: wraps(wrapped, assigned=WRAPPER_ASSIGNMENTS, updated=WRAPPER_UPDATES)
Georg Brandl116aa622007-08-15 14:28:22 +0000229
230 This is a convenience function for invoking ``partial(update_wrapper,
231 wrapped=wrapped, assigned=assigned, updated=updated)`` as a function decorator
Christian Heimesfe337bf2008-03-23 21:54:12 +0000232 when defining a wrapper function. For example:
Georg Brandl116aa622007-08-15 14:28:22 +0000233
Christian Heimesfe337bf2008-03-23 21:54:12 +0000234 >>> from functools import wraps
Georg Brandl116aa622007-08-15 14:28:22 +0000235 >>> def my_decorator(f):
236 ... @wraps(f)
237 ... def wrapper(*args, **kwds):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000238 ... print('Calling decorated function')
Georg Brandl116aa622007-08-15 14:28:22 +0000239 ... return f(*args, **kwds)
240 ... return wrapper
241 ...
242 >>> @my_decorator
243 ... def example():
244 ... """Docstring"""
Georg Brandl6911e3c2007-09-04 07:15:32 +0000245 ... print('Called example function')
Georg Brandl116aa622007-08-15 14:28:22 +0000246 ...
247 >>> example()
248 Calling decorated function
249 Called example function
250 >>> example.__name__
251 'example'
252 >>> example.__doc__
253 'Docstring'
254
255 Without the use of this decorator factory, the name of the example function
256 would have been ``'wrapper'``, and the docstring of the original :func:`example`
257 would have been lost.
258
259
260.. _partial-objects:
261
262:class:`partial` Objects
263------------------------
264
265:class:`partial` objects are callable objects created by :func:`partial`. They
266have three read-only attributes:
267
268
269.. attribute:: partial.func
270
271 A callable object or function. Calls to the :class:`partial` object will be
272 forwarded to :attr:`func` with new arguments and keywords.
273
274
275.. attribute:: partial.args
276
277 The leftmost positional arguments that will be prepended to the positional
278 arguments provided to a :class:`partial` object call.
279
280
281.. attribute:: partial.keywords
282
283 The keyword arguments that will be supplied when the :class:`partial` object is
284 called.
285
286:class:`partial` objects are like :class:`function` objects in that they are
287callable, weak referencable, and can have attributes. There are some important
288differences. For instance, the :attr:`__name__` and :attr:`__doc__` attributes
289are not created automatically. Also, :class:`partial` objects defined in
290classes behave like static methods and do not transform into bound methods
291during instance attribute look-up.
292