blob: 8f9528a1573a85532c57f199ff45e6db81e86845 [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
41.. function:: reduce(function, iterable[, initializer])
42
43 This is the same function as :func:`reduce`. It is made available in this module
44 to allow writing code more forward-compatible with Python 3.
45
46 .. versionadded:: 2.6
Georg Brandl8ec7f652007-08-15 14:28:01 +000047
48
49.. function:: partial(func[,*args][, **keywords])
50
51 Return a new :class:`partial` object which when called will behave like *func*
52 called with the positional arguments *args* and keyword arguments *keywords*. If
53 more arguments are supplied to the call, they are appended to *args*. If
54 additional keyword arguments are supplied, they extend and override *keywords*.
55 Roughly equivalent to::
56
57 def partial(func, *args, **keywords):
58 def newfunc(*fargs, **fkeywords):
59 newkeywords = keywords.copy()
60 newkeywords.update(fkeywords)
61 return func(*(args + fargs), **newkeywords)
62 newfunc.func = func
63 newfunc.args = args
64 newfunc.keywords = keywords
65 return newfunc
66
67 The :func:`partial` is used for partial function application which "freezes"
68 some portion of a function's arguments and/or keywords resulting in a new object
69 with a simplified signature. For example, :func:`partial` can be used to create
70 a callable that behaves like the :func:`int` function where the *base* argument
Georg Brandle8f1b002008-03-22 22:04:10 +000071 defaults to two:
Georg Brandl8ec7f652007-08-15 14:28:01 +000072
Georg Brandle8f1b002008-03-22 22:04:10 +000073 >>> from functools import partial
Georg Brandl8ec7f652007-08-15 14:28:01 +000074 >>> basetwo = partial(int, base=2)
75 >>> basetwo.__doc__ = 'Convert base 2 string to an int.'
76 >>> basetwo('10010')
77 18
78
79
80.. function:: update_wrapper(wrapper, wrapped[, assigned][, updated])
81
82 Update a *wrapper* function to look like the *wrapped* function. The optional
83 arguments are tuples to specify which attributes of the original function are
84 assigned directly to the matching attributes on the wrapper function and which
85 attributes of the wrapper function are updated with the corresponding attributes
86 from the original function. The default values for these arguments are the
87 module level constants *WRAPPER_ASSIGNMENTS* (which assigns to the wrapper
88 function's *__name__*, *__module__* and *__doc__*, the documentation string) and
89 *WRAPPER_UPDATES* (which updates the wrapper function's *__dict__*, i.e. the
90 instance dictionary).
91
Georg Brandl584265b2007-12-02 14:58:50 +000092 The main intended use for this function is in :term:`decorator` functions which
93 wrap the decorated function and return the wrapper. If the wrapper function is
94 not updated, the metadata of the returned function will reflect the wrapper
Georg Brandl8ec7f652007-08-15 14:28:01 +000095 definition rather than the original function definition, which is typically less
96 than helpful.
97
98
99.. function:: wraps(wrapped[, assigned][, updated])
100
101 This is a convenience function for invoking ``partial(update_wrapper,
102 wrapped=wrapped, assigned=assigned, updated=updated)`` as a function decorator
Georg Brandle8f1b002008-03-22 22:04:10 +0000103 when defining a wrapper function. For example:
Georg Brandl8ec7f652007-08-15 14:28:01 +0000104
Georg Brandle8f1b002008-03-22 22:04:10 +0000105 >>> from functools import wraps
Georg Brandl8ec7f652007-08-15 14:28:01 +0000106 >>> def my_decorator(f):
107 ... @wraps(f)
108 ... def wrapper(*args, **kwds):
109 ... print 'Calling decorated function'
110 ... return f(*args, **kwds)
111 ... return wrapper
112 ...
113 >>> @my_decorator
114 ... def example():
115 ... """Docstring"""
116 ... print 'Called example function'
117 ...
118 >>> example()
119 Calling decorated function
120 Called example function
121 >>> example.__name__
122 'example'
123 >>> example.__doc__
124 'Docstring'
125
126 Without the use of this decorator factory, the name of the example function
127 would have been ``'wrapper'``, and the docstring of the original :func:`example`
128 would have been lost.
129
130
131.. _partial-objects:
132
133:class:`partial` Objects
134------------------------
135
136:class:`partial` objects are callable objects created by :func:`partial`. They
137have three read-only attributes:
138
139
140.. attribute:: partial.func
141
142 A callable object or function. Calls to the :class:`partial` object will be
143 forwarded to :attr:`func` with new arguments and keywords.
144
145
146.. attribute:: partial.args
147
148 The leftmost positional arguments that will be prepended to the positional
149 arguments provided to a :class:`partial` object call.
150
151
152.. attribute:: partial.keywords
153
154 The keyword arguments that will be supplied when the :class:`partial` object is
155 called.
156
157:class:`partial` objects are like :class:`function` objects in that they are
158callable, weak referencable, and can have attributes. There are some important
159differences. For instance, the :attr:`__name__` and :attr:`__doc__` attributes
160are not created automatically. Also, :class:`partial` objects defined in
161classes behave like static methods and do not transform into bound methods
162during instance attribute look-up.
163