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