blob: 58c2429fd1f252793c0c3be01e24dad7ac23213a [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
Raymond Hettingerc50846a2010-04-05 18:56:31 +000023.. function:: cmp_to_key(func)
24
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
Georg Brandl2e7346a2010-07-31 18:09:23 +000045.. decorator:: lru_cache(maxsize)
46
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
51 The *maxsize* parameter defaults to 100. Since a dictionary is used to cache
52 results, the positional and keyword arguments to the function must be
53 hashable.
54
Raymond Hettinger02566ec2010-09-04 22:46:06 +000055 The wrapped function is instrumented with two attributes, :attr:`cache_hits`
56 and :attr:`cache_misses` which count the number of successful or unsuccessful
Georg Brandl2e7346a2010-07-31 18:09:23 +000057 cache lookups. These statistics are helpful for tuning the *maxsize*
58 parameter and for measuring the cache's effectiveness.
59
Raymond Hettinger02566ec2010-09-04 22:46:06 +000060 The wrapped function also has a :attr:`cache_clear` attribute which can be
Georg Brandl2e7346a2010-07-31 18:09:23 +000061 called (with no arguments) to clear the cache.
62
Raymond Hettinger3fccfcb2010-08-17 19:19:29 +000063 The original underlying function is accessible through the
64 :attr:`__wrapped__` attribute. This allows introspection, bypassing
65 the cache, or rewrapping the function with a different caching tool.
Nick Coghlan98876832010-08-17 06:17:18 +000066
Georg Brandl2e7346a2010-07-31 18:09:23 +000067 A `LRU (least recently used) cache
68 <http://en.wikipedia.org/wiki/Cache_algorithms#Least_Recently_Used>`_
69 is indicated when the pattern of calls changes over time, such as
Raymond Hettingerc8dc62d2010-08-02 00:59:14 +000070 when more recent calls are the best predictors of upcoming calls
71 (for example, the most popular articles on a news server tend to
72 change every day).
Georg Brandl2e7346a2010-07-31 18:09:23 +000073
74 .. versionadded:: 3.2
75
Georg Brandl67b21b72010-08-17 15:07:14 +000076
Georg Brandl8a1caa22010-07-29 16:01:11 +000077.. decorator:: total_ordering
Raymond Hettingerc50846a2010-04-05 18:56:31 +000078
79 Given a class defining one or more rich comparison ordering methods, this
Benjamin Peterson08bf91c2010-04-11 16:12:57 +000080 class decorator supplies the rest. This simplifies the effort involved
Raymond Hettingerc50846a2010-04-05 18:56:31 +000081 in specifying all of the possible rich comparison operations:
82
83 The class must define one of :meth:`__lt__`, :meth:`__le__`,
84 :meth:`__gt__`, or :meth:`__ge__`.
85 In addition, the class should supply an :meth:`__eq__` method.
86
87 For example::
88
89 @total_ordering
90 class Student:
91 def __eq__(self, other):
92 return ((self.lastname.lower(), self.firstname.lower()) ==
93 (other.lastname.lower(), other.firstname.lower()))
94 def __lt__(self, other):
95 return ((self.lastname.lower(), self.firstname.lower()) <
96 (other.lastname.lower(), other.firstname.lower()))
97
98 .. versionadded:: 3.2
99
Georg Brandl67b21b72010-08-17 15:07:14 +0000100
Georg Brandl036490d2009-05-17 13:00:36 +0000101.. function:: partial(func, *args, **keywords)
Georg Brandl116aa622007-08-15 14:28:22 +0000102
103 Return a new :class:`partial` object which when called will behave like *func*
104 called with the positional arguments *args* and keyword arguments *keywords*. If
105 more arguments are supplied to the call, they are appended to *args*. If
106 additional keyword arguments are supplied, they extend and override *keywords*.
107 Roughly equivalent to::
108
109 def partial(func, *args, **keywords):
110 def newfunc(*fargs, **fkeywords):
111 newkeywords = keywords.copy()
112 newkeywords.update(fkeywords)
113 return func(*(args + fargs), **newkeywords)
114 newfunc.func = func
115 newfunc.args = args
116 newfunc.keywords = keywords
117 return newfunc
118
119 The :func:`partial` is used for partial function application which "freezes"
120 some portion of a function's arguments and/or keywords resulting in a new object
121 with a simplified signature. For example, :func:`partial` can be used to create
122 a callable that behaves like the :func:`int` function where the *base* argument
Christian Heimesfe337bf2008-03-23 21:54:12 +0000123 defaults to two:
Georg Brandl116aa622007-08-15 14:28:22 +0000124
Christian Heimesfe337bf2008-03-23 21:54:12 +0000125 >>> from functools import partial
Georg Brandl116aa622007-08-15 14:28:22 +0000126 >>> basetwo = partial(int, base=2)
127 >>> basetwo.__doc__ = 'Convert base 2 string to an int.'
128 >>> basetwo('10010')
129 18
130
131
Georg Brandl58f9e4f2008-04-19 22:18:33 +0000132.. function:: reduce(function, iterable[, initializer])
Georg Brandl116aa622007-08-15 14:28:22 +0000133
134 Apply *function* of two arguments cumulatively to the items of *sequence*, from
135 left to right, so as to reduce the sequence to a single value. For example,
136 ``reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])`` calculates ``((((1+2)+3)+4)+5)``.
137 The left argument, *x*, is the accumulated value and the right argument, *y*, is
138 the update value from the *sequence*. If the optional *initializer* is present,
139 it is placed before the items of the sequence in the calculation, and serves as
140 a default when the sequence is empty. If *initializer* is not given and
141 *sequence* contains only one item, the first item is returned.
142
143
Georg Brandl036490d2009-05-17 13:00:36 +0000144.. function:: update_wrapper(wrapper, wrapped, assigned=WRAPPER_ASSIGNMENTS, updated=WRAPPER_UPDATES)
Georg Brandl116aa622007-08-15 14:28:22 +0000145
146 Update a *wrapper* function to look like the *wrapped* function. The optional
147 arguments are tuples to specify which attributes of the original function are
148 assigned directly to the matching attributes on the wrapper function and which
149 attributes of the wrapper function are updated with the corresponding attributes
150 from the original function. The default values for these arguments are the
151 module level constants *WRAPPER_ASSIGNMENTS* (which assigns to the wrapper
Antoine Pitrou560f7642010-08-04 18:28:02 +0000152 function's *__name__*, *__module__*, *__annotations__* and *__doc__*, the
153 documentation string) and *WRAPPER_UPDATES* (which updates the wrapper
154 function's *__dict__*, i.e. the instance dictionary).
Georg Brandl116aa622007-08-15 14:28:22 +0000155
Nick Coghlan98876832010-08-17 06:17:18 +0000156 To allow access to the original function for introspection and other purposes
157 (e.g. bypassing a caching decorator such as :func:`lru_cache`), this function
Éric Araujoc6ecb012010-11-06 06:33:03 +0000158 automatically adds a __wrapped__ attribute to the wrapper that refers to
Nick Coghlan98876832010-08-17 06:17:18 +0000159 the original function.
160
Christian Heimesd8654cf2007-12-02 15:22:16 +0000161 The main intended use for this function is in :term:`decorator` functions which
162 wrap the decorated function and return the wrapper. If the wrapper function is
163 not updated, the metadata of the returned function will reflect the wrapper
Georg Brandl116aa622007-08-15 14:28:22 +0000164 definition rather than the original function definition, which is typically less
165 than helpful.
166
Nick Coghlan98876832010-08-17 06:17:18 +0000167 :func:`update_wrapper` may be used with callables other than functions. Any
168 attributes named in *assigned* or *updated* that are missing from the object
169 being wrapped are ignored (i.e. this function will not attempt to set them
170 on the wrapper function). :exc:`AttributeError` is still raised if the
171 wrapper function itself is missing any attributes named in *updated*.
172
173 .. versionadded:: 3.2
Georg Brandl9e257012010-08-17 14:11:59 +0000174 Automatic addition of the ``__wrapped__`` attribute.
Nick Coghlan98876832010-08-17 06:17:18 +0000175
176 .. versionadded:: 3.2
Georg Brandl9e257012010-08-17 14:11:59 +0000177 Copying of the ``__annotations__`` attribute by default.
Nick Coghlan98876832010-08-17 06:17:18 +0000178
179 .. versionchanged:: 3.2
Georg Brandl9e257012010-08-17 14:11:59 +0000180 Missing attributes no longer trigger an :exc:`AttributeError`.
181
Georg Brandl116aa622007-08-15 14:28:22 +0000182
Georg Brandl8a1caa22010-07-29 16:01:11 +0000183.. decorator:: wraps(wrapped, assigned=WRAPPER_ASSIGNMENTS, updated=WRAPPER_UPDATES)
Georg Brandl116aa622007-08-15 14:28:22 +0000184
185 This is a convenience function for invoking ``partial(update_wrapper,
186 wrapped=wrapped, assigned=assigned, updated=updated)`` as a function decorator
Christian Heimesfe337bf2008-03-23 21:54:12 +0000187 when defining a wrapper function. For example:
Georg Brandl116aa622007-08-15 14:28:22 +0000188
Christian Heimesfe337bf2008-03-23 21:54:12 +0000189 >>> from functools import wraps
Georg Brandl116aa622007-08-15 14:28:22 +0000190 >>> def my_decorator(f):
191 ... @wraps(f)
192 ... def wrapper(*args, **kwds):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000193 ... print('Calling decorated function')
Georg Brandl116aa622007-08-15 14:28:22 +0000194 ... return f(*args, **kwds)
195 ... return wrapper
196 ...
197 >>> @my_decorator
198 ... def example():
199 ... """Docstring"""
Georg Brandl6911e3c2007-09-04 07:15:32 +0000200 ... print('Called example function')
Georg Brandl116aa622007-08-15 14:28:22 +0000201 ...
202 >>> example()
203 Calling decorated function
204 Called example function
205 >>> example.__name__
206 'example'
207 >>> example.__doc__
208 'Docstring'
209
210 Without the use of this decorator factory, the name of the example function
211 would have been ``'wrapper'``, and the docstring of the original :func:`example`
212 would have been lost.
213
214
215.. _partial-objects:
216
217:class:`partial` Objects
218------------------------
219
220:class:`partial` objects are callable objects created by :func:`partial`. They
221have three read-only attributes:
222
223
224.. attribute:: partial.func
225
226 A callable object or function. Calls to the :class:`partial` object will be
227 forwarded to :attr:`func` with new arguments and keywords.
228
229
230.. attribute:: partial.args
231
232 The leftmost positional arguments that will be prepended to the positional
233 arguments provided to a :class:`partial` object call.
234
235
236.. attribute:: partial.keywords
237
238 The keyword arguments that will be supplied when the :class:`partial` object is
239 called.
240
241:class:`partial` objects are like :class:`function` objects in that they are
242callable, weak referencable, and can have attributes. There are some important
243differences. For instance, the :attr:`__name__` and :attr:`__doc__` attributes
244are not created automatically. Also, :class:`partial` objects defined in
245classes behave like static methods and do not transform into bound methods
246during instance attribute look-up.
247