Reputation: 617
I have used Haskell in the past so I understand it's usage and benefits there. But in Python, I'm struggling to see why I would ever want to curry (besides stylistic preferences). Posts here and sites like this usually mention that currying allows for function re-usability but I don't see it. The common example of:
def f(a, b):
return a + b
vs
def f(a):
def g(b):
return a + b
return g
doesn't seem to showcase any real benefit. In fact, the function nesting definition and even calling f(a)(b)
seems less clear then the 'standard' function definition. Can someone provide an example where currying showcases some net benefit?
Upvotes: 1
Views: 293
Reputation: 3599
I often curry functions when using the multiprocessing
module for running a function in parallel. Its pool.map()
requires the function to accept a single argument (the data being worked on) but I often need additional parameters that are invariant. For this, I create a partial version of the function using functools.partial
:
from functools import partial
from multiprocessing import Pool
def do_work(constant_param, variable_param):
context = setup_spam(constant_param)
return calc_eggs(context, variable_param)
pool = Pool()
inputs = [1, 2, 3]
partial_func = partial(do_work, "potatoes")
results = pool.map(partial_func, inputs)
This effectively does the following calls in parallel:
do_work("potatoes", 1)
do_work("potatoes", 2)
do_work("potatoes", 3)
Upvotes: 2