blob: 77e92f819e09ee37d96535bee3e0b8118f448776 [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
Thomas Woutersed03b412007-08-28 21:37:11 +000016The :mod:`functools` module defines the following functions:
17
Raymond Hettingerc50846a2010-04-05 18:56:31 +000018.. function:: cmp_to_key(func)
19
Benjamin Petersoncca65312010-08-09 02:13:10 +000020 Transform an old-style comparison function to a key-function. Used with
21 tools that accept key functions (such as :func:`sorted`, :func:`min`,
22 :func:`max`, :func:`heapq.nlargest`, :func:`heapq.nsmallest`,
23 :func:`itertools.groupby`). This function is primarily used as a transition
24 tool for programs being converted from Py2.x which supported the use of
25 comparison functions.
Raymond Hettingerc50846a2010-04-05 18:56:31 +000026
Benjamin Petersoncca65312010-08-09 02:13:10 +000027 A compare function is any callable that accept two arguments, compares them,
28 and returns a negative number for less-than, zero for equality, or a positive
29 number for greater-than. A key function is a callable that accepts one
30 argument and returns another value that indicates the position in the desired
31 collation sequence.
Raymond Hettingerc50846a2010-04-05 18:56:31 +000032
Benjamin Petersoncca65312010-08-09 02:13:10 +000033 Example::
Raymond Hettingerc50846a2010-04-05 18:56:31 +000034
Benjamin Petersoncca65312010-08-09 02:13:10 +000035 sorted(iterable, key=cmp_to_key(locale.strcoll)) # locale-aware sort order
Raymond Hettingerc50846a2010-04-05 18:56:31 +000036
37 .. versionadded:: 3.2
38
Georg Brandl2e7346a2010-07-31 18:09:23 +000039.. decorator:: lfu_cache(maxsize)
40
41 Decorator to wrap a function with a memoizing callable that saves up to the
42 *maxsize* most frequent calls. It can save time when an expensive or I/O
43 bound function is periodically called with the same arguments.
44
45 The *maxsize* parameter defaults to 100. Since a dictionary is used to cache
46 results, the positional and keyword arguments to the function must be
47 hashable.
48
49 The wrapped function is instrumented with two attributes, :attr:`hits`
50 and :attr:`misses` which count the number of successful or unsuccessful
51 cache lookups. These statistics are helpful for tuning the *maxsize*
52 parameter and for measuring the cache's effectiveness.
53
54 The wrapped function also has a :attr:`clear` attribute which can be
55 called (with no arguments) to clear the cache.
56
57 A `LFU (least frequently used) cache
58 <http://en.wikipedia.org/wiki/Cache_algorithms#Least-Frequently_Used>`_
59 is indicated when the pattern of calls does not change over time, when
60 more the most common calls already seen are the best predictors of the
Raymond Hettingerc8dc62d2010-08-02 00:59:14 +000061 most common upcoming calls (for example, a phonelist of popular
62 help-lines may have access patterns that persist over time).
Georg Brandl2e7346a2010-07-31 18:09:23 +000063
64 .. versionadded:: 3.2
65
66.. decorator:: lru_cache(maxsize)
67
68 Decorator to wrap a function with a memoizing callable that saves up to the
69 *maxsize* most recent calls. It can save time when an expensive or I/O bound
70 function is periodically called with the same arguments.
71
72 The *maxsize* parameter defaults to 100. Since a dictionary is used to cache
73 results, the positional and keyword arguments to the function must be
74 hashable.
75
76 The wrapped function is instrumented with two attributes, :attr:`hits`
77 and :attr:`misses` which count the number of successful or unsuccessful
78 cache lookups. These statistics are helpful for tuning the *maxsize*
79 parameter and for measuring the cache's effectiveness.
80
81 The wrapped function also has a :attr:`clear` attribute which can be
82 called (with no arguments) to clear the cache.
83
84 A `LRU (least recently used) cache
85 <http://en.wikipedia.org/wiki/Cache_algorithms#Least_Recently_Used>`_
86 is indicated when the pattern of calls changes over time, such as
Raymond Hettingerc8dc62d2010-08-02 00:59:14 +000087 when more recent calls are the best predictors of upcoming calls
88 (for example, the most popular articles on a news server tend to
89 change every day).
Georg Brandl2e7346a2010-07-31 18:09:23 +000090
91 .. versionadded:: 3.2
92
Georg Brandl8a1caa22010-07-29 16:01:11 +000093.. decorator:: total_ordering
Raymond Hettingerc50846a2010-04-05 18:56:31 +000094
95 Given a class defining one or more rich comparison ordering methods, this
Benjamin Peterson08bf91c2010-04-11 16:12:57 +000096 class decorator supplies the rest. This simplifies the effort involved
Raymond Hettingerc50846a2010-04-05 18:56:31 +000097 in specifying all of the possible rich comparison operations:
98
99 The class must define one of :meth:`__lt__`, :meth:`__le__`,
100 :meth:`__gt__`, or :meth:`__ge__`.
101 In addition, the class should supply an :meth:`__eq__` method.
102
103 For example::
104
105 @total_ordering
106 class Student:
107 def __eq__(self, other):
108 return ((self.lastname.lower(), self.firstname.lower()) ==
109 (other.lastname.lower(), other.firstname.lower()))
110 def __lt__(self, other):
111 return ((self.lastname.lower(), self.firstname.lower()) <
112 (other.lastname.lower(), other.firstname.lower()))
113
114 .. versionadded:: 3.2
115
Georg Brandl036490d2009-05-17 13:00:36 +0000116.. function:: partial(func, *args, **keywords)
Georg Brandl116aa622007-08-15 14:28:22 +0000117
118 Return a new :class:`partial` object which when called will behave like *func*
119 called with the positional arguments *args* and keyword arguments *keywords*. If
120 more arguments are supplied to the call, they are appended to *args*. If
121 additional keyword arguments are supplied, they extend and override *keywords*.
122 Roughly equivalent to::
123
124 def partial(func, *args, **keywords):
125 def newfunc(*fargs, **fkeywords):
126 newkeywords = keywords.copy()
127 newkeywords.update(fkeywords)
128 return func(*(args + fargs), **newkeywords)
129 newfunc.func = func
130 newfunc.args = args
131 newfunc.keywords = keywords
132 return newfunc
133
134 The :func:`partial` is used for partial function application which "freezes"
135 some portion of a function's arguments and/or keywords resulting in a new object
136 with a simplified signature. For example, :func:`partial` can be used to create
137 a callable that behaves like the :func:`int` function where the *base* argument
Christian Heimesfe337bf2008-03-23 21:54:12 +0000138 defaults to two:
Georg Brandl116aa622007-08-15 14:28:22 +0000139
Christian Heimesfe337bf2008-03-23 21:54:12 +0000140 >>> from functools import partial
Georg Brandl116aa622007-08-15 14:28:22 +0000141 >>> basetwo = partial(int, base=2)
142 >>> basetwo.__doc__ = 'Convert base 2 string to an int.'
143 >>> basetwo('10010')
144 18
145
146
Georg Brandl58f9e4f2008-04-19 22:18:33 +0000147.. function:: reduce(function, iterable[, initializer])
Georg Brandl116aa622007-08-15 14:28:22 +0000148
149 Apply *function* of two arguments cumulatively to the items of *sequence*, from
150 left to right, so as to reduce the sequence to a single value. For example,
151 ``reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])`` calculates ``((((1+2)+3)+4)+5)``.
152 The left argument, *x*, is the accumulated value and the right argument, *y*, is
153 the update value from the *sequence*. If the optional *initializer* is present,
154 it is placed before the items of the sequence in the calculation, and serves as
155 a default when the sequence is empty. If *initializer* is not given and
156 *sequence* contains only one item, the first item is returned.
157
158
Georg Brandl036490d2009-05-17 13:00:36 +0000159.. function:: update_wrapper(wrapper, wrapped, assigned=WRAPPER_ASSIGNMENTS, updated=WRAPPER_UPDATES)
Georg Brandl116aa622007-08-15 14:28:22 +0000160
161 Update a *wrapper* function to look like the *wrapped* function. The optional
162 arguments are tuples to specify which attributes of the original function are
163 assigned directly to the matching attributes on the wrapper function and which
164 attributes of the wrapper function are updated with the corresponding attributes
165 from the original function. The default values for these arguments are the
166 module level constants *WRAPPER_ASSIGNMENTS* (which assigns to the wrapper
Antoine Pitrou560f7642010-08-04 18:28:02 +0000167 function's *__name__*, *__module__*, *__annotations__* and *__doc__*, the
168 documentation string) and *WRAPPER_UPDATES* (which updates the wrapper
169 function's *__dict__*, i.e. the instance dictionary).
Georg Brandl116aa622007-08-15 14:28:22 +0000170
Christian Heimesd8654cf2007-12-02 15:22:16 +0000171 The main intended use for this function is in :term:`decorator` functions which
172 wrap the decorated function and return the wrapper. If the wrapper function is
173 not updated, the metadata of the returned function will reflect the wrapper
Georg Brandl116aa622007-08-15 14:28:22 +0000174 definition rather than the original function definition, which is typically less
175 than helpful.
176
177
Georg Brandl8a1caa22010-07-29 16:01:11 +0000178.. decorator:: wraps(wrapped, assigned=WRAPPER_ASSIGNMENTS, updated=WRAPPER_UPDATES)
Georg Brandl116aa622007-08-15 14:28:22 +0000179
180 This is a convenience function for invoking ``partial(update_wrapper,
181 wrapped=wrapped, assigned=assigned, updated=updated)`` as a function decorator
Christian Heimesfe337bf2008-03-23 21:54:12 +0000182 when defining a wrapper function. For example:
Georg Brandl116aa622007-08-15 14:28:22 +0000183
Christian Heimesfe337bf2008-03-23 21:54:12 +0000184 >>> from functools import wraps
Georg Brandl116aa622007-08-15 14:28:22 +0000185 >>> def my_decorator(f):
186 ... @wraps(f)
187 ... def wrapper(*args, **kwds):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000188 ... print('Calling decorated function')
Georg Brandl116aa622007-08-15 14:28:22 +0000189 ... return f(*args, **kwds)
190 ... return wrapper
191 ...
192 >>> @my_decorator
193 ... def example():
194 ... """Docstring"""
Georg Brandl6911e3c2007-09-04 07:15:32 +0000195 ... print('Called example function')
Georg Brandl116aa622007-08-15 14:28:22 +0000196 ...
197 >>> example()
198 Calling decorated function
199 Called example function
200 >>> example.__name__
201 'example'
202 >>> example.__doc__
203 'Docstring'
204
205 Without the use of this decorator factory, the name of the example function
206 would have been ``'wrapper'``, and the docstring of the original :func:`example`
207 would have been lost.
208
209
210.. _partial-objects:
211
212:class:`partial` Objects
213------------------------
214
215:class:`partial` objects are callable objects created by :func:`partial`. They
216have three read-only attributes:
217
218
219.. attribute:: partial.func
220
221 A callable object or function. Calls to the :class:`partial` object will be
222 forwarded to :attr:`func` with new arguments and keywords.
223
224
225.. attribute:: partial.args
226
227 The leftmost positional arguments that will be prepended to the positional
228 arguments provided to a :class:`partial` object call.
229
230
231.. attribute:: partial.keywords
232
233 The keyword arguments that will be supplied when the :class:`partial` object is
234 called.
235
236:class:`partial` objects are like :class:`function` objects in that they are
237callable, weak referencable, and can have attributes. There are some important
238differences. For instance, the :attr:`__name__` and :attr:`__doc__` attributes
239are not created automatically. Also, :class:`partial` objects defined in
240classes behave like static methods and do not transform into bound methods
241during instance attribute look-up.
242