# Use of Python partial()

2022-01-30 05:27:52 waws520

Today I'd like to introduce Python Partial functions in (functools.partial)

First , We need to simply understand the role of the lower partial function ： Like a decorator , It can extend the function function , But it is not equivalent to a decorator . The common application scenario is when we need to call a function frequently , Some of these parameters are known fixed values , Usually we can call this function more than once , But it looks like the code is redundant , The emergence of partial function is to solve this problem rarely . Take a very simple example , For example, I just want to know 100 What is the sum of any number , Usually our implementation is like this ：

``````#  The first way ：
return sum(args)

print(add(1, 2, 3) + 100)
print(add(5, 5, 5) + 100)

#  The second way
#  After adding the incoming values , Plus 100 return
return sum(args) + 100

print(add(1, 2, 3))  # 106
print(add(5, 5, 5))  # 115
Copy code ``````

See the code above , It seems quite simple , It's not very hard . But there are problems with both approaches ： The first one is ,100 This fixed value will return , The code always feels repetitive ; The second kind , When we want to modify 100 At this fixed value , We need to change add This method . Now let's take a look at parital How to achieve ：

``````from functools import partial

return sum(args)

print(add_100(1, 2, 3))  # 106

print(add_101(1, 2, 3))  # 107
Copy code ``````

Is it simple ~

After knowing about the example of partial function , Let's look at the definition of partial function ：

`````` class func = functools.partial(func, *args, **keywords)
Copy code ``````

We can see ,partial Must accept three parameters , From the previous example , We can also roughly know the role of these three parameters , A brief introduction ：

``````func:  Functions that need to be extended , The function returned is actually a class  func  Function of
*args:  Position parameters that need to be fixed
**kwargs:  Keyword parameters that need to be fixed
#  If in the original function  func  Keyword in does not exist , Will expand , If there is , It will cover
Copy code ``````

Use a simple example code containing location parameters and keyword parameters to illustrate the usage ：

``````#  It's also the code just summed , The difference is the keyword parameters added
#  Print position parameters
for n in args:
print(n)
print("-"*20)
#  Print keyword parameters
for k, v in kwargs.items():
print('%s:%s' % (k, v))
#  Do not return for the time being , Just look at the parameter effect , understand  partial  usage

#  Normal call
add(1, 2, 3, v1=10, v2=20)
""" 1 2 3 -------------------- v1:10 v2:20 """

# partial
add_partial(1, 2, 3, k3=20)
""" 10 1 2 3 -------------------- k1:10 k2:20 k3:20 """

add_partial(1, 2, 3, k1=20)
""" 10 1 2 3 -------------------- k1:20 k2:20 """
Copy code ``````

Last , Let's take a look at the explanation in the official documents , I believe with the previous Introduction , Look back at the official documents , It should be easier to understand , At the same time, it can also deepen our impression ：

functools.partial(func, *args, **keywords)
Return a new partial object which when called will behave like func called with the positional arguments args and keyword arguments keywords. If more arguments are supplied to the call, they are appended to args. If additional keyword arguments are supplied, they extend and override keywords. Roughly equivalent to:\

Simple translation : It returns a partial function object , This object and func equally , Can be called , At the same time, the location parameter can be specified when calling (args) and Key parameters ( *kwargs). If more positional parameters are provided, call , They will be attached to args in . If additional keyword parameters are provided , They will extend and overwrite the original keyword parameters . Its implementation is roughly equivalent to the following code ：

``````#  Define a function , It takes three parameters
def partial(func, *args, **keywords):
def newfunc(*fargs, **fkeywords):
newkeywords = keywords.copy()
newkeywords.update(fkeywords)
return func(*args, *fargs, **newkeywords)
newfunc.func = func
newfunc.args = args
newfunc.keywords = keywords
return newfunc
Copy code ``````

The partial() is used for partial function application which “freezes” some portion of a function’s arguments and/or keywords resulting in a new object with a simplified signature. For example, partial() can be used to create a callable that behaves like the int() function where the base argument defaults to two:\

Simple translation ：partial() Is used as “ frozen ” Some function parameters or keyword parameters , At the same time, an object with a new label will be generated ( That is, return a new function ). such as ,partial() It can be used to build a similar int() Function of , At the same time specified base Parameter is 2, The code is as follows ：

``````#  The code is simple , I won't go on and on
>>> from functools import partial
>>> basetwo = partial(int, base=2)
>>> basetwo.__doc__ = 'Convert base 2 string to an int.'
>>> basetwo('10010')
Copy code ``````

Now let's see if the document is very clear .