Skip to content

Instantly share code, notes, and snippets.

@hcarvalhoalves
Last active August 29, 2015 14:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hcarvalhoalves/32af119918aa0837e020 to your computer and use it in GitHub Desktop.
Save hcarvalhoalves/32af119918aa0837e020 to your computer and use it in GitHub Desktop.
Currying decorator.
from functools import partial, wraps
import doctest
def curry(f):
"""
Allow partial evaluation of function (currying).
Returns a `functools.partial` until all arguments are specified:
>>> f = curry(lambda a,b: a + b)
>>> assert type(f(1)) == partial
>>> assert f(1)(1) == 2
>>> assert f(1, 1) == 2
Keeps default behaviour for keywords arguments, evaluating as
soon as possible:
>>> @curry
... def g(a, b, c=0):
... "My docstring."
... return a + b + c
...
>>> assert type(g(1)) == partial
>>> assert g(1)(1) == 2
>>> assert g(1)(1, c=1) == 3
>>> assert g.__doc__ == "My docstring."
"""
@wraps(f)
def curried_function(*args, **kwargs):
if len(args) < f.func_code.co_argcount:
return partial(f, *args, **kwargs)
return f(*args)
return curried_function
if __name__ == "__main__":
doctest.testmod()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment