blob: d7287bb67b5851645d57145f91a2e345bed53be5 [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:: lru_cache(maxsize)
40
41 Decorator to wrap a function with a memoizing callable that saves up to the
42 *maxsize* most recent calls. It can save time when an expensive or I/O bound
43 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 `LRU (least recently used) cache
58 <http://en.wikipedia.org/wiki/Cache_algorithms#Least_Recently_Used>`_
59 is indicated when the pattern of calls changes over time, such as
Raymond Hettingerc8dc62d2010-08-02 00:59:14 +000060 when more recent calls are the best predictors of upcoming calls
61 (for example, the most popular articles on a news server tend to
62 change every day).
Georg Brandl2e7346a2010-07-31 18:09:23 +000063
64 .. versionadded:: 3.2
65
Georg Brandl8a1caa22010-07-29 16:01:11 +000066.. decorator:: total_ordering
Raymond Hettingerc50846a2010-04-05 18:56:31 +000067
68 Given a class defining one or more rich comparison ordering methods, this
Benjamin Peterson08bf91c2010-04-11 16:12:57 +000069 class decorator supplies the rest. This simplifies the effort involved
Raymond Hettingerc50846a2010-04-05 18:56:31 +000070 in specifying all of the possible rich comparison operations:
71
72 The class must define one of :meth:`__lt__`, :meth:`__le__`,
73 :meth:`__gt__`, or :meth:`__ge__`.
74 In addition, the class should supply an :meth:`__eq__` method.
75
76 For example::
77
78 @total_ordering
79 class Student:
80 def __eq__(self, other):
81 return ((self.lastname.lower(), self.firstname.lower()) ==
82 (other.lastname.lower(), other.firstname.lower()))
83 def __lt__(self, other):
84 return ((self.lastname.lower(), self.firstname.lower()) <
85 (other.lastname.lower(), other.firstname.lower()))
86
87 .. versionadded:: 3.2
88
Georg Brandl036490d2009-05-17 13:00:36 +000089.. function:: partial(func, *args, **keywords)
Georg Brandl116aa622007-08-15 14:28:22 +000090
91 Return a new :class:`partial` object which when called will behave like *func*
92 called with the positional arguments *args* and keyword arguments *keywords*. If
93 more arguments are supplied to the call, they are appended to *args*. If
94 additional keyword arguments are supplied, they extend and override *keywords*.
95 Roughly equivalent to::
96
97 def partial(func, *args, **keywords):
98 def newfunc(*fargs, **fkeywords):
99 newkeywords = keywords.copy()
100 newkeywords.update(fkeywords)
101 return func(*(args + fargs), **newkeywords)
102 newfunc.func = func
103 newfunc.args = args
104 newfunc.keywords = keywords
105 return newfunc
106
107 The :func:`partial` is used for partial function application which "freezes"
108 some portion of a function's arguments and/or keywords resulting in a new object
109 with a simplified signature. For example, :func:`partial` can be used to create
110 a callable that behaves like the :func:`int` function where the *base* argument
Christian Heimesfe337bf2008-03-23 21:54:12 +0000111 defaults to two:
Georg Brandl116aa622007-08-15 14:28:22 +0000112
Christian Heimesfe337bf2008-03-23 21:54:12 +0000113 >>> from functools import partial
Georg Brandl116aa622007-08-15 14:28:22 +0000114 >>> basetwo = partial(int, base=2)
115 >>> basetwo.__doc__ = 'Convert base 2 string to an int.'
116 >>> basetwo('10010')
117 18
118
119
Georg Brandl58f9e4f2008-04-19 22:18:33 +0000120.. function:: reduce(function, iterable[, initializer])
Georg Brandl116aa622007-08-15 14:28:22 +0000121
122 Apply *function* of two arguments cumulatively to the items of *sequence*, from
123 left to right, so as to reduce the sequence to a single value. For example,
124 ``reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])`` calculates ``((((1+2)+3)+4)+5)``.
125 The left argument, *x*, is the accumulated value and the right argument, *y*, is
126 the update value from the *sequence*. If the optional *initializer* is present,
127 it is placed before the items of the sequence in the calculation, and serves as
128 a default when the sequence is empty. If *initializer* is not given and
129 *sequence* contains only one item, the first item is returned.
130
131
Georg Brandl036490d2009-05-17 13:00:36 +0000132.. function:: update_wrapper(wrapper, wrapped, assigned=WRAPPER_ASSIGNMENTS, updated=WRAPPER_UPDATES)
Georg Brandl116aa622007-08-15 14:28:22 +0000133
134 Update a *wrapper* function to look like the *wrapped* function. The optional
135 arguments are tuples to specify which attributes of the original function are
136 assigned directly to the matching attributes on the wrapper function and which
137 attributes of the wrapper function are updated with the corresponding attributes
138 from the original function. The default values for these arguments are the
139 module level constants *WRAPPER_ASSIGNMENTS* (which assigns to the wrapper
Antoine Pitrou560f7642010-08-04 18:28:02 +0000140 function's *__name__*, *__module__*, *__annotations__* and *__doc__*, the
141 documentation string) and *WRAPPER_UPDATES* (which updates the wrapper
142 function's *__dict__*, i.e. the instance dictionary).
Georg Brandl116aa622007-08-15 14:28:22 +0000143
Christian Heimesd8654cf2007-12-02 15:22:16 +0000144 The main intended use for this function is in :term:`decorator` functions which
145 wrap the decorated function and return the wrapper. If the wrapper function is
146 not updated, the metadata of the returned function will reflect the wrapper
Georg Brandl116aa622007-08-15 14:28:22 +0000147 definition rather than the original function definition, which is typically less
148 than helpful.
149
150
Georg Brandl8a1caa22010-07-29 16:01:11 +0000151.. decorator:: wraps(wrapped, assigned=WRAPPER_ASSIGNMENTS, updated=WRAPPER_UPDATES)
Georg Brandl116aa622007-08-15 14:28:22 +0000152
153 This is a convenience function for invoking ``partial(update_wrapper,
154 wrapped=wrapped, assigned=assigned, updated=updated)`` as a function decorator
Christian Heimesfe337bf2008-03-23 21:54:12 +0000155 when defining a wrapper function. For example:
Georg Brandl116aa622007-08-15 14:28:22 +0000156
Christian Heimesfe337bf2008-03-23 21:54:12 +0000157 >>> from functools import wraps
Georg Brandl116aa622007-08-15 14:28:22 +0000158 >>> def my_decorator(f):
159 ... @wraps(f)
160 ... def wrapper(*args, **kwds):
Georg Brandl6911e3c2007-09-04 07:15:32 +0000161 ... print('Calling decorated function')
Georg Brandl116aa622007-08-15 14:28:22 +0000162 ... return f(*args, **kwds)
163 ... return wrapper
164 ...
165 >>> @my_decorator
166 ... def example():
167 ... """Docstring"""
Georg Brandl6911e3c2007-09-04 07:15:32 +0000168 ... print('Called example function')
Georg Brandl116aa622007-08-15 14:28:22 +0000169 ...
170 >>> example()
171 Calling decorated function
172 Called example function
173 >>> example.__name__
174 'example'
175 >>> example.__doc__
176 'Docstring'
177
178 Without the use of this decorator factory, the name of the example function
179 would have been ``'wrapper'``, and the docstring of the original :func:`example`
180 would have been lost.
181
182
183.. _partial-objects:
184
185:class:`partial` Objects
186------------------------
187
188:class:`partial` objects are callable objects created by :func:`partial`. They
189have three read-only attributes:
190
191
192.. attribute:: partial.func
193
194 A callable object or function. Calls to the :class:`partial` object will be
195 forwarded to :attr:`func` with new arguments and keywords.
196
197
198.. attribute:: partial.args
199
200 The leftmost positional arguments that will be prepended to the positional
201 arguments provided to a :class:`partial` object call.
202
203
204.. attribute:: partial.keywords
205
206 The keyword arguments that will be supplied when the :class:`partial` object is
207 called.
208
209:class:`partial` objects are like :class:`function` objects in that they are
210callable, weak referencable, and can have attributes. There are some important
211differences. For instance, the :attr:`__name__` and :attr:`__doc__` attributes
212are not created automatically. Also, :class:`partial` objects defined in
213classes behave like static methods and do not transform into bound methods
214during instance attribute look-up.
215