“This is the 20th day of my participation in the First Challenge 2022. For details: First Challenge 2022”

preface

Python has a module called FuctionTools. This functools module provides many useful functions. The higher-order reduce function is in this module

The __all__ attribute list also contains a partial function, which is called a partial function. Notice that the partial function here is not the same as the partial function in the mathematical sense.

usage

There are default parameters in ordinary functions to accommodate and reduce the difficulty of parameter passing. Partial functions can also be used, for example:

Example 1

We create a function to handle different files. The default is to handle TXT files

def operator_file(file_name, file_type="txt"):
    if file_type=="txt":
       # do some thing
    if file_type=="pdf":
      # do some thing
    if file_type=="xls":
    ...

Copy the code

If you’re dealing with a large number of CSV files, and you want to be lazy and not have to call operator(file_name, “CSV “) every time, we might define a new function like this

def operator_csv(file_name, file_type="csv"):
    return  operator_file(file_name, file_type=file_type)
Copy the code

And then we’ll just call operator_CSV

If you use partial functions, you can skip creating a new function,

import functools
operator_csv = functools.partial(operator_file,  file_type="csv")
operator_csv(file_name)
Copy the code

Let’s actually experiment

conclusion

So the function of functools.partial is to fix some parameters of a function (that is, set defaults) and return a new function that is easier to call.

Note that the new operator_csv function simply resets the file_type parameter to CSV by default, but it can also pass in other values when the function is called. As you can see from the example, the partial function changes the default value of the original function to the default value of the newly defined function

csv_file = "111" txt_file = "222" operator_csv(csv_file) operator_csv(txt_file, CSV operator success TXT operator successCopy the code

Finally, when you create a partial function, you can actually take the function object, *args, and **kw.

operator_csv = functools.partial(operator_file, file_type="csv")
Copy the code

It actually fixes the operator_file() keyword argument file_type, which is:

operator_csv(file_name)
Copy the code

Is equivalent to:

kw = { 'file_type': "csv" }
operator_csv(file_name, **kw)
Copy the code

When a function has too many arguments and needs to be simplified, use functools.partial to create a new function that holds some of the arguments of the original function, making it easier to call.