Functional Python Programming

(Wang) #1
Chapter 10

Applying partial arguments with partial()


The partial() function leads to something called partial application. A partially
applied function is a new function built from an old function and a subset of the
required arguments. It is closely related to the concept of currying. Much of the
theoretical background is not relevant here, since currying doesn't apply to the
way Python functions are implemented. The concept, however, can lead us to
some handy simplifications.


We can look at trivial examples as follows:





exp2= partial(pow, 2)








exp2(12)





4096





exp2(17)-1





131071


We've created a function, exp2(y), which is the pow(2,y) function. The partial()
function bounds the first positional parameter to the pow() function. When we
evaluate the newly created exp2() function, we get values computed from the
argument bound by the partial() function, plus the additional argument provided
to the exp2() function.


The bindings of positional parameters are handed in a strict left-to-right order.
For functions that accept keyword parameters, these can also be provided when
building the partially applied function.


We can also create this kind of partially applied function with a lambda form
as follows:


exp2= lambda y: pow(2,y)


Neither is clearly superior. Measuring performance shows that the partial()
function is a hair faster than a lambda form in the following manner:



  • partial 0.37

  • lambda 0.42


This is 0.05 seconds over 1,000,000 iterations: not a remarkable savings.


Since lambda forms have all of the capabilities of the partial() function, it seems
that we can safely set this function aside as not being profoundly useful. We'll return
to it in Chapter 14, The PyMonad Library, and look at how we can accomplish this with
currying also.

Free download pdf