Python code reading (Chapter 45): coritization


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


from functools import partial

def curry(fn, *args):
  return partial(fn,*args)

add = lambda x, y: x + y
add10 = curry(add, 10)

add10(20) # 30

curryThe 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 tofnGiven 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 calledargsAnd keyword parameterskeywordsCalled. 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

Recommended Today

Concurrent programming: JMM

Hello, I’m Xiao Hei, a migrant worker who lives on the Internet. In the last issue, I shared some basic knowledge about threads in Java. In the example of thread termination, the first method says that to terminate a thread, you can use the flag bit method. Let’s review the code again. class MyRunnable implements […]