blob: 2316e804899e91a7b711659472af880539f16b1b [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001: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
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
Benjamin Petersoncca65312010-08-09 02:13:10 +000023 Transform an old-style comparison function to a key-function. Used with
24 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
27 tool for programs being converted from Py2.x which supported the use of
28 comparison functions.
Raymond Hettingerc50846a2010-04-05 18:56:31 +000029
Benjamin Petersoncca65312010-08-09 02:13:10 +000030 A compare function is any callable that accept two arguments, compares them,
31 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 Hettinger7496b412010-11-30 19:15:45 +000043.. decorator:: lru_cache(maxsize=100)
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 Hettingerc79fb0e2010-12-01 03:45:41 +000052 If *maxsize* is set to None, the LRU feature is disabled and the cache
53 can grow without bound.
54
Raymond Hettinger7496b412010-11-30 19:15:45 +000055 To help measure the effectiveness of the cache and tune the *maxsize*
56 parameter, the wrapped function is instrumented with a :func:`cache_info`
57 function that returns a :term:`named tuple` showing *hits*, *misses*,
Raymond Hettingerc79fb0e2010-12-01 03:45:41 +000058 *maxsize* and *currsize*. In a multi-threaded environment, the hits
59 and misses are approximate.
Nick Coghlan234515a2010-11-30 06:19:46 +000060
Raymond Hettinger7496b412010-11-30 19:15:45 +000061 The decorator also provides a :func:`cache_clear` function for clearing or
62 invalidating the cache.
Georg Brandl2e7346a2010-07-31 18:09:23 +000063
Raymond Hettinger3fccfcb2010-08-17 19:19:29 +000064 The original underlying function is accessible through the
Raymond Hettinger7496b412010-11-30 19:15:45 +000065 :attr:`__wrapped__` attribute. This is useful for introspection, for
66 bypassing the cache, or for rewrapping the function with a different cache.
Nick Coghlan98876832010-08-17 06:17:18 +000067
Raymond Hettingercc038582010-11-30 20:02:57 +000068 An `LRU (least recently used) cache
Raymond Hettinger7496b412010-11-30 19:15:45 +000069 <http://en.wikipedia.org/wiki/Cache_algorithms#Least_Recently_Used>`_ works
70 best when more recent calls are the best predictors of upcoming calls (for
71 example, the most popular articles on a news server tend to change daily).
72 The cache's size limit assures that the cache does not grow without bound on
73 long-running processes such as web servers.
74
Raymond Hettingercc038582010-11-30 20:02:57 +000075 Example of an LRU cache for static web content::
Raymond Hettinger7496b412010-11-30 19:15:45 +000076
Raymond Hettingercc038582010-11-30 20:02:57 +000077 @lru_cache(maxsize=20)
Raymond Hettinger7496b412010-11-30 19:15:45 +000078 def get_pep(num):
79 'Retrieve text of a Python Enhancement Proposal'
80 resource = 'http://www.python.org/dev/peps/pep-%04d/' % num
81 try:
82 with urllib.request.urlopen(resource) as s:
83 return s.read()
84 except urllib.error.HTTPError:
85 return 'Not Found'
86
87 >>> for n in 8, 290, 308, 320, 8, 218, 320, 279, 289, 320, 9991:
88 ... pep = get_pep(n)
89 ... print(n, len(pep))
90
91 >>> print(get_pep.cache_info())
92 CacheInfo(hits=3, misses=8, maxsize=20, currsize=8)
Georg Brandl2e7346a2010-07-31 18:09:23 +000093
Raymond Hettingerc79fb0e2010-12-01 03:45:41 +000094 Example of efficiently computing
95 `Fibonacci numbers <http://en.wikipedia.org/wiki/Fibonacci_number>`_
96 using a cache to implement a
97 `dynamic programming <http://en.wikipedia.org/wiki/Dynamic_programming>`_
98 technique::
99
100 @lru_cache(maxsize=None)
101 def fib(n):
102 if n < 2:
103 return n
104 return fib(n-1) + fib(n-2)
105
106 >>> print([fib(n) for n in range(16)])
107 [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610]
108
109 >>> print(fib.cache_info())
110 CacheInfo(hits=28, misses=16, maxsize=None, currsize=16)
111
Georg Brandl2e7346a2010-07-31 18:09:23 +0000112 .. versionadded:: 3.2
113
Georg Brandl8a1caa22010-07-29 16:01:11 +0000114.. decorator:: total_ordering
Raymond Hettingerc50846a2010-04-05 18:56:31 +0000115
116 Given a class defining one or more rich comparison ordering methods, this
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000117 class decorator supplies the rest. This simplifies the effort involved
Raymond Hettingerc50846a2010-04-05 18:56:31 +0000118 in specifying all of the possible rich comparison operations:
119
120 The class must define one of :meth:`__lt__`, :meth:`__le__`,
121 :meth:`__gt__`, or :meth:`__ge__`.
122 In addition, the class should supply an :meth:`__eq__` method.
123
124 For example::
125
126 @total_ordering
127 class Student:
128 def __eq__(self, other):
129 return ((self.lastname.lower(), self.firstname.lower()) ==
130 (other.lastname.lower(), other.firstname.lower()))
131 def __lt__(self, other):
132 return ((self.lastname.lower(), self.firstname.lower()) <
133 (other.lastname.lower(), other.firstname.lower()))
134
135 .. versionadded:: 3.2
136
Georg Brandl67b21b72010-08-17 15:07:14 +0000137
Georg Brandl036490d2009-05-17 13:00:36 +0000138.. function:: partial(func, *args, **keywords)
Georg Brandl116aa622007-08-15 14:28:22 +0000139
140 Return a new :class:`partial` object which when called will behave like *func*
141 called with the positional arguments *args* and keyword arguments *keywords*. If
142 more arguments are supplied to the call, they are appended to *args*. If
143 additional keyword arguments are supplied, they extend and override *keywords*.
144 Roughly equivalent to::
145
146 def partial(func, *args, **keywords):
147 def newfunc(*fargs, **fkeywords):
148 newkeywords = keywords.copy()
149 newkeywords.update(fkeywords)
150 return func(*(args + fargs), **newkeywords)
151 newfunc.func = func
152 newfunc.args = args
153 newfunc.keywords = keywords
154 return newfunc
155
156 The :func:`partial` is used for partial function application which "freezes"
157 some portion of a function's arguments and/or keywords resulting in a new object
158 with a simplified signature. For example, :func:`partial` can be used to create
159 a callable that behaves like the :func:`int` function where the *base* argument
Christian Heimesfe337bf2008-03-23 21:54:12 +0000160 defaults to two:
Georg Brandl116aa622007-08-15 14:28:22 +0000161
Christian Heimesfe337bf2008-03-23 21:54:12 +0000162 >>> from functools import partial
Georg Brandl116aa622007-08-15 14:28:22 +0000163 >>> basetwo = partial(int, base=2)
164 >>> basetwo.__doc__ = 'Convert base 2 string to an int.'
165 >>> basetwo('10010')
166 18
167
168
Georg Brandl58f9e4f2008-04-19 22:18:33 +0000169.. function:: reduce(function, iterable[, initializer])
Georg Brandl116aa622007-08-15 14:28:22 +0000170
171 Apply *function* of two arguments cumulatively to the items of *sequence*, from
172 left to right, so as to reduce the sequence to a single value. For example,
173 ``reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])`` calculates ``((((1+2)+3)+4)+5)``.
174 The left argument, *x*, is the accumulated value and the right argument, *y*, is
175 the update value from the *sequence*. If the optional *initializer* is present,
176 it is placed before the items of the sequence in the calculation, and serves as
177 a default when the sequence is empty. If *initializer* is not given and
178 *sequence* contains only one item, the first item is returned.
179
180
Georg Brandl036490d2009-05-17 13:00:36 +0000181.. function:: update_wrapper(wrapper, wrapped, assigned=WRAPPER_ASSIGNMENTS, updated=WRAPPER_UPDATES)
Georg Brandl116aa622007-08-15 14:28:22 +0000182
183 Update a *wrapper* function to look like the *wrapped* function. The optional
184 arguments are tuples to specify which attributes of the original function are
185 assigned directly to the matching attributes on the wrapper function and which
186 attributes of the wrapper function are updated with the corresponding attributes
187 from the original function. The default values for these arguments are the
188 module level constants *WRAPPER_ASSIGNMENTS* (which assigns to the wrapper
Antoine Pitrou560f7642010-08-04 18:28:02 +0000189 function's *__name__*, *__module__*, *__annotations__* and *__doc__*, the
190 documentation string) and *WRAPPER_UPDATES* (which updates the wrapper
191 function's *__dict__*, i.e. the instance dictionary).
Georg Brandl116aa622007-08-15 14:28:22 +0000192
Nick Coghlan98876832010-08-17 06:17:18 +0000193 To allow access to the original function for introspection and other purposes
194 (e.g. bypassing a caching decorator such as :func:`lru_cache`), this function
Éric Araujoc6ecb012010-11-06 06:33:03 +0000195 automatically adds a __wrapped__ attribute to the wrapper that refers to
Nick Coghlan98876832010-08-17 06:17:18 +0000196 the original function.
197
Christian Heimesd8654cf2007-12-02 15:22:16 +0000198 The main intended use for this function is in :term:`decorator` functions which
199 wrap the decorated function and return the wrapper. If the wrapper function is
200 not updated, the metadata of the returned function will reflect the wrapper
Georg Brandl116aa622007-08-15 14:28:22 +0000201 definition rather than the original function definition, which is typically less
202 than helpful.
203
Nick Coghlan98876832010-08-17 06:17:18 +0000204 :func:`update_wrapper` may be used with callables other than functions. Any
205 attributes named in *assigned* or *updated* that are missing from the object
206 being wrapped are ignored (i.e. this function will not attempt to set them
207 on the wrapper function). :exc:`AttributeError` is still raised if the
208 wrapper function itself is missing any attributes named in *updated*.
209
210 .. versionadded:: 3.2
Georg Brandl9e257012010-08-17 14:11:59 +0000211 Automatic addition of the ``__wrapped__`` attribute.
Nick Coghlan98876832010-08-17 06:17:18 +0000212
213 .. versionadded:: 3.2
Georg Brandl9e257012010-08-17 14:11:59 +0000214 Copying of the ``__annotations__`` attribute by default.
Nick Coghlan98876832010-08-17 06:17:18 +0000215
216 .. versionchanged:: 3.2
Georg Brandl9e257012010-08-17 14:11:59 +0000217 Missing attributes no longer trigger an :exc:`AttributeError`.
218
Georg Brandl116aa622007-08-15 14:28:22 +0000219
Georg Brandl8a1caa22010-07-29 16:01:11 +0000220.. decorator:: wraps(wrapped, assigned=WRAPPER_ASSIGNMENTS, updated=WRAPPER_UPDATES)
Georg Brandl116aa622007-08-15 14:28:22 +0000221
222 This is a convenience function for invoking ``partial(update_wrapper,
223 wrapped=wrapped, assigned=assigned, updated=updated)`` as a function decorator
Christian Heimesfe337bf2008-03-23 21:54:12 +0000224 when defining a wrapper function. For example:
Georg Brandl116aa622007-08-15 14:28:22 +0000225
Christian Heimesfe337bf2008-03-23 21:54:12 +0000226 >>> from functools import wraps
Georg Brandl116aa622007-08-15 14:28:22 +0000227 >>> def my_decorator(f):
228 ... @wraps(f)
229 ... def wrapper(*args, **kwds):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000230 ... print('Calling decorated function')
Georg Brandl116aa622007-08-15 14:28:22 +0000231 ... return f(*args, **kwds)
232 ... return wrapper
233 ...
234 >>> @my_decorator
235 ... def example():
236 ... """Docstring"""
Georg Brandl6911e3c2007-09-04 07:15:32 +0000237 ... print('Called example function')
Georg Brandl116aa622007-08-15 14:28:22 +0000238 ...
239 >>> example()
240 Calling decorated function
241 Called example function
242 >>> example.__name__
243 'example'
244 >>> example.__doc__
245 'Docstring'
246
247 Without the use of this decorator factory, the name of the example function
248 would have been ``'wrapper'``, and the docstring of the original :func:`example`
249 would have been lost.
250
251
252.. _partial-objects:
253
254:class:`partial` Objects
255------------------------
256
257:class:`partial` objects are callable objects created by :func:`partial`. They
258have three read-only attributes:
259
260
261.. attribute:: partial.func
262
263 A callable object or function. Calls to the :class:`partial` object will be
264 forwarded to :attr:`func` with new arguments and keywords.
265
266
267.. attribute:: partial.args
268
269 The leftmost positional arguments that will be prepended to the positional
270 arguments provided to a :class:`partial` object call.
271
272
273.. attribute:: partial.keywords
274
275 The keyword arguments that will be supplied when the :class:`partial` object is
276 called.
277
278:class:`partial` objects are like :class:`function` objects in that they are
279callable, weak referencable, and can have attributes. There are some important
280differences. For instance, the :attr:`__name__` and :attr:`__doc__` attributes
281are not created automatically. Also, :class:`partial` objects defined in
282classes behave like static methods and do not transform into bound methods
283during instance attribute look-up.
284