Python’s decorators with arguments

We have talked about decorators in python in this post. Now we will see how to use arguments into the decorators.

This is an example

def dec(personal):
    def features(fn):
        def add_some_decorations(a, b):
            res = fn(a, b)
            print(personal)
            print(fn.__doc__, f"{fn.__name__}({a}, {b}) - Output: " + str(res))
            return res
        return add_some_decorations
    return features


@dec("First function: Addition")
def add(a, b):
    "Addition of 2 arguments"
    return a + b


@dec("Second function: Subtraction")
def sub(a, b):
    "Subtraction of 2 arguments"
    return a - b


x = add(5, 2)
print(x)

x = sub(1, 4)
print(x)

The output

First function: Addition
Addition of 2 arguments add(5, 2) - Output: 7
7
Second function: Subtraction
Subtraction of 2 arguments sub(1, 4) - Output: -3
-3

Example nr. 2

A little more “sophisticated” usage of the decorator with more metadata of the functions using the decorators. In this case the decorator is used to explain what are the input and the output of the functions and how the function gets from the result.

def dec(operator=""):
    def features(fn):
        def add_some_decorations(a, b):
            res = fn(a, b)
            print("\n")
            print(f"Function: {fn.__name__}({a}, {b})")
            print("Operator: ", operator)
            print(fn.__doc__, ":", f"{a} and {b}")
            print("Return: ", end="")
            print(f"{a} {operator} {b}")
            print(f"Output: " + str(res))
            return res
        return add_some_decorations
    return features


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


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


x = add(5, 2)

x = sub(1, 4)

The output:

Function: add(5, 2)
Operator:  +
Addition of 2 arguments : 5 and 2
Return: 5 + 2
Output: 7


Function: sub(1, 4)
Operator:  -
Subtraction of 2 arguments : 1 and 4
Return: 1 - 4
Output: -3

 


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.