Created
September 4, 2011 19:48
-
-
Save Djexus/1193399 to your computer and use it in GitHub Desktop.
Curry decorator for Python functions and methods
This file contains hidden or 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
import inspect | |
def curry(func, *args, **kwargs): | |
''' | |
This decorator make your functions and methods curried. | |
Usage: | |
>>> adder = curry(lambda (x, y): (x + y)) | |
>>> adder(2, 3) | |
5 | |
>>> adder(2)(3) | |
5 | |
>>> adder(y = 3)(2) | |
5 | |
''' | |
assert inspect.getargspec(func)[1] == None, 'Currying can\'t work with *args syntax' | |
assert inspect.getargspec(func)[2] == None, 'Currying can\'t work with *kwargs syntax' | |
assert inspect.getargspec(func)[3] == None, 'Currying can\'t work with default arguments' | |
if (len(args) + len(kwargs)) >= func.__code__.co_argcount: | |
return func(*args, **kwargs) | |
return (lambda *x, **y: curry(func, *(args + x), **dict(kwargs, **y))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment