Created
October 20, 2019 10:01
-
-
Save abersheeran/866ffbf9dc23b2f377cfd3fe96f6dcce to your computer and use it in GitHub Desktop.
currying 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
import typing | |
import inspect | |
import functools | |
def currying(func: typing.Callable) -> typing.Callable: | |
f = func | |
if inspect.ismethod(func): | |
partial = functools.partialmethod | |
else: | |
partial = functools.partial | |
@functools.wraps(func) | |
def wrapper(*args, **kwargs) -> typing.Any: | |
nonlocal f | |
if args or kwargs: | |
f = partial(f, *args, **kwargs) | |
return wrapper | |
return f() | |
return wrapper | |
@currying | |
def add(*args) -> int: | |
return sum(args) | |
class T: | |
@currying | |
def add(self, *args) -> int: | |
assert isinstance(self.add.__self__, T) | |
return sum(args) | |
print(add(1)(2)(3)(4)(5)()) | |
print(T().add(1)(2)(3)()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment