Last active
November 10, 2019 21:36
-
-
Save funketh/465d136480d79ab6b935400635362bc3 to your computer and use it in GitHub Desktop.
currying decorator in python
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 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