Function question

Andrew Dalke dalke at dalkescientific.com
Mon Apr 8 01:01:54 EDT 2002


John wrote:
>Let's say there is a function with two arguments.
>def add(a,b): return a+b
>
>What I want to do is:
>I want to get 'a' dynamically..
>But once a value is decided, I want a separate function (say, new_add) that
>does
>new_add(b) (equals to) add(a,b)

What you want is often known as "currying".  From the ActiveState Cookbook
at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52549
are several implementations, the most recent being Alex Martelli quote
of Nick Perkins for a 2.2-specific version

def curry(*args, **create_time_kwds):
    func = args[0]
    create_time_args = args[1:]
    def curried_function(*call_time_args, **call_time_kwds):
        args = create_time_args + call_time_args
        kwds = create_time_kwds.copy()
        kwds.update(call_time_kwds)
        return func(*args, **kwds)
    return curried_function



Used, for example, as (not tested):
>>> import operator
>>> add_two = curry(operator.add, 2)
>>> add_two(4)
6
>>>

See also google groups for commentary on this topic.

                    Andrew
                    dalke at dalkescientific.com







More information about the Python-list mailing list