Skip to content

Instantly share code, notes, and snippets.

@funketh
Last active November 10, 2019 21:36
Show Gist options
  • Save funketh/465d136480d79ab6b935400635362bc3 to your computer and use it in GitHub Desktop.
Save funketh/465d136480d79ab6b935400635362bc3 to your computer and use it in GitHub Desktop.
currying decorator in python
from functools import wraps, partial
from inspect import signature
def curryable(func):
@wraps(func)
def curryable_func(*args, **kwargs):
try:
signature(func).bind(*args, **kwargs)
except TypeError:
return partial(curryable(func), *args, **kwargs)
else:
return func(*args, **kwargs)
return curryable_func
# Example 1: Partially supply arguments
@curryable
def add(a, b, c, d=5):
return a + b + c + d
print(add(1, 2, 3)) # Output: 11
print(add(1)(2)(3)) # Output: 11
print(add(1, 2)(3, 4)) # Output: 10
# Example 2: Use functions (that take a function as an argument) like decorators
@curryable
def multiply_return(multiplier, func):
def multiplied(*args, **kwargs):
return func(*args, **kwargs) * multiplier
return multiplied
def triple_me(a, b):
return a + b
triple_me = multiply_return(3, triple_me)
print(triple_me(2, 3)) # Output: 15
@multiply_return(3)
def triple_me_too(a, b):
return a + b
print(triple_me_too(2, 3)) # Output: 15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment