blob: 7c9b9cabfde19e6cadfa5ce9d39f91223a9efcc9 [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
35 argument and returns another value that indicates the position in the desired
36 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 Hettinger7496b412010-11-30 19:15:45 +000054 To help measure the effectiveness of the cache and tune the *maxsize*
55 parameter, the wrapped function is instrumented with a :func:`cache_info`
56 function that returns a :term:`named tuple` showing *hits*, *misses*,
57 *maxsize* and *currsize*.
Nick Coghlan234515a2010-11-30 06:19:46 +000058
Raymond Hettinger7496b412010-11-30 19:15:45 +000059 The decorator also provides a :func:`cache_clear` function for clearing or
60 invalidating the cache.
Georg Brandl2e7346a2010-07-31 18:09:23 +000061
Raymond Hettinger3fccfcb2010-08-17 19:19:29 +000062 The original underlying function is accessible through the
Raymond Hettinger7496b412010-11-30 19:15:45 +000063 :attr:`__wrapped__` attribute. This is useful for introspection, for
64 bypassing the cache, or for rewrapping the function with a different cache.
Nick Coghlan98876832010-08-17 06:17:18 +000065
Georg Brandl2e7346a2010-07-31 18:09:23 +000066 A `LRU (least recently used) cache
Raymond Hettinger7496b412010-11-30 19:15:45 +000067 <http://en.wikipedia.org/wiki/Cache_algorithms#Least_Recently_Used>`_ works
68 best when more recent calls are the best predictors of upcoming calls (for
69 example, the most popular articles on a news server tend to change daily).
70 The cache's size limit assures that the cache does not grow without bound on
71 long-running processes such as web servers.
72
73 Example -- Caching static web content::
74
75 @functools.lru_cache(maxsize=20)
76 def get_pep(num):
77 'Retrieve text of a Python Enhancement Proposal'
78 resource = 'http://www.python.org/dev/peps/pep-%04d/' % num
79 try:
80 with urllib.request.urlopen(resource) as s:
81 return s.read()
82 except urllib.error.HTTPError:
83 return 'Not Found'
84
85 >>> for n in 8, 290, 308, 320, 8, 218, 320, 279, 289, 320, 9991:
86 ... pep = get_pep(n)
87 ... print(n, len(pep))
88
89 >>> print(get_pep.cache_info())
90 CacheInfo(hits=3, misses=8, maxsize=20, currsize=8)
Georg Brandl2e7346a2010-07-31 18:09:23 +000091
92 .. versionadded:: 3.2
93
Georg Brandl67b21b72010-08-17 15:07:14 +000094
Georg Brandl8a1caa22010-07-29 16:01:11 +000095.. decorator:: total_ordering
Raymond Hettingerc50846a2010-04-05 18:56:31 +000096
97 Given a class defining one or more rich comparison ordering methods, this
Benjamin Peterson08bf91c2010-04-11 16:12:57 +000098 class decorator supplies the rest. This simplifies the effort involved
Raymond Hettingerc50846a2010-04-05 18:56:31 +000099 in specifying all of the possible rich comparison operations:
100
101 The class must define one of :meth:`__lt__`, :meth:`__le__`,
102 :meth:`__gt__`, or :meth:`__ge__`.
103 In addition, the class should supply an :meth:`__eq__` method.
104
105 For example::
106
107 @total_ordering
108 class Student:
109 def __eq__(self, other):
110 return ((self.lastname.lower(), self.firstname.lower()) ==
111 (other.lastname.lower(), other.firstname.lower()))
112 def __lt__(self, other):
113 return ((self.lastname.lower(), self.firstname.lower()) <
114 (other.lastname.lower(), other.firstname.lower()))
115
116 .. versionadded:: 3.2
117
Georg Brandl67b21b72010-08-17 15:07:14 +0000118
Georg Brandl036490d2009-05-17 13:00:36 +0000119.. function:: partial(func, *args, **keywords)
Georg Brandl116aa622007-08-15 14:28:22 +0000120
121 Return a new :class:`partial` object which when called will behave like *func*
122 called with the positional arguments *args* and keyword arguments *keywords*. If
123 more arguments are supplied to the call, they are appended to *args*. If
124 additional keyword arguments are supplied, they extend and override *keywords*.
125 Roughly equivalent to::
126
127 def partial(func, *args, **keywords):
128 def newfunc(*fargs, **fkeywords):
129 newkeywords = keywords.copy()
130 newkeywords.update(fkeywords)
131 return func(*(args + fargs), **newkeywords)
132 newfunc.func = func
133 newfunc.args = args
134 newfunc.keywords = keywords
135 return newfunc
136
137 The :func:`partial` is used for partial function application which "freezes"
138 some portion of a function's arguments and/or keywords resulting in a new object
139 with a simplified signature. For example, :func:`partial` can be used to create
140 a callable that behaves like the :func:`int` function where the *base* argument
Christian Heimesfe337bf2008-03-23 21:54:12 +0000141 defaults to two:
Georg Brandl116aa622007-08-15 14:28:22 +0000142
Christian Heimesfe337bf2008-03-23 21:54:12 +0000143 >>> from functools import partial
Georg Brandl116aa622007-08-15 14:28:22 +0000144 >>> basetwo = partial(int, base=2)
145 >>> basetwo.__doc__ = 'Convert base 2 string to an int.'
146 >>> basetwo('10010')
147 18
148
149
Georg Brandl58f9e4f2008-04-19 22:18:33 +0000150.. function:: reduce(function, iterable[, initializer])
Georg Brandl116aa622007-08-15 14:28:22 +0000151
152 Apply *function* of two arguments cumulatively to the items of *sequence*, from
153 left to right, so as to reduce the sequence to a single value. For example,
154 ``reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])`` calculates ``((((1+2)+3)+4)+5)``.
155 The left argument, *x*, is the accumulated value and the right argument, *y*, is
156 the update value from the *sequence*. If the optional *initializer* is present,
157 it is placed before the items of the sequence in the calculation, and serves as
158 a default when the sequence is empty. If *initializer* is not given and
159 *sequence* contains only one item, the first item is returned.
160
161
Georg Brandl036490d2009-05-17 13:00:36 +0000162.. function:: update_wrapper(wrapper, wrapped, assigned=WRAPPER_ASSIGNMENTS, updated=WRAPPER_UPDATES)
Georg Brandl116aa622007-08-15 14:28:22 +0000163
164 Update a *wrapper* function to look like the *wrapped* function. The optional
165 arguments are tuples to specify which attributes of the original function are
166 assigned directly to the matching attributes on the wrapper function and which
167 attributes of the wrapper function are updated with the corresponding attributes
168 from the original function. The default values for these arguments are the
169 module level constants *WRAPPER_ASSIGNMENTS* (which assigns to the wrapper
Antoine Pitrou560f7642010-08-04 18:28:02 +0000170 function's *__name__*, *__module__*, *__annotations__* and *__doc__*, the
171 documentation string) and *WRAPPER_UPDATES* (which updates the wrapper
172 function's *__dict__*, i.e. the instance dictionary).
Georg Brandl116aa622007-08-15 14:28:22 +0000173
Nick Coghlan98876832010-08-17 06:17:18 +0000174 To allow access to the original function for introspection and other purposes
175 (e.g. bypassing a caching decorator such as :func:`lru_cache`), this function
Éric Araujoc6ecb012010-11-06 06:33:03 +0000176 automatically adds a __wrapped__ attribute to the wrapper that refers to
Nick Coghlan98876832010-08-17 06:17:18 +0000177 the original function.
178
Christian Heimesd8654cf2007-12-02 15:22:16 +0000179 The main intended use for this function is in :term:`decorator` functions which
180 wrap the decorated function and return the wrapper. If the wrapper function is
181 not updated, the metadata of the returned function will reflect the wrapper
Georg Brandl116aa622007-08-15 14:28:22 +0000182 definition rather than the original function definition, which is typically less
183 than helpful.
184
Nick Coghlan98876832010-08-17 06:17:18 +0000185 :func:`update_wrapper` may be used with callables other than functions. Any
186 attributes named in *assigned* or *updated* that are missing from the object
187 being wrapped are ignored (i.e. this function will not attempt to set them
188 on the wrapper function). :exc:`AttributeError` is still raised if the
189 wrapper function itself is missing any attributes named in *updated*.
190
191 .. versionadded:: 3.2
Georg Brandl9e257012010-08-17 14:11:59 +0000192 Automatic addition of the ``__wrapped__`` attribute.
Nick Coghlan98876832010-08-17 06:17:18 +0000193
194 .. versionadded:: 3.2
Georg Brandl9e257012010-08-17 14:11:59 +0000195 Copying of the ``__annotations__`` attribute by default.
Nick Coghlan98876832010-08-17 06:17:18 +0000196
197 .. versionchanged:: 3.2
Georg Brandl9e257012010-08-17 14:11:59 +0000198 Missing attributes no longer trigger an :exc:`AttributeError`.
199
Georg Brandl116aa622007-08-15 14:28:22 +0000200
Georg Brandl8a1caa22010-07-29 16:01:11 +0000201.. decorator:: wraps(wrapped, assigned=WRAPPER_ASSIGNMENTS, updated=WRAPPER_UPDATES)
Georg Brandl116aa622007-08-15 14:28:22 +0000202
203 This is a convenience function for invoking ``partial(update_wrapper,
204 wrapped=wrapped, assigned=assigned, updated=updated)`` as a function decorator
Christian Heimesfe337bf2008-03-23 21:54:12 +0000205 when defining a wrapper function. For example:
Georg Brandl116aa622007-08-15 14:28:22 +0000206
Christian Heimesfe337bf2008-03-23 21:54:12 +0000207 >>> from functools import wraps
Georg Brandl116aa622007-08-15 14:28:22 +0000208 >>> def my_decorator(f):
209 ... @wraps(f)
210 ... def wrapper(*args, **kwds):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000211 ... print('Calling decorated function')
Georg Brandl116aa622007-08-15 14:28:22 +0000212 ... return f(*args, **kwds)
213 ... return wrapper
214 ...
215 >>> @my_decorator
216 ... def example():
217 ... """Docstring"""
Georg Brandl6911e3c2007-09-04 07:15:32 +0000218 ... print('Called example function')
Georg Brandl116aa622007-08-15 14:28:22 +0000219 ...
220 >>> example()
221 Calling decorated function
222 Called example function
223 >>> example.__name__
224 'example'
225 >>> example.__doc__
226 'Docstring'
227
228 Without the use of this decorator factory, the name of the example function
229 would have been ``'wrapper'``, and the docstring of the original :func:`example`
230 would have been lost.
231
232
233.. _partial-objects:
234
235:class:`partial` Objects
236------------------------
237
238:class:`partial` objects are callable objects created by :func:`partial`. They
239have three read-only attributes:
240
241
242.. attribute:: partial.func
243
244 A callable object or function. Calls to the :class:`partial` object will be
245 forwarded to :attr:`func` with new arguments and keywords.
246
247
248.. attribute:: partial.args
249
250 The leftmost positional arguments that will be prepended to the positional
251 arguments provided to a :class:`partial` object call.
252
253
254.. attribute:: partial.keywords
255
256 The keyword arguments that will be supplied when the :class:`partial` object is
257 called.
258
259:class:`partial` objects are like :class:`function` objects in that they are
260callable, weak referencable, and can have attributes. There are some important
261differences. For instance, the :attr:`__name__` and :attr:`__doc__` attributes
262are not created automatically. Also, :class:`partial` objects defined in
263classes behave like static methods and do not transform into bound methods
264during instance attribute look-up.
265