11
def makebold(fn):
    def wrapped():
        return "<b>" + fn() + "</b>"
    return wrapped

def makeitalic(fn):
    def wrapped():
        return "<i>" + fn() + "</i>"
    return wrapped

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

print(hello()) ## returns "<b><i>hello world</i></b>"

In this code, why not just define the functions makeitalic() and makebold() and pass in the function hello?

Am I missing something here or are decorators really better for more complicated things?

1 Answer 1

8

In this code, why not just define the functions makeitalic() and makebold() and pass in the function hello?

You certainly could! Decorators are just syntactic sugar. Under the hood, what happens is:

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

becomes:

def hello():
    return "hello world"

hello = makebold(hello)
hello = makeitalic(hello)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, seems unnecessary in this case. I'm sure they offer concision in other use cases.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.