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