blob: 6dc9f0abed8568b99d1bf11040fc348af51d532b [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +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
Georg Brandlae0ee8a2007-08-28 08:29:08 +000018The :mod:`functools` module defines the following functions:
19
Raymond Hettinger20ae90d2010-04-04 01:24:59 +000020.. function:: total_ordering(cls)
21
22 Given a class defining one or more rich comparison ordering methods, this
23 class decorator supplies the rest. This simplies the effort involved
24 in specifying all of the possible rich comparison operations:
25
26 The class must define one of :meth:`__lt__`, :meth:`__le__`,
27 :meth:`__gt__`, or :meth:`__ge__`.
28 In addition, the class should supply an :meth:`__eq__` method.
29
30 For example::
31
32 @total_ordering
33 class Student:
34 def __eq__(self, other):
35 return ((self.lastname.lower(), self.firstname.lower()) ==
36 (other.lastname.lower(), other.firstname.lower()))
37 def __lt__(self, other):
38 return ((self.lastname.lower(), self.firstname.lower()) <
39 (other.lastname.lower(), other.firstname.lower()))
Georg Brandlae0ee8a2007-08-28 08:29:08 +000040
Raymond Hettinger0d57caa2010-04-04 07:33:46 +000041 .. versionadded:: 2.7
42
Georg Brandlae0ee8a2007-08-28 08:29:08 +000043.. function:: reduce(function, iterable[, initializer])
44
45 This is the same function as :func:`reduce`. It is made available in this module
46 to allow writing code more forward-compatible with Python 3.
47
48 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +000049
50
51.. function:: partial(func[,*args][, **keywords])
52
53 Return a new :class:`partial` object which when called will behave like *func*
54 called with the positional arguments *args* and keyword arguments *keywords*. If
55 more arguments are supplied to the call, they are appended to *args*. If
56 additional keyword arguments are supplied, they extend and override *keywords*.
57 Roughly equivalent to::
58
59 def partial(func, *args, **keywords):
60 def newfunc(*fargs, **fkeywords):
61 newkeywords = keywords.copy()
62 newkeywords.update(fkeywords)
63 return func(*(args + fargs), **newkeywords)
64 newfunc.func = func
65 newfunc.args = args
66 newfunc.keywords = keywords
67 return newfunc
68
69 The :func:`partial` is used for partial function application which "freezes"
70 some portion of a function's arguments and/or keywords resulting in a new object
71 with a simplified signature. For example, :func:`partial` can be used to create
72 a callable that behaves like the :func:`int` function where the *base* argument
Georg Brandle8f1b002008-03-22 22:04:10 +000073 defaults to two:
Georg Brandl8ec7f652007-08-15 14:28:01 +000074
Georg Brandle8f1b002008-03-22 22:04:10 +000075 >>> from functools import partial
Georg Brandl8ec7f652007-08-15 14:28:01 +000076 >>> basetwo = partial(int, base=2)
77 >>> basetwo.__doc__ = 'Convert base 2 string to an int.'
78 >>> basetwo('10010')
79 18
80
81
82.. function:: update_wrapper(wrapper, wrapped[, assigned][, updated])
83
84 Update a *wrapper* function to look like the *wrapped* function. The optional
85 arguments are tuples to specify which attributes of the original function are
86 assigned directly to the matching attributes on the wrapper function and which
87 attributes of the wrapper function are updated with the corresponding attributes
88 from the original function. The default values for these arguments are the
89 module level constants *WRAPPER_ASSIGNMENTS* (which assigns to the wrapper
90 function's *__name__*, *__module__* and *__doc__*, the documentation string) and
91 *WRAPPER_UPDATES* (which updates the wrapper function's *__dict__*, i.e. the
92 instance dictionary).
93
Georg Brandl584265b2007-12-02 14:58:50 +000094 The main intended use for this function is in :term:`decorator` functions which
95 wrap the decorated function and return the wrapper. If the wrapper function is
96 not updated, the metadata of the returned function will reflect the wrapper
Georg Brandl8ec7f652007-08-15 14:28:01 +000097 definition rather than the original function definition, which is typically less
98 than helpful.
99
100
101.. function:: wraps(wrapped[, assigned][, updated])
102
103 This is a convenience function for invoking ``partial(update_wrapper,
104 wrapped=wrapped, assigned=assigned, updated=updated)`` as a function decorator
Georg Brandle8f1b002008-03-22 22:04:10 +0000105 when defining a wrapper function. For example:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000106
Georg Brandle8f1b002008-03-22 22:04:10 +0000107 >>> from functools import wraps
Georg Brandl8ec7f652007-08-15 14:28:01 +0000108 >>> def my_decorator(f):
109 ... @wraps(f)
110 ... def wrapper(*args, **kwds):
111 ... print 'Calling decorated function'
112 ... return f(*args, **kwds)
113 ... return wrapper
114 ...
115 >>> @my_decorator
116 ... def example():
117 ... """Docstring"""
118 ... print 'Called example function'
119 ...
120 >>> example()
121 Calling decorated function
122 Called example function
123 >>> example.__name__
124 'example'
125 >>> example.__doc__
126 'Docstring'
127
128 Without the use of this decorator factory, the name of the example function
129 would have been ``'wrapper'``, and the docstring of the original :func:`example`
130 would have been lost.
131
132
133.. _partial-objects:
134
135:class:`partial` Objects
136------------------------
137
138:class:`partial` objects are callable objects created by :func:`partial`. They
139have three read-only attributes:
140
141
142.. attribute:: partial.func
143
144 A callable object or function. Calls to the :class:`partial` object will be
145 forwarded to :attr:`func` with new arguments and keywords.
146
147
148.. attribute:: partial.args
149
150 The leftmost positional arguments that will be prepended to the positional
151 arguments provided to a :class:`partial` object call.
152
153
154.. attribute:: partial.keywords
155
156 The keyword arguments that will be supplied when the :class:`partial` object is
157 called.
158
159:class:`partial` objects are like :class:`function` objects in that they are
160callable, weak referencable, and can have attributes. There are some important
161differences. For instance, the :attr:`__name__` and :attr:`__doc__` attributes
162are not created automatically. Also, :class:`partial` objects defined in
163classes behave like static methods and do not transform into bound methods
164during instance attribute look-up.
165