blob: 20bbe54956c98fe07d4e8b38a23cddc0f29be233 [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 Brandl67b21b72010-08-17 15:07:14 +000039
Georg Brandl2e7346a2010-07-31 18:09:23 +000040.. decorator:: lru_cache(maxsize)
41
42 Decorator to wrap a function with a memoizing callable that saves up to the
43 *maxsize* most recent calls. It can save time when an expensive or I/O bound
44 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
Nick Coghlan98876832010-08-17 06:17:18 +000058 The :attr:`__wrapped__` attribute may be used to access the original
59 function (e.g. to bypass the cache or to apply a different caching
60 strategy)
61
Georg Brandl2e7346a2010-07-31 18:09:23 +000062 A `LRU (least recently used) cache
63 <http://en.wikipedia.org/wiki/Cache_algorithms#Least_Recently_Used>`_
64 is indicated when the pattern of calls changes over time, such as
Raymond Hettingerc8dc62d2010-08-02 00:59:14 +000065 when more recent calls are the best predictors of upcoming calls
66 (for example, the most popular articles on a news server tend to
67 change every day).
Georg Brandl2e7346a2010-07-31 18:09:23 +000068
69 .. versionadded:: 3.2
70
Georg Brandl67b21b72010-08-17 15:07:14 +000071
Georg Brandl8a1caa22010-07-29 16:01:11 +000072.. decorator:: total_ordering
Raymond Hettingerc50846a2010-04-05 18:56:31 +000073
74 Given a class defining one or more rich comparison ordering methods, this
Benjamin Peterson08bf91c2010-04-11 16:12:57 +000075 class decorator supplies the rest. This simplifies the effort involved
Raymond Hettingerc50846a2010-04-05 18:56:31 +000076 in specifying all of the possible rich comparison operations:
77
78 The class must define one of :meth:`__lt__`, :meth:`__le__`,
79 :meth:`__gt__`, or :meth:`__ge__`.
80 In addition, the class should supply an :meth:`__eq__` method.
81
82 For example::
83
84 @total_ordering
85 class Student:
86 def __eq__(self, other):
87 return ((self.lastname.lower(), self.firstname.lower()) ==
88 (other.lastname.lower(), other.firstname.lower()))
89 def __lt__(self, other):
90 return ((self.lastname.lower(), self.firstname.lower()) <
91 (other.lastname.lower(), other.firstname.lower()))
92
93 .. versionadded:: 3.2
94
Georg Brandl67b21b72010-08-17 15:07:14 +000095
Georg Brandl036490d2009-05-17 13:00:36 +000096.. function:: partial(func, *args, **keywords)
Georg Brandl116aa622007-08-15 14:28:22 +000097
98 Return a new :class:`partial` object which when called will behave like *func*
99 called with the positional arguments *args* and keyword arguments *keywords*. If
100 more arguments are supplied to the call, they are appended to *args*. If
101 additional keyword arguments are supplied, they extend and override *keywords*.
102 Roughly equivalent to::
103
104 def partial(func, *args, **keywords):
105 def newfunc(*fargs, **fkeywords):
106 newkeywords = keywords.copy()
107 newkeywords.update(fkeywords)
108 return func(*(args + fargs), **newkeywords)
109 newfunc.func = func
110 newfunc.args = args
111 newfunc.keywords = keywords
112 return newfunc
113
114 The :func:`partial` is used for partial function application which "freezes"
115 some portion of a function's arguments and/or keywords resulting in a new object
116 with a simplified signature. For example, :func:`partial` can be used to create
117 a callable that behaves like the :func:`int` function where the *base* argument
Christian Heimesfe337bf2008-03-23 21:54:12 +0000118 defaults to two:
Georg Brandl116aa622007-08-15 14:28:22 +0000119
Christian Heimesfe337bf2008-03-23 21:54:12 +0000120 >>> from functools import partial
Georg Brandl116aa622007-08-15 14:28:22 +0000121 >>> basetwo = partial(int, base=2)
122 >>> basetwo.__doc__ = 'Convert base 2 string to an int.'
123 >>> basetwo('10010')
124 18
125
126
Georg Brandl58f9e4f2008-04-19 22:18:33 +0000127.. function:: reduce(function, iterable[, initializer])
Georg Brandl116aa622007-08-15 14:28:22 +0000128
129 Apply *function* of two arguments cumulatively to the items of *sequence*, from
130 left to right, so as to reduce the sequence to a single value. For example,
131 ``reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])`` calculates ``((((1+2)+3)+4)+5)``.
132 The left argument, *x*, is the accumulated value and the right argument, *y*, is
133 the update value from the *sequence*. If the optional *initializer* is present,
134 it is placed before the items of the sequence in the calculation, and serves as
135 a default when the sequence is empty. If *initializer* is not given and
136 *sequence* contains only one item, the first item is returned.
137
138
Georg Brandl036490d2009-05-17 13:00:36 +0000139.. function:: update_wrapper(wrapper, wrapped, assigned=WRAPPER_ASSIGNMENTS, updated=WRAPPER_UPDATES)
Georg Brandl116aa622007-08-15 14:28:22 +0000140
141 Update a *wrapper* function to look like the *wrapped* function. The optional
142 arguments are tuples to specify which attributes of the original function are
143 assigned directly to the matching attributes on the wrapper function and which
144 attributes of the wrapper function are updated with the corresponding attributes
145 from the original function. The default values for these arguments are the
146 module level constants *WRAPPER_ASSIGNMENTS* (which assigns to the wrapper
Antoine Pitrou560f7642010-08-04 18:28:02 +0000147 function's *__name__*, *__module__*, *__annotations__* and *__doc__*, the
148 documentation string) and *WRAPPER_UPDATES* (which updates the wrapper
149 function's *__dict__*, i.e. the instance dictionary).
Georg Brandl116aa622007-08-15 14:28:22 +0000150
Nick Coghlan98876832010-08-17 06:17:18 +0000151 To allow access to the original function for introspection and other purposes
152 (e.g. bypassing a caching decorator such as :func:`lru_cache`), this function
153 automatically adds a __wrapped__ attribute to the the wrapped that refers to
154 the original function.
155
Christian Heimesd8654cf2007-12-02 15:22:16 +0000156 The main intended use for this function is in :term:`decorator` functions which
157 wrap the decorated function and return the wrapper. If the wrapper function is
158 not updated, the metadata of the returned function will reflect the wrapper
Georg Brandl116aa622007-08-15 14:28:22 +0000159 definition rather than the original function definition, which is typically less
160 than helpful.
161
Nick Coghlan98876832010-08-17 06:17:18 +0000162 :func:`update_wrapper` may be used with callables other than functions. Any
163 attributes named in *assigned* or *updated* that are missing from the object
164 being wrapped are ignored (i.e. this function will not attempt to set them
165 on the wrapper function). :exc:`AttributeError` is still raised if the
166 wrapper function itself is missing any attributes named in *updated*.
167
168 .. versionadded:: 3.2
Georg Brandl9e257012010-08-17 14:11:59 +0000169 Automatic addition of the ``__wrapped__`` attribute.
Nick Coghlan98876832010-08-17 06:17:18 +0000170
171 .. versionadded:: 3.2
Georg Brandl9e257012010-08-17 14:11:59 +0000172 Copying of the ``__annotations__`` attribute by default.
Nick Coghlan98876832010-08-17 06:17:18 +0000173
174 .. versionchanged:: 3.2
Georg Brandl9e257012010-08-17 14:11:59 +0000175 Missing attributes no longer trigger an :exc:`AttributeError`.
176
Georg Brandl116aa622007-08-15 14:28:22 +0000177
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