blob: 01e1fcb5627dd3358ba90e556490cc7310599b3d [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
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
Thomas Woutersed03b412007-08-28 21:37:11 +000018The :mod:`functools` module defines the following functions:
19
20
21.. function:: reduce(function, iterable[, initializer])
22
23 This is the same function as :func:`reduce`. It is made available in this module
24 to allow writing code more forward-compatible with Python 3.
25
26 .. versionadded:: 2.6
Georg Brandl116aa622007-08-15 14:28:22 +000027
28
29.. function:: partial(func[,*args][, **keywords])
30
31 Return a new :class:`partial` object which when called will behave like *func*
32 called with the positional arguments *args* and keyword arguments *keywords*. If
33 more arguments are supplied to the call, they are appended to *args*. If
34 additional keyword arguments are supplied, they extend and override *keywords*.
35 Roughly equivalent to::
36
37 def partial(func, *args, **keywords):
38 def newfunc(*fargs, **fkeywords):
39 newkeywords = keywords.copy()
40 newkeywords.update(fkeywords)
41 return func(*(args + fargs), **newkeywords)
42 newfunc.func = func
43 newfunc.args = args
44 newfunc.keywords = keywords
45 return newfunc
46
47 The :func:`partial` is used for partial function application which "freezes"
48 some portion of a function's arguments and/or keywords resulting in a new object
49 with a simplified signature. For example, :func:`partial` can be used to create
50 a callable that behaves like the :func:`int` function where the *base* argument
51 defaults to two::
52
53 >>> basetwo = partial(int, base=2)
54 >>> basetwo.__doc__ = 'Convert base 2 string to an int.'
55 >>> basetwo('10010')
56 18
57
58
59.. function:: reduce(function, sequence[, initializer])
60
61 Apply *function* of two arguments cumulatively to the items of *sequence*, from
62 left to right, so as to reduce the sequence to a single value. For example,
63 ``reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])`` calculates ``((((1+2)+3)+4)+5)``.
64 The left argument, *x*, is the accumulated value and the right argument, *y*, is
65 the update value from the *sequence*. If the optional *initializer* is present,
66 it is placed before the items of the sequence in the calculation, and serves as
67 a default when the sequence is empty. If *initializer* is not given and
68 *sequence* contains only one item, the first item is returned.
69
70
71.. function:: update_wrapper(wrapper, wrapped[, assigned][, updated])
72
73 Update a *wrapper* function to look like the *wrapped* function. The optional
74 arguments are tuples to specify which attributes of the original function are
75 assigned directly to the matching attributes on the wrapper function and which
76 attributes of the wrapper function are updated with the corresponding attributes
77 from the original function. The default values for these arguments are the
78 module level constants *WRAPPER_ASSIGNMENTS* (which assigns to the wrapper
79 function's *__name__*, *__module__* and *__doc__*, the documentation string) and
80 *WRAPPER_UPDATES* (which updates the wrapper function's *__dict__*, i.e. the
81 instance dictionary).
82
83 The main intended use for this function is in decorator functions which wrap the
84 decorated function and return the wrapper. If the wrapper function is not
85 updated, the metadata of the returned function will reflect the wrapper
86 definition rather than the original function definition, which is typically less
87 than helpful.
88
89
90.. function:: wraps(wrapped[, assigned][, updated])
91
92 This is a convenience function for invoking ``partial(update_wrapper,
93 wrapped=wrapped, assigned=assigned, updated=updated)`` as a function decorator
94 when defining a wrapper function. For example::
95
96 >>> def my_decorator(f):
97 ... @wraps(f)
98 ... def wrapper(*args, **kwds):
99 ... print 'Calling decorated function'
100 ... return f(*args, **kwds)
101 ... return wrapper
102 ...
103 >>> @my_decorator
104 ... def example():
105 ... """Docstring"""
106 ... print 'Called example function'
107 ...
108 >>> example()
109 Calling decorated function
110 Called example function
111 >>> example.__name__
112 'example'
113 >>> example.__doc__
114 'Docstring'
115
116 Without the use of this decorator factory, the name of the example function
117 would have been ``'wrapper'``, and the docstring of the original :func:`example`
118 would have been lost.
119
120
121.. _partial-objects:
122
123:class:`partial` Objects
124------------------------
125
126:class:`partial` objects are callable objects created by :func:`partial`. They
127have three read-only attributes:
128
129
130.. attribute:: partial.func
131
132 A callable object or function. Calls to the :class:`partial` object will be
133 forwarded to :attr:`func` with new arguments and keywords.
134
135
136.. attribute:: partial.args
137
138 The leftmost positional arguments that will be prepended to the positional
139 arguments provided to a :class:`partial` object call.
140
141
142.. attribute:: partial.keywords
143
144 The keyword arguments that will be supplied when the :class:`partial` object is
145 called.
146
147:class:`partial` objects are like :class:`function` objects in that they are
148callable, weak referencable, and can have attributes. There are some important
149differences. For instance, the :attr:`__name__` and :attr:`__doc__` attributes
150are not created automatically. Also, :class:`partial` objects defined in
151classes behave like static methods and do not transform into bound methods
152during instance attribute look-up.
153