# 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