blob: 086b0b5d1b462ba1e87e6d7b1cd4d6d50bfaea8e [file] [log] [blame]
Georg Brandle9401a02012-01-25 22:36:25 +01001:mod:`functools` --- Higher-order functions and operations on callable objects
Georg Brandl8ec7f652007-08-15 14:28:01 +00002==============================================================================
3
4.. module:: functools
Georg Brandle9401a02012-01-25 22:36:25 +01005 :synopsis: Higher-order functions and operations on callable objects.
Georg Brandl8ec7f652007-08-15 14:28:01 +00006.. 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
Georg Brandl8ec7f652007-08-15 14:28:01 +000011.. versionadded:: 2.5
12
Éric Araujo29a0b572011-08-19 02:14:03 +020013**Source code:** :source:`Lib/functools.py`
14
15--------------
16
Georg Brandl8ec7f652007-08-15 14:28:01 +000017The :mod:`functools` module is for higher-order functions: functions that act on
18or return other functions. In general, any callable object can be treated as a
19function for the purposes of this module.
20
Georg Brandlae0ee8a2007-08-28 08:29:08 +000021The :mod:`functools` module defines the following functions:
22
Raymond Hettingerbb006cf2010-04-04 21:45:01 +000023.. function:: cmp_to_key(func)
Raymond Hettingera551f312010-04-04 18:34:45 +000024
Raymond Hettingerccae4792014-11-09 17:10:17 -080025 Transform an old-style comparison function to a :term:`key function`. Used
26 with tools that accept key functions (such as :func:`sorted`, :func:`min`,
Benjamin Petersond74ca122010-08-09 02:17:24 +000027 :func:`max`, :func:`heapq.nlargest`, :func:`heapq.nsmallest`,
28 :func:`itertools.groupby`). This function is primarily used as a transition
Ezio Melotti055d70d2012-01-16 08:21:24 +020029 tool for programs being converted to Python 3 where comparison functions are
30 no longer supported.
Raymond Hettingera551f312010-04-04 18:34:45 +000031
Georg Brandle9401a02012-01-25 22:36:25 +010032 A comparison function is any callable that accept two arguments, compares them,
Benjamin Petersond74ca122010-08-09 02:17:24 +000033 and returns a negative number for less-than, zero for equality, or a positive
34 number for greater-than. A key function is a callable that accepts one
Raymond Hettingerccae4792014-11-09 17:10:17 -080035 argument and returns another value to be used as the sort key.
Raymond Hettingera551f312010-04-04 18:34:45 +000036
Benjamin Petersond74ca122010-08-09 02:17:24 +000037 Example::
Raymond Hettingera551f312010-04-04 18:34:45 +000038
Benjamin Petersond74ca122010-08-09 02:17:24 +000039 sorted(iterable, key=cmp_to_key(locale.strcoll)) # locale-aware sort order
Raymond Hettingera551f312010-04-04 18:34:45 +000040
Raymond Hettingerccae4792014-11-09 17:10:17 -080041 For sorting examples and a brief sorting tutorial, see `Sorting HowTo
42 <https://wiki.python.org/moin/HowTo/Sorting/>`_\.
43
44
Raymond Hettingera551f312010-04-04 18:34:45 +000045 .. versionadded:: 2.7
46
Raymond Hettinger20ae90d2010-04-04 01:24:59 +000047.. function:: total_ordering(cls)
48
49 Given a class defining one or more rich comparison ordering methods, this
Andrew M. Kuchling884d0a32010-04-11 12:48:08 +000050 class decorator supplies the rest. This simplifies the effort involved
Raymond Hettinger20ae90d2010-04-04 01:24:59 +000051 in specifying all of the possible rich comparison operations:
52
53 The class must define one of :meth:`__lt__`, :meth:`__le__`,
54 :meth:`__gt__`, or :meth:`__ge__`.
55 In addition, the class should supply an :meth:`__eq__` method.
56
57 For example::
58
59 @total_ordering
60 class Student:
61 def __eq__(self, other):
62 return ((self.lastname.lower(), self.firstname.lower()) ==
63 (other.lastname.lower(), other.firstname.lower()))
64 def __lt__(self, other):
65 return ((self.lastname.lower(), self.firstname.lower()) <
66 (other.lastname.lower(), other.firstname.lower()))
Georg Brandlae0ee8a2007-08-28 08:29:08 +000067
Raymond Hettinger0d57caa2010-04-04 07:33:46 +000068 .. versionadded:: 2.7
69
Georg Brandlae0ee8a2007-08-28 08:29:08 +000070.. function:: reduce(function, iterable[, initializer])
71
72 This is the same function as :func:`reduce`. It is made available in this module
73 to allow writing code more forward-compatible with Python 3.
74
75 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +000076
77
78.. function:: partial(func[,*args][, **keywords])
79
80 Return a new :class:`partial` object which when called will behave like *func*
81 called with the positional arguments *args* and keyword arguments *keywords*. If
82 more arguments are supplied to the call, they are appended to *args*. If
83 additional keyword arguments are supplied, they extend and override *keywords*.
84 Roughly equivalent to::
85
86 def partial(func, *args, **keywords):
87 def newfunc(*fargs, **fkeywords):
88 newkeywords = keywords.copy()
89 newkeywords.update(fkeywords)
90 return func(*(args + fargs), **newkeywords)
91 newfunc.func = func
92 newfunc.args = args
93 newfunc.keywords = keywords
94 return newfunc
95
96 The :func:`partial` is used for partial function application which "freezes"
97 some portion of a function's arguments and/or keywords resulting in a new object
98 with a simplified signature. For example, :func:`partial` can be used to create
99 a callable that behaves like the :func:`int` function where the *base* argument
Georg Brandle8f1b002008-03-22 22:04:10 +0000100 defaults to two:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000101
Georg Brandle8f1b002008-03-22 22:04:10 +0000102 >>> from functools import partial
Georg Brandl8ec7f652007-08-15 14:28:01 +0000103 >>> basetwo = partial(int, base=2)
104 >>> basetwo.__doc__ = 'Convert base 2 string to an int.'
105 >>> basetwo('10010')
106 18
107
108
109.. function:: update_wrapper(wrapper, wrapped[, assigned][, updated])
110
111 Update a *wrapper* function to look like the *wrapped* function. The optional
112 arguments are tuples to specify which attributes of the original function are
113 assigned directly to the matching attributes on the wrapper function and which
114 attributes of the wrapper function are updated with the corresponding attributes
115 from the original function. The default values for these arguments are the
116 module level constants *WRAPPER_ASSIGNMENTS* (which assigns to the wrapper
117 function's *__name__*, *__module__* and *__doc__*, the documentation string) and
118 *WRAPPER_UPDATES* (which updates the wrapper function's *__dict__*, i.e. the
119 instance dictionary).
120
Georg Brandl584265b2007-12-02 14:58:50 +0000121 The main intended use for this function is in :term:`decorator` functions which
122 wrap the decorated function and return the wrapper. If the wrapper function is
123 not updated, the metadata of the returned function will reflect the wrapper
Georg Brandl8ec7f652007-08-15 14:28:01 +0000124 definition rather than the original function definition, which is typically less
125 than helpful.
126
127
128.. function:: wraps(wrapped[, assigned][, updated])
129
Ezio Melotti249fcf62014-08-05 08:14:28 +0300130 This is a convenience function for invoking :func:`update_wrapper` as a
131 function decorator when defining a wrapper function. It is equivalent to
132 ``partial(update_wrapper, wrapped=wrapped, assigned=assigned, updated=updated)``.
133 For example::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000134
Georg Brandle8f1b002008-03-22 22:04:10 +0000135 >>> from functools import wraps
Georg Brandl8ec7f652007-08-15 14:28:01 +0000136 >>> def my_decorator(f):
137 ... @wraps(f)
138 ... def wrapper(*args, **kwds):
139 ... print 'Calling decorated function'
140 ... return f(*args, **kwds)
141 ... return wrapper
142 ...
143 >>> @my_decorator
144 ... def example():
145 ... """Docstring"""
146 ... print 'Called example function'
147 ...
148 >>> example()
149 Calling decorated function
150 Called example function
151 >>> example.__name__
152 'example'
153 >>> example.__doc__
154 'Docstring'
155
156 Without the use of this decorator factory, the name of the example function
157 would have been ``'wrapper'``, and the docstring of the original :func:`example`
158 would have been lost.
159
160
161.. _partial-objects:
162
163:class:`partial` Objects
164------------------------
165
166:class:`partial` objects are callable objects created by :func:`partial`. They
167have three read-only attributes:
168
169
170.. attribute:: partial.func
171
172 A callable object or function. Calls to the :class:`partial` object will be
173 forwarded to :attr:`func` with new arguments and keywords.
174
175
176.. attribute:: partial.args
177
178 The leftmost positional arguments that will be prepended to the positional
179 arguments provided to a :class:`partial` object call.
180
181
182.. attribute:: partial.keywords
183
184 The keyword arguments that will be supplied when the :class:`partial` object is
185 called.
186
187:class:`partial` objects are like :class:`function` objects in that they are
188callable, weak referencable, and can have attributes. There are some important
189differences. For instance, the :attr:`__name__` and :attr:`__doc__` attributes
190are not created automatically. Also, :class:`partial` objects defined in
191classes behave like static methods and do not transform into bound methods
192during instance attribute look-up.
193