Computer >> Computer tutorials >  >> Programming >> Python

How to make a chain of function decorators in Python?


Decorators are “wrappers”, which allow us to execute code before and after the function they decorate without modifying the function itself.

Example

The given code can be wrapped in a chain of decorators as follows.

def makebold(fn):
    def wrapped():
        return "<b>" + fn() + "</b>"
    return wrapped
def makeitalic(fn):
    def wrapped():
        return "<i>" + fn() + "</i>"
    return wrapped
@makebold
@makeitalic
def hello():
    return "hello world"
print hello()

Output

C:/Users/TutorialsPoint1/~.py
<b><i>hello world</i></b>

If this html code is executed as in the link given below we get the output  as bold and italicised 'hello world'