HOW CAN I MAKE A CHAIN OF FUNCTION DECORATORS IN PYTHON?

ezra heywood

Total Post:145

Points:1019
Posted by  ezra heywood
Python 
 817  View(s)
Ratings:
Rate this:
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.
  1. Mayank Tripathi

    Post:397

    Points:3117
    Re: How can I make a chain of function decorators in Python?

    Check out the documentation to see how decorators work. Here is what you asked for:

    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() ## returns <b><i>hello world</i></b>

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!