Introduction to Python code reading collection:Why not recommend Python beginners to directly look at the project source code
The code read in this article realizes the function of curry function.
In computer science, currying (English: currying), also translated as carrierization or gallization, is a technology that transforms a function that accepts multiple parameters into a function that accepts a single parameter (the first parameter of the initial function), and returns a new function that accepts the remaining parameters and returns the result.
The code snippet read in this article comes from30-seconds-of-python。
curry
from functools import partial
def curry(fn, *args):
return partial(fn,*args)
# EXAMPLES
add = lambda x, y: x + y
add10 = curry(add, 10)
add10(20) # 30
curry
The function receives an initial function and some parameters that accept multiple parameters, and returns a function that accepts a single parameter.
Function usefunctools.partial()
Generate a partial object. The behavior of this part of the object when called is similar tofn
Given that some parameters are called, the remaining parameters need to be provided.
Intuitively, Coriolis claims that “if you fix some parameters, you will get a function that accepts the remaining parameters”. So for a function with two variablesx+y
, if fixedy=2
, you get a function with one variablex+2
。
functools.partial(func, /, *args, **keywords)
Returns a new partial object that behaves like func with positional parameters when calledargs
And keyword parameterskeywords
Called. If more parameters are provided for the call, they are appended to theargs
。 If additional keyword parameters are provided, they are extended and overloadedkeywords
。 Roughly equivalent to:
def partial(func, /, *args, **keywords):
def newfunc(*fargs, **fkeywords):
newkeywords = {**keywords, **fkeywords}
return func(*args, *fargs, **newkeywords)
newfunc.func = func
newfunc.args = args
newfunc.keywords = keywords
return newfunc