blob: 0c5e57b0b0e12bb0dbff3787590c2078b4c7b37c [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +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
12.. versionadded:: 2.5
13
14The :mod:`functools` module is for higher-order functions: functions that act on
15or return other functions. In general, any callable object can be treated as a
16function for the purposes of this module.
17
Georg Brandlae0ee8a2007-08-28 08:29:08 +000018The :mod:`functools` module defines the following functions:
19
Raymond Hettingerbb006cf2010-04-04 21:45:01 +000020.. function:: cmp_to_key(func)
Raymond Hettingera551f312010-04-04 18:34:45 +000021
Benjamin Petersond74ca122010-08-09 02:17:24 +000022 Transform an old-style comparison function to a key-function. Used with
23 tools that accept key functions (such as :func:`sorted`, :func:`min`,
24 :func:`max`, :func:`heapq.nlargest`, :func:`heapq.nsmallest`,
25 :func:`itertools.groupby`). This function is primarily used as a transition
26 tool for programs being converted to Py3.x where comparison functions are no
27 longer supported.
Raymond Hettingera551f312010-04-04 18:34:45 +000028
Benjamin Petersond74ca122010-08-09 02:17:24 +000029 A compare function is any callable that accept two arguments, compares them,
30 and returns a negative number for less-than, zero for equality, or a positive
31 number for greater-than. A key function is a callable that accepts one
32 argument and returns another value that indicates the position in the desired
33 collation sequence.
Raymond Hettingera551f312010-04-04 18:34:45 +000034
Benjamin Petersond74ca122010-08-09 02:17:24 +000035 Example::
Raymond Hettingera551f312010-04-04 18:34:45 +000036
Benjamin Petersond74ca122010-08-09 02:17:24 +000037 sorted(iterable, key=cmp_to_key(locale.strcoll)) # locale-aware sort order
Raymond Hettingera551f312010-04-04 18:34:45 +000038
39 .. versionadded:: 2.7
40
Raymond Hettinger20ae90d2010-04-04 01:24:59 +000041.. function:: total_ordering(cls)
42
43 Given a class defining one or more rich comparison ordering methods, this
Andrew M. Kuchling884d0a32010-04-11 12:48:08 +000044 class decorator supplies the rest. This simplifies the effort involved
Raymond Hettinger20ae90d2010-04-04 01:24:59 +000045 in specifying all of the possible rich comparison operations:
46
47 The class must define one of :meth:`__lt__`, :meth:`__le__`,
48 :meth:`__gt__`, or :meth:`__ge__`.
49 In addition, the class should supply an :meth:`__eq__` method.
50
51 For example::
52
53 @total_ordering
54 class Student:
55 def __eq__(self, other):
56 return ((self.lastname.lower(), self.firstname.lower()) ==
57 (other.lastname.lower(), other.firstname.lower()))
58 def __lt__(self, other):
59 return ((self.lastname.lower(), self.firstname.lower()) <
60 (other.lastname.lower(), other.firstname.lower()))
Georg Brandlae0ee8a2007-08-28 08:29:08 +000061
Raymond Hettinger0d57caa2010-04-04 07:33:46 +000062 .. versionadded:: 2.7
63
Georg Brandlae0ee8a2007-08-28 08:29:08 +000064.. function:: reduce(function, iterable[, initializer])
65
66 This is the same function as :func:`reduce`. It is made available in this module
67 to allow writing code more forward-compatible with Python 3.
68
69 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +000070
71
72.. function:: partial(func[,*args][, **keywords])
73
74 Return a new :class:`partial` object which when called will behave like *func*
75 called with the positional arguments *args* and keyword arguments *keywords*. If
76 more arguments are supplied to the call, they are appended to *args*. If
77 additional keyword arguments are supplied, they extend and override *keywords*.
78 Roughly equivalent to::
79
80 def partial(func, *args, **keywords):
81 def newfunc(*fargs, **fkeywords):
82 newkeywords = keywords.copy()
83 newkeywords.update(fkeywords)
84 return func(*(args + fargs), **newkeywords)
85 newfunc.func = func
86 newfunc.args = args
87 newfunc.keywords = keywords
88 return newfunc
89
90 The :func:`partial` is used for partial function application which "freezes"
91 some portion of a function's arguments and/or keywords resulting in a new object
92 with a simplified signature. For example, :func:`partial` can be used to create
93 a callable that behaves like the :func:`int` function where the *base* argument
Georg Brandle8f1b002008-03-22 22:04:10 +000094 defaults to two:
Georg Brandl8ec7f652007-08-15 14:28:01 +000095
Georg Brandle8f1b002008-03-22 22:04:10 +000096 >>> from functools import partial
Georg Brandl8ec7f652007-08-15 14:28:01 +000097 >>> basetwo = partial(int, base=2)
98 >>> basetwo.__doc__ = 'Convert base 2 string to an int.'
99 >>> basetwo('10010')
100 18
101
102
103.. function:: update_wrapper(wrapper, wrapped[, assigned][, updated])
104
105 Update a *wrapper* function to look like the *wrapped* function. The optional
106 arguments are tuples to specify which attributes of the original function are
107 assigned directly to the matching attributes on the wrapper function and which
108 attributes of the wrapper function are updated with the corresponding attributes
109 from the original function. The default values for these arguments are the
110 module level constants *WRAPPER_ASSIGNMENTS* (which assigns to the wrapper
111 function's *__name__*, *__module__* and *__doc__*, the documentation string) and
112 *WRAPPER_UPDATES* (which updates the wrapper function's *__dict__*, i.e. the
113 instance dictionary).
114
Georg Brandl584265b2007-12-02 14:58:50 +0000115 The main intended use for this function is in :term:`decorator` functions which
116 wrap the decorated function and return the wrapper. If the wrapper function is
117 not updated, the metadata of the returned function will reflect the wrapper
Georg Brandl8ec7f652007-08-15 14:28:01 +0000118 definition rather than the original function definition, which is typically less
119 than helpful.
120
121
122.. function:: wraps(wrapped[, assigned][, updated])
123
124 This is a convenience function for invoking ``partial(update_wrapper,
125 wrapped=wrapped, assigned=assigned, updated=updated)`` as a function decorator
Georg Brandle8f1b002008-03-22 22:04:10 +0000126 when defining a wrapper function. For example:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000127
Georg Brandle8f1b002008-03-22 22:04:10 +0000128 >>> from functools import wraps
Georg Brandl8ec7f652007-08-15 14:28:01 +0000129 >>> def my_decorator(f):
130 ... @wraps(f)
131 ... def wrapper(*args, **kwds):
132 ... print 'Calling decorated function'
133 ... return f(*args, **kwds)
134 ... return wrapper
135 ...
136 >>> @my_decorator
137 ... def example():
138 ... """Docstring"""
139 ... print 'Called example function'
140 ...
141 >>> example()
142 Calling decorated function
143 Called example function
144 >>> example.__name__
145 'example'
146 >>> example.__doc__
147 'Docstring'
148
149 Without the use of this decorator factory, the name of the example function
150 would have been ``'wrapper'``, and the docstring of the original :func:`example`
151 would have been lost.
152
153
154.. _partial-objects:
155
156:class:`partial` Objects
157------------------------
158
159:class:`partial` objects are callable objects created by :func:`partial`. They
160have three read-only attributes:
161
162
163.. attribute:: partial.func
164
165 A callable object or function. Calls to the :class:`partial` object will be
166 forwarded to :attr:`func` with new arguments and keywords.
167
168
169.. attribute:: partial.args
170
171 The leftmost positional arguments that will be prepended to the positional
172 arguments provided to a :class:`partial` object call.
173
174
175.. attribute:: partial.keywords
176
177 The keyword arguments that will be supplied when the :class:`partial` object is
178 called.
179
180:class:`partial` objects are like :class:`function` objects in that they are
181callable, weak referencable, and can have attributes. There are some important
182differences. For instance, the :attr:`__name__` and :attr:`__doc__` attributes
183are not created automatically. Also, :class:`partial` objects defined in
184classes behave like static methods and do not transform into bound methods
185during instance attribute look-up.
186