How to make a chain of function decorators?

Technology CommunityCategory: PythonHow to make a chain of function decorators?
VietMX Staff asked 3 years ago
Problem

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>"

Consider:

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>"