Last active
February 20, 2016 00:41
-
-
Save xhjkl/aff5af7db85d810c46a5 to your computer and use it in GitHub Desktop.
Convenient Currying for Python Decorators
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
from functools import partial, wraps | |
def curry(f): | |
""" Represent given n-ary function | |
as a sequence of unary functions. | |
Useful for function decorators with arguments. | |
Each unary function provides a closure around | |
one argument. If all arguments have been passed, | |
the initial function is called as usual. | |
Passing arguments through separate invocations | |
has the same effect as of enumerating them with comma | |
in a single invocation. | |
If decorated function is able to be called | |
with different number of arguments, the first invocation | |
with least enough total number of arguments | |
shall do the call. | |
""" | |
def curried(*args, **keywords): | |
try: | |
return f.__call__(*args, **keywords) | |
except TypeError: | |
return curry(partial(f, *args, **keywords)) | |
return wraps(f)(curried) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment