Skip to content

Instantly share code, notes, and snippets.

@jocke-l
Created August 21, 2016 14:34
Show Gist options
  • Save jocke-l/40dcdc60560d0e7ab18c8fbc9d038163 to your computer and use it in GitHub Desktop.
Save jocke-l/40dcdc60560d0e7ab18c8fbc9d038163 to your computer and use it in GitHub Desktop.
Currying functions in python
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