Wednesday 28 December 2016

python - How to make a chain of function decorators?




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



@makebold
@makeitalic
def say():
return "Hello"


...which should return:




"Hello"


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


Answer



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



from functools import wraps


def makebold(fn):
@wraps(fn)
def wrapped(*args, **kwargs):
return "" + fn(*args, **kwargs) + ""
return wrapped

def makeitalic(fn):
@wraps(fn)
def wrapped(*args, **kwargs):
return "" + fn(*args, **kwargs) + ""

return wrapped

@makebold
@makeitalic
def hello():
return "hello world"

@makebold
@makeitalic
def log(s):

return s

print hello() # returns "hello world"
print hello.__name__ # with functools.wraps() this returns "hello"
print log('hello') # returns "hello"

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...