How to make function decorators and chain them together

0 votes

How can I make two decorators in Python that would do the following?

@makebold
@makeitalic
def say():
   return "Hello"

...which should return:

"<b><i>Hello</i></b>"

I'm not trying to make HTML this way in a real application - just trying to understand how decorators and decorator chaining works.

Dec 4, 2020 in Python by anonymous
• 10,480 points
53 views

1 answer to this question.

0 votes

Here is what you asked for:

from functools import wraps

def makebold(fn):
    @wraps(fn)
    def wrapped(*args, **kwargs):
        return "<b>" + fn(*args, **kwargs) + "</b>"
    return wrapped

def makeitalic(fn):
    @wraps(fn)
    def wrapped(*args, **kwargs):
        return "<i>" + fn(*args, **kwargs) + "</i>"
    return wrapped

@makebold
@makeitalic
def hello():
    return "hello world"

@makebold
@makeitalic
def log(s):
    return s

print hello()        # returns "<b><i>hello world</i></b>"
print hello.__name__ # with functools.wraps() this returns "hello"
print log('hello')   # returns "<b><i>hello</i></b>"
answered Dec 4, 2020 by Gitika
• 65,910 points

Related Questions In Python

0 votes
1 answer

How to make a chain of function decorators?

Hello @kartik, Python decorators add extra functionality to ...READ MORE

answered Apr 13, 2020 in Python by Niroj
• 82,760 points
296 views
0 votes
1 answer

How to run a Function in Spyder and check output?

You will see the output of the ...READ MORE

answered May 17, 2019 in Python by Omkar
• 69,150 points
6,527 views
0 votes
1 answer
0 votes
2 answers
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 2,183 views
0 votes
0 answers
0 votes
4 answers

How to print objects of class using print function in Python?

>>> class Test: ... ...READ MORE

answered Dec 15, 2020 in Python by Roshni
• 10,480 points
51,748 views
0 votes
4 answers

how to sort a list of numbers without using built-in functions like min, max or any other function?

Yes it is possible. You can refer ...READ MORE

answered Jun 27, 2019 in Python by Arvind
• 3,000 points
45,407 views