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).
|