« Back to Index

[Python Decorator Order]

View original Gist on GitHub

Tags: #python #decorator #order

Python Decorator Order.py

"""
Decorators are 'bottom up', meaning:

The bottom decorator is executed, and its result is
provided as input to the decorator above it.

In the below code this would look something like:

makebold(makeitalic(hello()))
"""

def makebold(fn):
    # fn == makeitalic(hello())
    def wrapped():
        return "<b>" + fn() + "</b>"
    return wrapped

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

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

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