Previous Page
Next Page

8.6. The functional Module

The functional module (introduced in Python 2.5) is intended to eventually supply several interesting functions and types to support functional programming in Python. At the time of writing, there is debate about renaming the module to functools, or perhaps introducing a separate functools module, to hold higher-order functions not strictly connected to the idioms of functional programming (in particular, built-in decorators). However, again at the time of writing, only one function has been definitively accepted for inclusion in the functional module.

partial

partial(func,*a,**k)

func is any callable. partial returns another callable p that is just like func, but with some positional and/or named parameters already bound to the values given in a and k. In other words, p is a partial application of func, often also known (with debatable correctness, but colorfully) as a currying of func to the given arguments (named in honor of mathematician Haskell Curry). For example, say that we have a list of numbers L and want to clip the negative ones to 0. In Python 2.5, one way to do it is:

L = map(functional.partial(max, 0), L)

as an alternative to the lambda-using snippet:

L = map(lambda x: max(0, x), L)

and the list-comprehension:

L = [max(0, x) for x in L]

functional.partial really comes into its own in situations that require callbacks, such as event-driven programming for GUIs (covered in Chapter 17) and networking applications (covered in "Event-Driven Socket Programs" on page 533).



Previous Page
Next Page