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 "" + fn() + ""
  return wrapped
def makeitalic(fn):
def wrapped():
  return "" + fn() + ""
  return wrapped
@makebold @makeitalic
def hello():
  return "hello world"
print hello()
  

Output

  

C:/Users/codegyan/~.py
hello world 
  

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

How to make a chain of function decorators in Python?

Published on 03-Oct-2021 13:33:57

You may also like this!