Python decorators: example 4, expanding features with reduce

Let’s make something more useful in this 4th example of usage of python decorators. This time we will not only give more informations about the input, output and function’s operations, but we will add the chance to add or subtract (or easily divide or multiply creating other functions for that), using the decorators.

The code

We have two functions that add and subtracts two numbers.

def add(a, b):
    "Addition of a list of arguments"
    return a + b



def sub(a, b):
    "Subtraction of a list of arguments"
    return a - b

We want to add or subtract any number without changing anything in the code of the functions but using a decorator.

We use functools reduce

With reduce you can do that:

from functools import reduce


def add(a, b):
    return a + b


x = reduce(add, [1, 2, 3])
print(x)

# output: 6

We do not want to make it in every function that adds, subtracts, divides or multiply… so

Let’s do it with a decorator

from functools import reduce

def dec(operator=""):
    def features(fn):
        def add_some_decorations(*args):
            res = reduce(fn, *args)
            print(f"Result of {fn.__name__}: {res}")
            print(f"Operator: {operator}")
            print("Numbers: ", end="")
            print(*args)
            print()
            return res
        return add_some_decorations
    return features


@dec(operator="+")
def add(a, b):
    "Addition of a list of arguments"
    return a + b


@dec(operator="-")
def sub(a, b):
    "Subtraction of a list of arguments"
    return a - b


x = add([5, 2])

x = sub([1, 4])

This is the output:

Result of add: 7
Operator: +
Numbers: [5, 2]

Result of sub: -3
Operator: -
Numbers: [1, 4]


Subscribe to the newsletter for updates
Tkinter templates
Avatar My youtube channel

Twitter: @pythonprogrammi - python_pygame

Videos

Speech recognition game

Pygame's Platform Game

Other Pygame's posts

Published by pythonprogramming

Started with basic on the spectrum, loved javascript in the 90ies and python in the 2000, now I am back with python, still making some javascript stuff when needed.