Python | Making a chain of function decorators (bold italic underline etc)

def func_bold(fn):
    def wrapper(text):
        return "<b>" + fn(text) + "</b>"
    return wrapper

def func_italic(fn):
    def wrapper(text):
        return "<i>" + fn(text) + "</i>"
    return wrapper

def func_underline(fn):
    def wrapper(text):
        return "<u>" + fn(text) + "</u>"
    return wrapper


@func_bold
@func_italic
@func_underline
def get_text(text):
    return text

usrInput = input("Enter your input string: ")
print(get_text(usrInput))

Output:

Enter your input string: Hey there ! We are the masters of Python
<b><i><u>Hey there ! We are the masters of Python</u></i></b>

Explanation:

Here in this program, we defined three functions and in each function, we added the tags for bold, italic and underline respectively. A decorator is a design pattern in Python that enables you to change a function’s behaviour by enclosing it in another function. A modified version of the original function is returned by the outer function, which is referred to as the decorator. Applying several decorators inside of a function is known as chaining decorators. Python enables us to add several decorators to a function. Combining numerous effects, it makes decorators helpful for reusable building blocks.

Share:

Author: Dhvanil V