Imran Imran - 1 year ago 65
Python Question

How can I make a chain of function decorators in Python?

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

def say():
return "Hello"

which should return


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

Answer Source

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

def hello():
    return "hello world"

print hello() ## returns "<b><i>hello world</i></b>"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download