blob: b2d69deb8c33da8d6d8643372c7ffb1eb13745e5 [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
20 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`).
24 This function is primarily used as a transition tool for programs
25 being converted from Py2.x which supported the use of comparison
26 functions.
27
28 A compare function is any callable that accept two arguments, compares
29 them, and returns a negative number for less-than, zero for equality,
30 or a positive number for greater-than. A key function is a callable
31 that accepts one argument and returns another value that indicates
32 the position in the desired collation sequence.
33
34 Example::
35
36 sorted(iterable, key=cmp_to_key(locale.strcoll)) # locale-aware sort order
37
38 .. versionadded:: 3.2
39
Georg Brandl2e7346a2010-07-31 18:09:23 +000040.. decorator:: lfu_cache(maxsize)
41
42 Decorator to wrap a function with a memoizing callable that saves up to the
43 *maxsize* most frequent calls. It can save time when an expensive or I/O
44 bound function is periodically called with the same arguments.
45
46 The *maxsize* parameter defaults to 100. Since a dictionary is used to cache
47 results, the positional and keyword arguments to the function must be
48 hashable.
49
50 The wrapped function is instrumented with two attributes, :attr:`hits`
51 and :attr:`misses` which count the number of successful or unsuccessful
52 cache lookups. These statistics are helpful for tuning the *maxsize*
53 parameter and for measuring the cache's effectiveness.
54
55 The wrapped function also has a :attr:`clear` attribute which can be
56 called (with no arguments) to clear the cache.
57
58 A `LFU (least frequently used) cache
59 <http://en.wikipedia.org/wiki/Cache_algorithms#Least-Frequently_Used>`_
60 is indicated when the pattern of calls does not change over time, when
61 more the most common calls already seen are the best predictors of the
62 most common upcoming calls.
63
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
87 when more recent calls are the best predictors of upcoming calls.
88
89 .. versionadded:: 3.2
90
Georg Brandl8a1caa22010-07-29 16:01:11 +000091.. decorator:: total_ordering
Raymond Hettingerc50846a2010-04-05 18:56:31 +000092
93 Given a class defining one or more rich comparison ordering methods, this
Benjamin Peterson08bf91c2010-04-11 16:12:57 +000094 class decorator supplies the rest. This simplifies the effort involved
Raymond Hettingerc50846a2010-04-05 18:56:31 +000095 in specifying all of the possible rich comparison operations:
96
97 The class must define one of :meth:`__lt__`, :meth:`__le__`,
98 :meth:`__gt__`, or :meth:`__ge__`.
99 In addition, the class should supply an :meth:`__eq__` method.
100
101 For example::
102
103 @total_ordering
104 class Student:
105 def __eq__(self, other):
106 return ((self.lastname.lower(), self.firstname.lower()) ==
107 (other.lastname.lower(), other.firstname.lower()))
108 def __lt__(self, other):
109 return ((self.lastname.lower(), self.firstname.lower()) <
110 (other.lastname.lower(), other.firstname.lower()))
111
112 .. versionadded:: 3.2
113
Georg Brandl036490d2009-05-17 13:00:36 +0000114.. function:: partial(func, *args, **keywords)
Georg Brandl116aa622007-08-15 14:28:22 +0000115
116 Return a new :class:`partial` object which when called will behave like *func*
117 called with the positional arguments *args* and keyword arguments *keywords*. If
118 more arguments are supplied to the call, they are appended to *args*. If
119 additional keyword arguments are supplied, they extend and override *keywords*.
120 Roughly equivalent to::
121
122 def partial(func, *args, **keywords):
123 def newfunc(*fargs, **fkeywords):
124 newkeywords = keywords.copy()
125 newkeywords.update(fkeywords)
126 return func(*(args + fargs), **newkeywords)
127 newfunc.func = func
128 newfunc.args = args
129 newfunc.keywords = keywords
130 return newfunc
131
132 The :func:`partial` is used for partial function application which "freezes"
133 some portion of a function's arguments and/or keywords resulting in a new object
134 with a simplified signature. For example, :func:`partial` can be used to create
135 a callable that behaves like the :func:`int` function where the *base* argument
Christian Heimesfe337bf2008-03-23 21:54:12 +0000136 defaults to two:
Georg Brandl116aa622007-08-15 14:28:22 +0000137
Christian Heimesfe337bf2008-03-23 21:54:12 +0000138 >>> from functools import partial
Georg Brandl116aa622007-08-15 14:28:22 +0000139 >>> basetwo = partial(int, base=2)
140 >>> basetwo.__doc__ = 'Convert base 2 string to an int.'
141 >>> basetwo('10010')
142 18
143
144
Georg Brandl58f9e4f2008-04-19 22:18:33 +0000145.. function:: reduce(function, iterable[, initializer])
Georg Brandl116aa622007-08-15 14:28:22 +0000146
147 Apply *function* of two arguments cumulatively to the items of *sequence*, from
148 left to right, so as to reduce the sequence to a single value. For example,
149 ``reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])`` calculates ``((((1+2)+3)+4)+5)``.
150 The left argument, *x*, is the accumulated value and the right argument, *y*, is
151 the update value from the *sequence*. If the optional *initializer* is present,
152 it is placed before the items of the sequence in the calculation, and serves as
153 a default when the sequence is empty. If *initializer* is not given and
154 *sequence* contains only one item, the first item is returned.
155
156
Georg Brandl036490d2009-05-17 13:00:36 +0000157.. function:: update_wrapper(wrapper, wrapped, assigned=WRAPPER_ASSIGNMENTS, updated=WRAPPER_UPDATES)
Georg Brandl116aa622007-08-15 14:28:22 +0000158
159 Update a *wrapper* function to look like the *wrapped* function. The optional
160 arguments are tuples to specify which attributes of the original function are
161 assigned directly to the matching attributes on the wrapper function and which
162 attributes of the wrapper function are updated with the corresponding attributes
163 from the original function. The default values for these arguments are the
164 module level constants *WRAPPER_ASSIGNMENTS* (which assigns to the wrapper
165 function's *__name__*, *__module__* and *__doc__*, the documentation string) and
166 *WRAPPER_UPDATES* (which updates the wrapper function's *__dict__*, i.e. the
167 instance dictionary).
168
Christian Heimesd8654cf2007-12-02 15:22:16 +0000169 The main intended use for this function is in :term:`decorator` functions which
170 wrap the decorated function and return the wrapper. If the wrapper function is
171 not updated, the metadata of the returned function will reflect the wrapper
Georg Brandl116aa622007-08-15 14:28:22 +0000172 definition rather than the original function definition, which is typically less
173 than helpful.
174
175
Georg Brandl8a1caa22010-07-29 16:01:11 +0000176.. decorator:: wraps(wrapped, assigned=WRAPPER_ASSIGNMENTS, updated=WRAPPER_UPDATES)
Georg Brandl116aa622007-08-15 14:28:22 +0000177
178 This is a convenience function for invoking ``partial(update_wrapper,
179 wrapped=wrapped, assigned=assigned, updated=updated)`` as a function decorator
Christian Heimesfe337bf2008-03-23 21:54:12 +0000180 when defining a wrapper function. For example:
Georg Brandl116aa622007-08-15 14:28:22 +0000181
Christian Heimesfe337bf2008-03-23 21:54:12 +0000182 >>> from functools import wraps
Georg Brandl116aa622007-08-15 14:28:22 +0000183 >>> def my_decorator(f):
184 ... @wraps(f)
185 ... def wrapper(*args, **kwds):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000186 ... print('Calling decorated function')
Georg Brandl116aa622007-08-15 14:28:22 +0000187 ... return f(*args, **kwds)
188 ... return wrapper
189 ...
190 >>> @my_decorator
191 ... def example():
192 ... """Docstring"""
Georg Brandl6911e3c2007-09-04 07:15:32 +0000193 ... print('Called example function')
Georg Brandl116aa622007-08-15 14:28:22 +0000194 ...
195 >>> example()
196 Calling decorated function
197 Called example function
198 >>> example.__name__
199 'example'
200 >>> example.__doc__
201 'Docstring'
202
203 Without the use of this decorator factory, the name of the example function
204 would have been ``'wrapper'``, and the docstring of the original :func:`example`
205 would have been lost.
206
207
208.. _partial-objects:
209
210:class:`partial` Objects
211------------------------
212
213:class:`partial` objects are callable objects created by :func:`partial`. They
214have three read-only attributes:
215
216
217.. attribute:: partial.func
218
219 A callable object or function. Calls to the :class:`partial` object will be
220 forwarded to :attr:`func` with new arguments and keywords.
221
222
223.. attribute:: partial.args
224
225 The leftmost positional arguments that will be prepended to the positional
226 arguments provided to a :class:`partial` object call.
227
228
229.. attribute:: partial.keywords
230
231 The keyword arguments that will be supplied when the :class:`partial` object is
232 called.
233
234:class:`partial` objects are like :class:`function` objects in that they are
235callable, weak referencable, and can have attributes. There are some important
236differences. For instance, the :attr:`__name__` and :attr:`__doc__` attributes
237are not created automatically. Also, :class:`partial` objects defined in
238classes behave like static methods and do not transform into bound methods
239during instance attribute look-up.
240