How to make a chain of function decorators?

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.

Apr 13 in Python by kartik
• 11,290 points
20 views

1 answer to this question.

0 votes

Hello @kartik,

Python decorators add extra functionality to another function

An italics decorator could be like

def makeitalic(fn):
    def newFunc():
        return "<i>" + fn() + "</i>"
    return newFunc

Note that a function is defined inside a function. What it basically does is replace a function with the newly defined one. For example, I have this class

class foo:
    def bar(self):
        print "hi"
    def foobar(self):
        print "hi again"

Now say, I want both functions to print "---" after and before they are done. I could add a print "---" before and after each print statement. But because I don't like repeating myself, I will make a decorator

def addDashes(fn): # notice it takes a function as an argument
    def newFunction(self): # define a new function
        print "---"
        fn(self) # call the original function
        print "---"
    return newFunction
    # Return the newly defined function - it will "replace" the original

So now I can change my class to

class foo:
    @addDashes
    def bar(self):
        print "hi"

    @addDashes
    def foobar(self):
        print "hi again"

Hope this works!!

answered Apr 13 by Niroj
• 22,790 points

Related Questions In Python

0 votes
2 answers
+2 votes
2 answers

How to make a laplacian pyramid using OpenCV python?

down voteacceptTheeThe problem is that you're iterating ...READ MORE

answered Apr 3, 2018 in Python by charlie_brown
• 7,760 points
2,328 views
0 votes
1 answer

how to find factorial of a number?

You can find factorial by many ways. ...READ MORE

answered May 4, 2018 in Python by aayushi
• 750 points
87 views
0 votes
2 answers

How to calculate square root of a number in python?

calculate square root in python >>> import math ...READ MORE

answered Apr 2, 2019 in Python by anonymous
515 views
+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 947 views
0 votes
0 answers
0 votes
1 answer

How to make a flat list out of list of lists?

Hii @kartik, Given a list of lists l, flat_list = ...READ MORE

answered Apr 13 in Python by Niroj
• 22,790 points
29 views
0 votes
1 answer

How to unzip a list of tuples into individual lists?

Hello @kartik, zip is its own inverse! Provided you ...READ MORE

answered Apr 23 in Python by Niroj
• 22,790 points
24 views