Skip to content

Instantly share code, notes, and snippets.

@xhjkl
Last active February 20, 2016 00:41
Show Gist options
  • Save xhjkl/aff5af7db85d810c46a5 to your computer and use it in GitHub Desktop.
Save xhjkl/aff5af7db85d810c46a5 to your computer and use it in GitHub Desktop.
Convenient Currying for Python Decorators
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