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