|
28 | 28 | %====================================================================== |
29 | 29 | \section{PEP 309: Partial Function Application} |
30 | 30 |
|
31 | | -For programs written in a functional style, it can be useful to |
32 | | -construct variants of existing functions that have some of the |
33 | | -parameters filled in. This is called ``partial function application''. |
34 | | -The new \module{functional} module contains a \class{partial} class |
35 | | -that provides partial application. |
36 | | - |
37 | 31 | The \module{functional} module is intended to contain tools for |
38 | 32 | functional-style programming. Currently it only contains |
39 | 33 | \class{partial}, but new functions will probably be added in future |
40 | 34 | versions of Python. |
41 | 35 |
|
42 | | -% XXX write rest of this |
| 36 | +For programs written in a functional style, it can be useful to |
| 37 | +construct variants of existing functions that have some of the |
| 38 | +parameters filled in. Consider a Python function \code{f(a, b, c)}; |
| 39 | +you could create a new function \code{g(b, c)} that was equivalent to |
| 40 | +\code{f(1, b, c)}. This is called ``partial function application'', |
| 41 | +and is provided by the \class{partial} class in the new |
| 42 | +\module{functional} module. |
| 43 | + |
| 44 | +The constructor for \class{partial} takes the arguments |
| 45 | +\code{(\var{function}, \var{arg1}, \var{arg2}, ... |
| 46 | +\var{kwarg1}=\var{value1}, \var{kwarg2}=\var{value2})}. The resulting |
| 47 | +object is callable, so you can just call it to invoke \var{function} |
| 48 | +with the filled-in arguments. |
| 49 | + |
| 50 | +Here's a small but realistic example: |
| 51 | + |
| 52 | +\begin{verbatim} |
| 53 | +import functional |
| 54 | +
|
| 55 | +def log (message, subsystem): |
| 56 | + "Write the contents of 'message' to the specified subsystem." |
| 57 | + print '%s: %s' % (subsystem, message) |
| 58 | + ... |
| 59 | +
|
| 60 | +server_log = functional.partial(log, subsystem='server') |
| 61 | +\end{verbatim} |
| 62 | + |
| 63 | +Here's another example, from a program that uses PyGTk. |
| 64 | + |
43 | 65 | % XXX add example from my GTk programming |
44 | 66 |
|
45 | 67 |
|
|
0 commit comments