Associating Parameters with a Function (Currying)
Credit: Scott David Daniels, Ben Wolfson, Nick Perkins, and Alex Martelli
Problem
You need to tweak a function (or other callable) to get another callable with fewer formal arguments, keeping the original arguments’ given values fixed (i.e., you need to curry a callable to make another).
Solution
Curry is not just a spice used in Asian cuisine; it’s also an important technique in Python and other programming languages:
class curry:
def _ _init_ _(self, fun, *args, **kwargs):
self.fun = fun
self.pending = args[:]
self.kwargs = kwargs.copy( )
def _ _call_ _(self, *args, **kwargs):
if kwargs and self.kwargs:
kw = self.kwargs.copy( )
kw.update(kwargs)
else:
kw = kwargs or self.kwargs
return self.fun(*(self.pending + args), **kw)Discussion
Popular in functional programming, currying is a way to bind some of
the function’s arguments and wait for the rest of
the arguments to show up later. Currying is named in honor of
Haskell
Curry, a mathematician who laid some of the cornerstones in the
theory of formal systems and processes. The
curry function defined in this recipe is
called with a callable and some or all of the arguments to the
callable. The curry function returns a function
that takes subsequent parameters as arguments, and
curry calls the original with all of those
parameters. This recipe uses a class instance to hold the curried
parameters until they’re needed. For example:
double = curry(operator.mul, 2) triple = curry(operator.mul, ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access