Partial Application With functools.partial
Learn how to create partial applications of functions using the partial function in the functools library.
We'll cover the following...
We'll cover the following...
functools.partial
function
The functools
module provides a function, partial
, that can be used to create a partial application of a function. Here is how you could use it to create a max0
function:
Press + to interact
Python 3.8
from functools import partialmax0 = partial(max, 0)print(max0(3)) # 3print(max0(-1)) # 0
Here is how you could use it with map
, similar to the previous example:
Press + to interact
Python 3.8
from functools import partialm = map(partial(max, 3), [1, 2, 3, 4, 5])print(list(m))
The advantage here is that you don’t have to define a separate closure, maxn
. The code is more ...