Skip to content

Instantly share code, notes, and snippets.

@abersheeran
Created October 20, 2019 10:01
Show Gist options
  • Save abersheeran/866ffbf9dc23b2f377cfd3fe96f6dcce to your computer and use it in GitHub Desktop.
Save abersheeran/866ffbf9dc23b2f377cfd3fe96f6dcce to your computer and use it in GitHub Desktop.
currying in Python
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