blob: c092d6d4f4d0cb3fe118716742249c035a538f52 [file] [log] [blame]
Raymond Hettinger9c323f82005-02-28 19:39:44 +00001\section{\module{functional} ---
2 Higher order functions and operations on callable objects.}
3
4\declaremodule{standard}{functional} % standard library, in Python
5
6\moduleauthor{Peter Harris}{scav@blueyonder.co.uk}
7\moduleauthor{Raymond Hettinger}{python@rcn.com}
8\sectionauthor{Peter Harris}{scav@blueyonder.co.uk}
9
10\modulesynopsis{Higher-order functions and operations on callable objects.}
11
12
13The \module{functional} module is for higher-order functions: functions
14that act on or return other functions. In general, any callable object can
15be treated as a function for the purposes of this module.
16
17
18The \module{functional} module defines the following function:
19
20\begin{funcdesc}{partial}{func\optional{,*args}\optional{, **keywords}}
21Return a new \class{partial} object which when called will behave like
22\var{func} called with the positional arguments \var{args} and keyword
23arguments \var{keywords}. If more arguments are supplied to the call, they
24are appended to \var{args}. If additional keyword arguments are supplied,
25they extend and override \var{keywords}. Roughly equivalent to:
26 \begin{verbatim}
27 def partial(func, *args, **keywords):
28 def newfunc(*fargs, **fkeywords):
29 newkeywords = keywords.copy()
30 newkeywords.update(fkeywords)
31 return func(*(args + fargs), **newkeywords)
32 newfunc.func = func
33 newfunc.args = args
34 newfunc.keywords = keywords
35 return newfunc
36 \end{verbatim}
37
38The \function{partial} is used for partial function application which
39``freezes'' some portion of a function's arguments and/or keywords
40resulting in an new object with a simplified signature. For example,
41\function{partial} can be used to create a callable that behaves like
42the \function{int} function where the \var{base} argument defaults to
43two:
44 \begin{verbatim}
45 >>> basetwo = partial(int, base=2)
46 >>> basetwo('10010')
47 18
48 \end{verbatim}
49\end{funcdesc}
50
51
52
53\subsection{\class{partial} Objects \label{partial-objects}}
54
55
56\class{partial} objects are callable objects created by \function{partial()}.
57They have three read-only attributes:
58
59\begin{memberdesc}[callable]{func}{}
60A callable object or function. Calls to the \class{partial} object will
61be forwarded to \member{func} with new arguments and keywords.
62\end{memberdesc}
63
64\begin{memberdesc}[tuple]{args}{}
65The leftmost positional arguments that will be prepended to the
66positional arguments provided to a \class{partial} object call.
67\end{memberdesc}
68
69\begin{memberdesc}[dict]{keywords}{}
70The keyword arguments that will be supplied when the \class{partial} object
71is called.
72\end{memberdesc}