X
X
Xcopy2015-04-16 11:47:48
Python
Xcopy, 2015-04-16 11:47:48

What is currying (currying) used for in real tasks?

Hello!
I recently learned about such a thing as currying , in Python, currying in the simplest case can be written like this:

f = lambda y: lambda x: x + y
print f(2)(2)

Will output: 4
Could you give an example (preferably from life and in Python) where currying can be applied, otherwise I won’t know in what real situations it may be needed.
Thanks in advance for your reply!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vadim Shandrinov, 2015-04-16
@perminovma

Suppose there is a function that takes many parameters and the first parameter is the form class name (in django)

def cool_staff(form_class, inits, defaults, user, other_param):
    # много строчек кода

and you suddenly find that in your code there are a lot of calls that have the same first parameter.
...
res = cool_staff(form_class=MainForm, inits={a:1, b:3}, defaults=[1,2,3], ...)
...
res = cool_staff(form_class=MainForm, inits={a:100500, b:42}, defaults=[3,2,1], ...)
...

Then you do this:
and your calls are simplified
...
res = main_cool_staff(inits={a:1, b:3}, defaults=[1,2,3], ...)
...
res = main_cool_staff(inits={a:100500, b:42}, defaults=[3,2,1], ...)
...

was in a real project.
UPD. This form of currying will not work for unnamed parameters.
so use always named parameters, it's good style.
UPD2. Another suggested option
import functools
main_cool_staff = functools.partial(cool_staff, MainForm)

works with unnamed parameters too. Thanks Andrey Dugin

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question