Partial Function Application -- Advantages over normal function?

Steven D'Aprano steve+comp.lang.python at pearwood.info
Mon Jul 18 17:08:22 CEST 2011


Kurian Thayil wrote:

> Hi,
> 
> I am a newbie in python and would like to learn GUI programming. I would
> like to know what exactly is Partial Function Applicaton
> (functool.partial())? Or how is it advantageous compared to normal
> functions? Or is there any advantange? Thanks in advance.

It is mostly for functional programming style.

But one lucky side-effect of the implementation is that partial functions
*may* sometimes be faster than the alternative written in pure Python,
provided the original function is written in C:


from functools import partial
from operator import add

def add_one(x):
    return add(1, x)  # Like 1+x

add_two = partial(add, 2)

from timeit import Timer
setup = "from __main__ import add_one, add_two"
t1 = Timer("add_one(42)", setup)
t2 = Timer("add_two(42)", setup)



And in action:

>>> t1.timeit()
0.7412619590759277
>>> t2.timeit()
0.3557558059692383

So in this example, the partial function is about twice as fast as the one
written in Python.

This does not necessarily apply for all functions, but it sometimes is
useful.


-- 
Steven




More information about the Python-list mailing list