HiveBrain v1.2.0
Get Started
← Back to all entries
snippetpythonCriticalCanonical

How do I make function decorators and chain them together?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
howfunctionanddecoratorstogetherthemmakechain

Problem

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

@make_bold
@make_italic
def say():
   return "Hello"


Calling say() should return:

"Hello"

Solution

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 wrapper(*args, **kwargs):
        return "" + fn(*args, **kwargs) + ""
    return wrapper

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

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

Code Snippets

from functools import wraps

def makebold(fn):
    @wraps(fn)
    def wrapper(*args, **kwargs):
        return "<b>" + fn(*args, **kwargs) + "</b>"
    return wrapper

def makeitalic(fn):
    @wraps(fn)
    def wrapper(*args, **kwargs):
        return "<i>" + fn(*args, **kwargs) + "</i>"
    return wrapper

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

Context

Stack Overflow Q#739654, score: 3103

Revisions (0)

No revisions yet.