Last active
August 29, 2015 14:16
-
-
Save hcarvalhoalves/32af119918aa0837e020 to your computer and use it in GitHub Desktop.
Currying decorator.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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