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
573 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,770 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,840 points
1,201 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,220 points
10,861 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 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,434 views
0 votes
1 answer
0 votes
4 answers

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

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

answered Dec 16, 2020 in Python by Roshni
• 10,480 points
78,511 views
+1 vote
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,050 points
188,462 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP