A neat currying implementation in Python 

I wanted to share what I think is a neat implementation of currying in Python.

Getting the arity of a function

First we need to be able to get the arity of a function. This is how we do it:

import inspect

def arity(f):
  args, varargs, varkw, defaults = inspect.getargspec(f)
  return len(args)
  # use this in Python 3.3+ 
  # return len(inspect.signature(f).parameters)
  

 

Now, behold!

def curry(f):
  def g(*args):
    if len(args) < arity(f):
      return lambda *moreargs: g(*(args+moreargs))
    return f(*args)
  return g

Let’s test it

@curry
def f(a, b, c, d, e):
  print("finally calling 'f', with args:", a, b, c, d) 
  result = a + b + c + d + e
  print("result was:", result) 
  return result

f1 = f(2)         # f1 is a curried function of arity 4
f2 = f1(1, 3)     # f2 is a curried function of arity 2
f2(4, 5)          # returns 15
f2(4)(5)          # returns 15 too  

Author: matiasmorant

Mechanical engineer fascinated by math, programming & science

One thought on “A neat currying implementation in Python ”

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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s