Created
August 21, 2016 14:34
-
-
Save jocke-l/40dcdc60560d0e7ab18c8fbc9d038163 to your computer and use it in GitHub Desktop.
Currying functions 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 inspect | |
def curry(func): | |
return Currying(func) | |
class Currying: | |
def __init__(self, function, args=None): | |
self._function = function | |
self._args = args or [] | |
self._num_args = len(inspect.signature(function).parameters) | |
def __repr__(self): | |
return '<{}: function={} args={} num_args={}>'.format( | |
type(self).__name__, | |
self._function.__name__, | |
self._args, | |
self._num_args | |
) | |
def __call__(self, *added_args): | |
new_args = self._args + list(added_args) | |
return Currying(self._function, new_args)._call_or_return_self() | |
def _call_or_return_self(self): | |
try: | |
return self._function(*self._args) | |
except TypeError: | |
if len(self._args) > self._num_args: | |
raise | |
return self | |
# >>> @curry | |
# ... def f(a, b, c): | |
# ... return c | |
# ... | |
# >>> f | |
# <Currying: function=f args=[] num_args=3> | |
# >>> f(1) | |
# <Currying: function=f args=[1] num_args=3> | |
# >>> f(1, 2) | |
# <Currying: function=f args=[1, 2] num_args=3> | |
# >>> f(1)(2) | |
# <Currying: function=f args=[1, 2] num_args=3> | |
# >>> f(1)(2, 3) | |
# 3 | |
# >>> f(1)(2)(3) | |
# 3 | |
# >>> f(1)(2)(3)(4) | |
# TypeError: f() takes 3 positional arguments but 4 were given |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment