Tuesday 3 April 2007

Partial Functions in Python

Recently I have found many uses for the "function that returns a function" python idiom. The basic idea is something like this:

def get_is_small(limit):

    def is_small(i):
        return i < limit
    
    return is_small

The net result is that you have a function reusable in many different situations, without having to keep track of the limit value:

>> is_quite_small = get_is_small(15)
>> is_very_small = get_is_small(3)
>> is_quite_small(6)
True
>> is_very_small(6)
False

This should all become much easier to do once python 2.5 is released, as there is a general purpose function to provide the outer function for you. I believe it will look something like:

import functional
def is_small(limit, i):
    return i < limit

is_quite_small = partial(is_small, 15)
is_very_small  = partial(is_small,3)

Update: Now that 2.5 has been released, I can confirm that it does have a partial function in the standard library - but in the module functools.

No comments: