blob: 07081625baa0fd8b06901ddc0b72113832514678 [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
11
Georg Brandl116aa622007-08-15 14:28:22 +000012The :mod:`functools` module is for higher-order functions: functions that act on
13or return other functions. In general, any callable object can be treated as a
14function for the purposes of this module.
15
Éric Araujo6e6cb8e2010-11-16 19:13:50 +000016.. seealso::
17
18 Latest version of the :source:`functools Python source code
19 <Lib/functools.py>`
20
Thomas Woutersed03b412007-08-28 21:37:11 +000021The :mod:`functools` module defines the following functions:
22
Éric Araujob10089e2010-11-18 14:22:08 +000023.. function:: cmp_to_key(func)
Raymond Hettingerc50846a2010-04-05 18:56:31 +000024
Benjamin Petersoncca65312010-08-09 02:13:10 +000025 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 Hettingerc50846a2010-04-05 18:56:31 +000031
Benjamin Petersoncca65312010-08-09 02:13:10 +000032 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 Hettingerc79fb0e2010-12-01 03:45:41 +000035 argument and returns another value indicating the position in the desired
Benjamin Petersoncca65312010-08-09 02:13:10 +000036 collation sequence.
Raymond Hettingerc50846a2010-04-05 18:56:31 +000037
Benjamin Petersoncca65312010-08-09 02:13:10 +000038 Example::
Raymond Hettingerc50846a2010-04-05 18:56:31 +000039
Benjamin Petersoncca65312010-08-09 02:13:10 +000040 sorted(iterable, key=cmp_to_key(locale.strcoll)) # locale-aware sort order
Raymond Hettingerc50846a2010-04-05 18:56:31 +000041
42 .. versionadded:: 3.2
43
Georg Brandl67b21b72010-08-17 15:07:14 +000044
Raymond Hettinger7496b412010-11-30 19:15:45 +000045.. decorator:: lru_cache(maxsize=100)
Georg Brandl2e7346a2010-07-31 18:09:23 +000046
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 Hettinger7496b412010-11-30 19:15:45 +000051 Since a dictionary is used to cache results, the positional and keyword
52 arguments to the function must be hashable.
Georg Brandl2e7346a2010-07-31 18:09:23 +000053
Raymond Hettingerc79fb0e2010-12-01 03:45:41 +000054 If *maxsize* is set to None, the LRU feature is disabled and the cache
55 can grow without bound.
56
Raymond Hettinger7496b412010-11-30 19:15:45 +000057 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 Hettingerc79fb0e2010-12-01 03:45:41 +000060 *maxsize* and *currsize*. In a multi-threaded environment, the hits
61 and misses are approximate.
Nick Coghlan234515a2010-11-30 06:19:46 +000062
Raymond Hettinger7496b412010-11-30 19:15:45 +000063 The decorator also provides a :func:`cache_clear` function for clearing or
64 invalidating the cache.
Georg Brandl2e7346a2010-07-31 18:09:23 +000065
Raymond Hettinger3fccfcb2010-08-17 19:19:29 +000066 The original underlying function is accessible through the
Raymond Hettinger7496b412010-11-30 19:15:45 +000067 :attr:`__wrapped__` attribute. This is useful for introspection, for
68 bypassing the cache, or for rewrapping the function with a different cache.
Nick Coghlan98876832010-08-17 06:17:18 +000069
Raymond Hettingercc038582010-11-30 20:02:57 +000070 An `LRU (least recently used) cache
Raymond Hettinger7496b412010-11-30 19:15:45 +000071 <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 Hettingercc038582010-11-30 20:02:57 +000077 Example of an LRU cache for static web content::
Raymond Hettinger7496b412010-11-30 19:15:45 +000078
Raymond Hettingercc038582010-11-30 20:02:57 +000079 @lru_cache(maxsize=20)
Raymond Hettinger7496b412010-11-30 19:15:45 +000080 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 Brandl2e7346a2010-07-31 18:09:23 +000095
Raymond Hettingerc79fb0e2010-12-01 03:45:41 +000096 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 Brandl2e7346a2010-07-31 18:09:23 +0000114 .. versionadded:: 3.2
115
Georg Brandl8a1caa22010-07-29 16:01:11 +0000116.. decorator:: total_ordering
Raymond Hettingerc50846a2010-04-05 18:56:31 +0000117
118 Given a class defining one or more rich comparison ordering methods, this
Benjamin Peterson08bf91c2010-04-11 16:12:57 +0000119 class decorator supplies the rest. This simplifies the effort involved
Raymond Hettingerc50846a2010-04-05 18:56:31 +0000120 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 Brandl67b21b72010-08-17 15:07:14 +0000139
Georg Brandl036490d2009-05-17 13:00:36 +0000140.. function:: partial(func, *args, **keywords)
Georg Brandl116aa622007-08-15 14:28:22 +0000141
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 Heimesfe337bf2008-03-23 21:54:12 +0000162 defaults to two:
Georg Brandl116aa622007-08-15 14:28:22 +0000163
Christian Heimesfe337bf2008-03-23 21:54:12 +0000164 >>> from functools import partial
Georg Brandl116aa622007-08-15 14:28:22 +0000165 >>> basetwo = partial(int, base=2)
166 >>> basetwo.__doc__ = 'Convert base 2 string to an int.'
167 >>> basetwo('10010')
168 18
169
170
Georg Brandl58f9e4f2008-04-19 22:18:33 +0000171.. function:: reduce(function, iterable[, initializer])
Georg Brandl116aa622007-08-15 14:28:22 +0000172
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 Brandl036490d2009-05-17 13:00:36 +0000183.. function:: update_wrapper(wrapper, wrapped, assigned=WRAPPER_ASSIGNMENTS, updated=WRAPPER_UPDATES)
Georg Brandl116aa622007-08-15 14:28:22 +0000184
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 Pitrou560f7642010-08-04 18:28:02 +0000191 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 Brandl116aa622007-08-15 14:28:22 +0000194
Nick Coghlan98876832010-08-17 06:17:18 +0000195 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 Araujoc6ecb012010-11-06 06:33:03 +0000197 automatically adds a __wrapped__ attribute to the wrapper that refers to
Nick Coghlan98876832010-08-17 06:17:18 +0000198 the original function.
199
Christian Heimesd8654cf2007-12-02 15:22:16 +0000200 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 Brandl116aa622007-08-15 14:28:22 +0000203 definition rather than the original function definition, which is typically less
204 than helpful.
205
Nick Coghlan98876832010-08-17 06:17:18 +0000206 :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 Brandl9e257012010-08-17 14:11:59 +0000213 Automatic addition of the ``__wrapped__`` attribute.
Nick Coghlan98876832010-08-17 06:17:18 +0000214
215 .. versionadded:: 3.2
Georg Brandl9e257012010-08-17 14:11:59 +0000216 Copying of the ``__annotations__`` attribute by default.
Nick Coghlan98876832010-08-17 06:17:18 +0000217
218 .. versionchanged:: 3.2
Georg Brandl9e257012010-08-17 14:11:59 +0000219 Missing attributes no longer trigger an :exc:`AttributeError`.
220
Georg Brandl116aa622007-08-15 14:28:22 +0000221
Georg Brandl8a1caa22010-07-29 16:01:11 +0000222.. decorator:: wraps(wrapped, assigned=WRAPPER_ASSIGNMENTS, updated=WRAPPER_UPDATES)
Georg Brandl116aa622007-08-15 14:28:22 +0000223
224 This is a convenience function for invoking ``partial(update_wrapper,
225 wrapped=wrapped, assigned=assigned, updated=updated)`` as a function decorator
Christian Heimesfe337bf2008-03-23 21:54:12 +0000226 when defining a wrapper function. For example:
Georg Brandl116aa622007-08-15 14:28:22 +0000227
Christian Heimesfe337bf2008-03-23 21:54:12 +0000228 >>> from functools import wraps
Georg Brandl116aa622007-08-15 14:28:22 +0000229 >>> def my_decorator(f):
230 ... @wraps(f)
231 ... def wrapper(*args, **kwds):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000232 ... print('Calling decorated function')
Georg Brandl116aa622007-08-15 14:28:22 +0000233 ... return f(*args, **kwds)
234 ... return wrapper
235 ...
236 >>> @my_decorator
237 ... def example():
238 ... """Docstring"""
Georg Brandl6911e3c2007-09-04 07:15:32 +0000239 ... print('Called example function')
Georg Brandl116aa622007-08-15 14:28:22 +0000240 ...
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
260have 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
281callable, weak referencable, and can have attributes. There are some important
282differences. For instance, the :attr:`__name__` and :attr:`__doc__` attributes
283are not created automatically. Also, :class:`partial` objects defined in
284classes behave like static methods and do not transform into bound methods
285during instance attribute look-up.
286