Functools: partial and reduce

Github repo

You find this and other examples in this github repository.

Partial

With partial you gave a fixed value to an existing function so that you do not have to rewrite the original

Example

from functools import partial


def vat(price, percentage):
    return price * (100 + percentage) / 100


vat22 = partial(vat, percentage=22)
computer_price_plus_vat = vat22(1000)
print(computer_price_plus_vat)

out:

1220.0
>>>

 

Reduce

Reduce, from the module functools, lets you take a function with 2 arguments and use it with an iterable (ex: a list) to do with all the items of the iterable (list) what the function does with the 2 arguments. For example it can sum all the items in the list if the function sums the 2 arguments or can concatenate every string, if the original function concatenates two string.

Example

from functools import reduce


def join(a: str, b: str) -> str:
    return a + " " + b


result = reduce(join, ["I", "Love", "Python", "so", "much"])
print(result)

out:

I Love Python so much
>>>


Subscribe to the newsletter for updates
Tkinter templates
My youtube channel

Twitter: @pythonprogrammi - python_pygame

Videos

Speech recognition game

Pygame's Platform Game

Other Pygame's posts