I Might Be Wrong

thunkurry: a Python decorator for partial application

Posted in Python by Leif Ryge on September 30, 2010

Here is a decorator which allows you to curry named and/or positional arguments as many times as you like. The underlying function is finally called when the decorated function is called as a thunk (meaning, without any arguments).

def thunkurry(f_, *t_, **d_):
    """Currying thunk decorator
    Example usage:
    >>> prod = lambda *a: reduce(operator.mul, a)
    >>> sum_ = lambda *a: sum(a)
    >>> thunkurry(prod)(2)(3)(4)() == prod(2,3,4) == 24
    True
    >>> thunkurry(lambda a,b,c:a+b+c)(c=1)(2)(c=3)(4)()
    9
    >>> a = thunkurry(sum_)
    >>> a = a(1)(2)(3); a()
    6
    >>> a = a(1)(2)(3); a()
    12
    """
    def fn(*T_, **D_):
        return f_(*t_, **d_) if not (T_ or D_) \
                else thunkurry(f_, *t_ + T_, **dict(d_.items() + D_.items()))
    fn.__doc__ = f_.__doc__
    return fn

I’ve mostly found this useful as a class decorator.

(Note: the Talk:Currying page on wikipedia has some discussion about the terms currying vs. partial application; I’m using the terms interchangeably here and am not sure if that is wrong.)

Tagged with: , , , ,

2 Responses

Subscribe to comments with RSS.

  1. spain basketball league nba said, on December 22, 2012 at 9:49 am

    You can definitely see your enthusiasm in the work you write.

    The world hopes for

    even more passionate writers like you who aren’t afraid to say how they believe. Always go after

    your heart.

  2. Franklin said, on December 29, 2012 at 10:31 pm

    Do you have a spam issue on this site; I also am a blogger, and I was curious about your situation;
    we have created some nice procedures and we

    are looking to trade solutions with other folks,
    please shoot me an email if interested.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: