1 PEP 309: Partial Function Application

The functional module is intended to contain tools for functional-style programming. Currently it only contains partial, but new functions will probably be added in future versions of Python.

For programs written in a functional style, it can be useful to construct variants of existing functions that have some of the parameters filled in. Consider a Python function f(a, b, c); you could create a new function g(b, c) that was equivalent to f(1, b, c). This is called ``partial function application'', and is provided by the partial class in the new functional module.

The constructor for partial takes the arguments (function, arg1, arg2, ... kwarg1=value1, kwarg2=value2). The resulting object is callable, so you can just call it to invoke function with the filled-in arguments.

Here's a small but realistic example:

import functional

def log (message, subsystem):
    "Write the contents of 'message' to the specified subsystem."
    print '%s: %s' % (subsystem, message)
    ...

server_log = functional.partial(log, subsystem='server')

Here's another example, from a program that uses PyGTk. Here a context-sensitive pop-up menu is being constructed dynamically. The callback provided for the menu option is a partially applied version of the open_item() method, where the first argument has been provided.

...
class Application:
    def open_item(self, path):
       ...
    def init (self):
        open_func = functional.partial(self.open_item, item_path)
        popup_menu.append( ("Open", open_func, 1) )

See Also:

PEP 309, Partial Function Application
PEP proposed and written by Peter Harris; implemented by Hye-Shik Chang, with adaptations by Raymond Hettinger.

See About this document... for information on suggesting changes.